import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { XCircle } from 'lucide-react';
import { differenceInDays, format } from 'date-fns';
import { toast } from 'sonner';
import { RequestDateChange } from '@/components/RequestDateChange';

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

interface BookingActionsProps {
  order: any;
  queryKeys?: string[][];
}

export const BookingActions = ({ order, queryKeys = [] }: BookingActionsProps) => {
  const queryClient = useQueryClient();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState('');

  // VT e-learning orders have no schedule — they can be cancelled at any
  // time pre-completion and don't support "date change requests".
  const isOnlineOrder = !order.start_date;
  const daysUntilCourse = isOnlineOrder
    ? Number.POSITIVE_INFINITY
    : differenceInDays(new Date(order.start_date + 'T00:00:00'), new Date());
  const canCancel = ['pending', 'paid', 'confirmed'].includes(order.status) && daysUntilCourse >= 14;
  const hasPendingDateChange = !!order.pending_date_change;
  const canRequestDateChange = !isOnlineOrder
    && ['pending', 'paid', 'confirmed'].includes(order.status)
    && daysUntilCourse >= 1
    && !hasPendingDateChange;

  const invalidate = () => queryKeys.forEach((k) => queryClient.invalidateQueries({ queryKey: k }));

  const cancelMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch('/api/functions/process-refund', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          order_id: order.id,
          reason: cancelReason || 'Cancelled by user',
          action: 'cancel',
        }),
      });
      if (!res.ok) throw new Error('Failed to cancel');
      const data = await res.json();
      if (data?.error) throw new Error(data.error);
      return data;
    },
    onSuccess: () => {
      toast.success('Booking cancelled successfully');
      invalidate();
      setCancelOpen(false);
      setCancelReason('');
    },
    onError: (err: Error) => toast.error(err.message || 'Failed to cancel booking'),
  });

  if (!canCancel && !canRequestDateChange && !hasPendingDateChange) return null;

  return (
    <>
      <div className="flex gap-2 flex-wrap items-center">
        <RequestDateChange order={order} onSubmitted={invalidate} />
        {canCancel && (
          <Button
            variant="outline"
            size="sm"
            className="text-destructive border-destructive/30 hover:bg-destructive/10"
            onClick={() => setCancelOpen(true)}
          >
            <XCircle className="w-3.5 h-3.5 mr-1.5" /> Cancel Booking
          </Button>
        )}
      </div>

      <AlertDialog open={cancelOpen} onOpenChange={setCancelOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Cancel Booking?</AlertDialogTitle>
            <AlertDialogDescription>
              This will cancel your booking for <strong>{order.courses?.title || order.course?.title || 'this course'}</strong>
              {order.start_date
                ? <> on {format(new Date(order.start_date + 'T00:00:00'), 'EEE d MMM yyyy')}.</>
                : '.'}
              {!isOnlineOrder && daysUntilCourse >= 14 && ' Cancellations made more than 14 days before the course date are eligible for a full refund.'}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="py-2">
            <Label>Reason (optional)</Label>
            <Textarea
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
              placeholder="Why are you cancelling?"
              rows={2}
            />
          </div>
          <AlertDialogFooter>
            <AlertDialogCancel>Keep Booking</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={cancelMutation.isPending}
              onClick={() => cancelMutation.mutate()}
            >
              {cancelMutation.isPending ? 'Cancelling...' : 'Cancel Booking'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default BookingActions;
