import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { useState } from 'react';

interface DeletionStatusBannerProps {
  scheduledDate: string;
  onCancelled: () => void;
}

export function DeletionStatusBanner({ scheduledDate, onCancelled }: DeletionStatusBannerProps) {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const calculateDaysRemaining = () => {
    const scheduled = new Date(scheduledDate);
    const now = new Date();
    const diffTime = scheduled.getTime() - now.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return Math.max(0, diffDays);
  };

  const handleCancelDeletion = async () => {
    setLoading(true);
    try {
      const { error } = await supabase.functions.invoke('cancel-account-deletion', {
        body: { cancellation_reason: 'User cancelled from settings' },
      });

      if (error) throw error;

      toast({
        title: 'Deletion Cancelled',
        description: 'Your account has been reactivated.',
      });

      onCancelled();
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: 'Error',
        description: error.message || 'Failed to cancel deletion',
      });
    } finally {
      setLoading(false);
    }
  };

  const daysRemaining = calculateDaysRemaining();
  const formattedDate = new Date(scheduledDate).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  return (
    <Alert variant="destructive" className="mb-6">
      <AlertTriangle className="w-4 h-4" />
      <AlertTitle>Account Deletion Scheduled</AlertTitle>
      <AlertDescription className="space-y-2">
        <p>
          Your account is scheduled for permanent deletion on <strong>{formattedDate}</strong>.
        </p>
        <p className="text-sm">
          {daysRemaining > 0 ? (
            <>
              <strong>{daysRemaining}</strong> day{daysRemaining !== 1 ? 's' : ''} remaining to cancel.
            </>
          ) : (
            'You can now confirm deletion with your confirmation code.'
          )}
        </p>
        <div className="flex gap-2 mt-3">
          <Button
            variant="outline"
            size="sm"
            onClick={handleCancelDeletion}
            disabled={loading}
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
            Cancel Deletion
          </Button>
        </div>
      </AlertDescription>
    </Alert>
  );
}
