"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { useAppTheme } from "@/components/ThemeProvider";
import { Input } from "@/components/ui/input";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Loader2, X, CheckCircle2 } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { verifyOtpSchema, type VerifyOtpInput } from "@/lib/schema/auth";
import { toast } from "sonner";

interface VerifyOtpDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  email: string;
  context?: "registration" | "password_reset";
  onVerificationSuccess?: () => void;
  title?: string;
  description?: string;
}

export function VerifyOtpDialog({ 
  open, 
  onOpenChange, 
  email: initialEmail,
  context = "registration",
  onVerificationSuccess,
  title = "Verify your email",
  description = "Enter the verification code sent to your email"
}: VerifyOtpDialogProps) {
  const { theme } = useAppTheme();
  const isDark = theme === "dark";
  const { verifyOtp, verifyOtpMutation, resendOtpMutation } = useAuth();
  const [otpData, setOtpData] = useState<VerifyOtpInput>({
    email: initialEmail,
    otp: "",
  });
  const [email, setEmail] = useState(initialEmail);
  const [otpSent, setOtpSent] = useState(false);
  const [isSendingOtp, setIsSendingOtp] = useState(false);

  // Update email when prop changes
  useEffect(() => {
    if (initialEmail) {
      setEmail(initialEmail);
      setOtpData(prev => ({ ...prev, email: initialEmail }));
    }
  }, [initialEmail]);

  // Automatically send OTP when dialog opens
  useEffect(() => {
    if (open && !otpSent) {
      const emailToSend = initialEmail || email;
      if (emailToSend) {
        setIsSendingOtp(true);
        resendOtpMutation.mutateAsync({ 
          email: emailToSend, 
          context 
        })
        .then(() => {
          toast.success("Verification code sent! Please check your email.");
          setOtpSent(true);
          setIsSendingOtp(false);
        })
        .catch((err) => {
          const errorMessage = err instanceof Error ? err.message : "Failed to send verification code";
          toast.error(errorMessage);
          setIsSendingOtp(false);
          // Still allow user to manually resend
        });
      }
    }
    
    // Reset when dialog closes
    if (!open) {
      setOtpSent(false);
      setIsSendingOtp(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, initialEmail, email, context, otpSent]);

  const handleVerifyOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const emailToVerify = email || otpData.email;
    if (!emailToVerify) {
      toast.error("Email address is required");
      return;
    }
    
    const validation = verifyOtpSchema.safeParse({
      email: emailToVerify,
      otp: otpData.otp,
    });
    
    if (!validation.success) {
      const firstError = validation.error.issues[0];
      toast.error(firstError.message);
      return;
    }
    
    try {
      const result = await verifyOtp({
        email: emailToVerify,
        otp: otpData.otp,
      });
      
      if (result.message || result.tokens) {
        toast.success("Email verified successfully!");
        // Reset form
        setOtpData({ email: emailToVerify, otp: "" });
        onOpenChange(false);
        // Call success callback if provided
        if (onVerificationSuccess) {
          onVerificationSuccess();
        }
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "OTP verification failed. Please try again.";
      toast.error(errorMessage);
    }
  };

  const handleResendOtp = async () => {
    const emailToResend = email || otpData.email;
    if (!emailToResend) {
      toast.error("Email address is required");
      return;
    }
    
    try {
      setIsSendingOtp(true);
      await resendOtpMutation.mutateAsync({ 
        email: emailToResend, 
        context 
      });
      toast.success("OTP resent successfully! Please check your email.");
      setOtpSent(true);
      setIsSendingOtp(false);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Failed to resend OTP";
      toast.error(errorMessage);
      setIsSendingOtp(false);
    }
  };

  const handleOtpChange = (field: keyof VerifyOtpInput, value: string) => {
    setOtpData((prev) => ({ ...prev, [field]: value }));
  };

  // Reset form when dialog closes
  const handleDialogChange = (isOpen: boolean) => {
    if (!isOpen) {
      setOtpData({ email: initialEmail || "", otp: "" });
      setOtpSent(false);
      setIsSendingOtp(false);
    }
    onOpenChange(isOpen);
  };

  return (
    <Dialog open={open} onOpenChange={handleDialogChange}>
      <DialogContent 
        showCloseButton={false}
        className={`max-w-md max-h-[90vh] overflow-hidden flex flex-col p-0 ${isDark ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}`}
      >
        {/* Header with Close Button - Fixed */}
        <div className="flex items-start justify-between p-6 pb-4 flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
          <DialogHeader className="flex-1 pr-2">
            <DialogTitle className="text-2xl sm:text-3xl font-bold bg-gradient-to-r from-rose-600 via-pink-600 to-rose-600 bg-clip-text text-transparent">
              {title}
            </DialogTitle>
            <DialogDescription className={`text-sm sm:text-base mt-1 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
              {description}
            </DialogDescription>
          </DialogHeader>
          {/* Close Button */}
          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={() => handleDialogChange(false)}
            className={`flex-shrink-0 w-8 h-8 rounded-full ${isDark ? 'text-gray-400 hover:text-gray-300 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'}`}
            aria-label="Close"
          >
            <X className="w-5 h-5" />
          </Button>
        </div>

        {/* Scrollable Content */}
        <div className="overflow-y-auto flex-1 px-6">
          <form className="space-y-4 sm:space-y-5 py-4 sm:py-6" onSubmit={handleVerifyOtp}>
            {/* Loading indicator while sending */}
            {isSendingOtp && !otpSent && (
              <div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-yellow-900/20 border-yellow-800' : 'bg-yellow-50 border-yellow-200'}`}>
                <div className="flex items-center gap-3">
                  <Loader2 className="w-5 h-5 animate-spin text-yellow-600" />
                  <p className={`text-sm font-medium ${isDark ? 'text-yellow-200' : 'text-yellow-900'}`}>
                    Sending verification code...
                  </p>
                </div>
              </div>
            )}

            {/* Success message after sending */}
            {otpSent && (
              <div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-blue-900/20 border-blue-800' : 'bg-blue-50 border-blue-200'}`}>
                <div className="flex items-start gap-3">
                  <CheckCircle2 className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-blue-400' : 'text-blue-600'}`} />
                  <div>
                    <p className={`text-sm font-medium ${isDark ? 'text-blue-200' : 'text-blue-900'}`}>
                      Check your email
                    </p>
                    <p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-blue-300' : 'text-blue-700'}`}>
                      We've sent a 6-digit verification code to {email || otpData.email || "your email address"}.
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Show info message if OTP hasn't been sent yet but dialog is open */}
            {!isSendingOtp && !otpSent && (
              <div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-blue-900/20 border-blue-800' : 'bg-blue-50 border-blue-200'}`}>
                <div className="flex items-start gap-3">
                  <CheckCircle2 className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-blue-400' : 'text-blue-600'}`} />
                  <div>
                    <p className={`text-sm font-medium ${isDark ? 'text-blue-200' : 'text-blue-900'}`}>
                      Enter verification code
                    </p>
                    <p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-blue-300' : 'text-blue-700'}`}>
                      Enter the 6-digit verification code sent to {email || otpData.email || "your email address"}.
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Email Field (if not provided or editable) */}
            {!initialEmail && (
              <div className="space-y-1.5 sm:space-y-2">
                <label htmlFor="verify-email" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                  Email address *
                </label>
                <Input
                  id="verify-email"
                  type="email"
                  placeholder="Email address"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    handleOtpChange("email", e.target.value);
                  }}
                  className={`h-11 sm:h-12 text-sm sm:text-base ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'}`}
                  required
                />
              </div>
            )}

            {/* OTP Field */}
            <div className="space-y-1.5 sm:space-y-2">
              <label className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
                Verification Code *
              </label>
              <div className="flex justify-center">
                <InputOTP
                  maxLength={6}
                  value={otpData.otp}
                  onChange={(value) => handleOtpChange("otp", value)}
                >
                  <InputOTPGroup className="gap-2 sm:gap-3">
                    <InputOTPSlot index={0} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                    <InputOTPSlot index={1} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                    <InputOTPSlot index={2} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                    <InputOTPSlot index={3} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                    <InputOTPSlot index={4} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                    <InputOTPSlot index={5} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
                  </InputOTPGroup>
                </InputOTP>
              </div>
            </div>

            {/* Resend OTP */}
            <div className="text-center">
              <Button
                type="button"
                variant="link"
                onClick={handleResendOtp}
                disabled={resendOtpMutation.isPending}
                className={`h-auto p-0 text-xs sm:text-sm font-medium ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'}`}
              >
                {resendOtpMutation.isPending ? "Sending..." : "Didn't receive the code? Resend"}
              </Button>
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={verifyOtpMutation.isPending}
              className="w-full h-11 sm:h-12 text-sm sm:text-base font-semibold bg-gradient-to-r from-rose-500 to-pink-600 hover:from-rose-600 hover:to-pink-700 text-white shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed mt-4 sm:mt-6"
            >
              {verifyOtpMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Verifying...
                </>
              ) : (
                "Verify Email"
              )}
            </Button>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  );
}

