import { AlertTriangle, CreditCard } from 'lucide-react';

import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { trackEvent } from '@/lib/analytics';
import { DUNNING_MODAL_DISMISSED, DUNNING_MODAL_UPDATE_CLICKED } from '@/lib/event-catalog';

interface PaymentFailedModalProps {
  open: boolean;
  onDismiss: () => void;
  portalUrl: string;
  daysInDunning: number;
}

export function PaymentFailedModal({
  open,
  onDismiss,
  portalUrl,
  daysInDunning,
}: PaymentFailedModalProps) {
  const handleUpdatePayment = () => {
    trackEvent(DUNNING_MODAL_UPDATE_CLICKED, { days_in_dunning: daysInDunning });
    window.location.href = portalUrl;
  };

  const handleDismiss = () => {
    trackEvent(DUNNING_MODAL_DISMISSED, { days_in_dunning: daysInDunning });
    onDismiss();
  };

  return (
    <Dialog open={open} onOpenChange={(isOpen) => !isOpen && handleDismiss()}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30">
            <AlertTriangle className="h-6 w-6 text-red-600 dark:text-red-400" />
          </div>
          <DialogTitle className="text-center">Payment Failed</DialogTitle>
          <DialogDescription className="text-center">
            Your last payment didn&apos;t go through. Update your payment method to keep your Pro
            features active.
          </DialogDescription>
        </DialogHeader>

        <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-950/50">
          <p className="text-sm text-red-800 dark:text-red-200">
            {daysInDunning > 0 ? (
              <>
                Your payment has been overdue for{' '}
                <strong>
                  {daysInDunning} day{daysInDunning !== 1 ? 's' : ''}
                </strong>
                . If not resolved, your subscription will be downgraded to the Free plan.
              </>
            ) : (
              <>
                Please update your payment method as soon as possible to avoid any interruption to
                your service.
              </>
            )}
          </p>
        </div>

        <DialogFooter className="flex-col gap-2 sm:flex-col">
          <Button onClick={handleUpdatePayment} className="w-full gap-2">
            <CreditCard className="h-4 w-4" />
            Update Payment Method
          </Button>
          <Button variant="ghost" onClick={handleDismiss} className="w-full text-muted-foreground">
            Remind me later
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
