import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Progress } from '@/components/ui/progress';
import { Mail, Info, CheckCircle2, Circle, Loader2 } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { handleError, handleSuccess } from '@/lib/errorHandler';

interface EmailChangeStatusProps {
  currentEmail: string;
  pendingEmail: string;
  onCancel: () => void;
}

type EmailChangeData = {
  has_pending_change: boolean;
  current_email?: string;
  new_email?: string;
  current_email_verified?: boolean;
  new_email_verified?: boolean;
  change_sent_at?: string;
};

export function EmailChangeStatus({ 
  currentEmail, 
  pendingEmail, 
  onCancel 
}: EmailChangeStatusProps) {
  const [verificationStatus, setVerificationStatus] = useState({
    oldEmailVerified: false,
    newEmailVerified: false
  });
  const [loading, setLoading] = useState(true);
  const [resending, setResending] = useState(false);

  const checkVerificationStatus = async () => {
    try {
      const { data, error } = await supabase.rpc('get_email_change_status');
      
      if (error) throw error;

      const emailData = data as EmailChangeData;
      
      if (emailData.has_pending_change) {
        setVerificationStatus({
          oldEmailVerified: emailData.current_email_verified || false,
          newEmailVerified: emailData.new_email_verified || false
        });
      }
    } catch (error: unknown) {
      handleError(error, { action: 'Check verification status' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    checkVerificationStatus();
    // Poll every 30 seconds
    const interval = setInterval(checkVerificationStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  const handleResendVerification = async () => {
    setResending(true);
    try {
      const { error } = await supabase.auth.updateUser({ 
        email: pendingEmail 
      });
      
      if (error) throw error;
      
      handleSuccess(
        'Verification emails resent',
        'Check your inbox for the verification links.'
      );
    } catch (error: unknown) {
      handleError(error, { action: 'Resend verification emails' });
    } finally {
      setResending(false);
    }
  };

  const verificationProgress = 
    (verificationStatus.oldEmailVerified ? 50 : 0) +
    (verificationStatus.newEmailVerified ? 50 : 0);

  if (loading) {
    return (
      <Card className="border-blue-500/30">
        <CardContent className="flex items-center justify-center py-8">
          <Loader2 className="w-6 h-6 animate-spin" />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="border-blue-500/30">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Mail className="w-5 h-5 text-blue-500" />
          Email Change in Progress
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <Alert>
          <Info className="w-4 h-4" />
          <AlertDescription>
            To complete your email change, both emails must be verified.
          </AlertDescription>
        </Alert>

        {/* Progress indicator */}
        <div className="space-y-3">
          <div className="flex items-center gap-3">
            {verificationStatus.oldEmailVerified ? (
              <CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
            ) : (
              <Circle className="w-5 h-5 text-muted-foreground flex-shrink-0" />
            )}
            <div className="flex-1 min-w-0">
              <p className="font-medium">Current Email</p>
              <p className="text-sm text-muted-foreground truncate">{currentEmail}</p>
            </div>
            {verificationStatus.oldEmailVerified && (
              <Badge variant="secondary" className="bg-green-500/10 text-green-500">
                Verified
              </Badge>
            )}
          </div>

          <Separator />

          <div className="flex items-center gap-3">
            {verificationStatus.newEmailVerified ? (
              <CheckCircle2 className="w-5 h-5 text-green-500 flex-shrink-0" />
            ) : (
              <Circle className="w-5 h-5 text-muted-foreground flex-shrink-0" />
            )}
            <div className="flex-1 min-w-0">
              <p className="font-medium">New Email</p>
              <p className="text-sm text-muted-foreground truncate">{pendingEmail}</p>
            </div>
            {verificationStatus.newEmailVerified && (
              <Badge variant="secondary" className="bg-green-500/10 text-green-500">
                Verified
              </Badge>
            )}
          </div>
        </div>

        {/* Action buttons */}
        <div className="flex flex-col sm:flex-row gap-2">
          <Button
            variant="outline"
            onClick={handleResendVerification}
            disabled={resending}
            className="flex-1"
          >
            {resending ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Resending...
              </>
            ) : (
              'Resend Verification Emails'
            )}
          </Button>
          <Button
            variant="ghost"
            onClick={onCancel}
            className="text-destructive hover:text-destructive hover:bg-destructive/10"
          >
            Cancel Change
          </Button>
        </div>

        {/* Progress bar */}
        <div className="space-y-2">
          <div className="flex justify-between text-sm">
            <span className="text-muted-foreground">Progress</span>
            <span className="font-medium">{verificationProgress}%</span>
          </div>
          <Progress value={verificationProgress} className="h-2" />
        </div>
      </CardContent>
    </Card>
  );
}
