'use client';

import { useTransition } from 'react';

import { useRouter } from 'next/navigation';

import { XCircle } from 'lucide-react';
import { useTranslations } from 'next-intl';

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@kit/ui/alert-dialog';
import { Button } from '@kit/ui/button';

interface CancelBookingButtonProps {
  bookingId: string;
  accountId: string;
}

export function CancelBookingButton({
  bookingId,
  accountId,
}: CancelBookingButtonProps) {
  const router = useRouter();
  const t = useTranslations('bookings');
  const [isPending, startTransition] = useTransition();

  const handleCancel = () => {
    startTransition(async () => {
      try {
        const response = await fetch(`/api/bookings/${bookingId}/cancel`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ accountId }),
        });

        if (response.ok) {
          router.refresh();
        }
      } catch (error) {
        console.error('Failed to cancel booking:', error);
      }
    });
  };

  return (
    <AlertDialog>
      <AlertDialogTrigger
        render={
          <Button variant="destructive" disabled={isPending}>
            <XCircle className="mr-2 h-4 w-4" aria-hidden="true" />
            {t('cancel.confirm')}
          </Button>
        }
      />
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t('cancel.title')}</AlertDialogTitle>
          <AlertDialogDescription>
            {t('cancel.description')}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>{t('cancel.cancel')}</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleCancel}
            variant="destructive"
            disabled={isPending}
          >
            {isPending ? t('cancel.cancelling') : t('cancel.confirm')}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
