/**
 * components/auth/ForgotPasswordModal.tsx
 * Interactive modal dialog for sending Firebase password reset links to Gmail.
 */

"use client";

import { useState, useEffect } from "react";
import { Mail, ArrowRight, X, CheckCircle2, KeyRound, Loader2, RotateCw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import toast from "react-hot-toast";

interface ForgotPasswordModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialEmail?: string;
}

export function ForgotPasswordModal({
  isOpen,
  onClose,
  initialEmail = "",
}: ForgotPasswordModalProps) {
  const { forgotPassword } = useAuth();
  const [email, setEmail] = useState(initialEmail);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [cooldown, setCooldown] = useState(0);

  useEffect(() => {
    if (isOpen) {
      setEmail(initialEmail);
      setError("");
      setIsSubmitted(false);
    }
  }, [isOpen, initialEmail]);

  // Countdown timer for resend
  useEffect(() => {
    if (cooldown > 0) {
      const timer = setTimeout(() => setCooldown((c) => c - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [cooldown]);

  if (!isOpen) return null;

  const validate = () => {
    if (!email.trim()) {
      setError("Please enter your email address");
      return false;
    }
    if (!/\S+@\S+\.\S+/.test(email.trim())) {
      setError("Please enter a valid email address");
      return false;
    }
    setError("");
    return true;
  };

  const handleSend = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    setError("");
    try {
      await forgotPassword(email.trim());
      setIsSubmitted(true);
      setCooldown(60);
      toast.success("Password reset email sent!");
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Failed to send reset email";
      setError(msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
        onClick={onClose}
      />

      {/* Modal Card */}
      <div className="relative w-full max-w-md bg-white rounded-3xl shadow-2xl border border-slate-100 p-8 overflow-hidden z-10 animate-in fade-in zoom-in-95 duration-200">
        {/* Close Button */}
        <button
          type="button"
          onClick={onClose}
          className="absolute top-6 right-6 p-2 text-slate-400 hover:text-black rounded-full hover:bg-slate-100 transition-colors"
          aria-label="Close dialog"
        >
          <X className="h-5 w-5" />
        </button>

        {!isSubmitted ? (
          <div>
            {/* Header Icon */}
            <div className="h-12 w-12 rounded-2xl bg-indigo-50 border border-indigo-100/50 flex items-center justify-center mb-6">
              <KeyRound className="h-6 w-6 text-indigo-600" />
            </div>

            {/* Title & Description */}
            <h3 className="text-2xl font-black text-slate-900 tracking-tight mb-2">
              Reset Password
            </h3>
            <p className="text-slate-500 text-sm leading-relaxed mb-6">
              Enter your registered Gmail or email address and we&apos;ll send you a link to reset your password.
            </p>

            {/* Form */}
            <form onSubmit={handleSend} className="space-y-4">
              <Input
                id="reset-email"
                label="Email address"
                type="email"
                placeholder="you@gmail.com"
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  if (error) setError("");
                }}
                error={error}
                leftIcon={<Mail className="h-4 w-4" />}
                autoComplete="email"
                autoFocus
              />

              <div className="pt-2 flex flex-col gap-3">
                <Button
                  id="send-reset-submit"
                  type="submit"
                  fullWidth
                  loading={loading}
                  size="lg"
                  rightIcon={!loading && <ArrowRight className="h-4 w-4" />}
                >
                  Send Reset Link
                </Button>

                <button
                  type="button"
                  onClick={onClose}
                  className="text-xs font-bold text-slate-400 hover:text-slate-700 uppercase tracking-widest py-2 transition-colors"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        ) : (
          <div className="text-center py-2">
            {/* Success Icon */}
            <div className="h-16 w-16 rounded-full bg-emerald-50 border border-emerald-100 flex items-center justify-center mx-auto mb-5 text-emerald-600">
              <CheckCircle2 className="h-8 w-8" />
            </div>

            <h3 className="text-2xl font-black text-slate-900 tracking-tight mb-2">
              Check Your Email
            </h3>
            <p className="text-slate-500 text-sm leading-relaxed mb-6">
              We sent a password reset link to:
              <br />
              <span className="font-semibold text-slate-900 break-all">{email}</span>
            </p>

            <div className="bg-slate-50 border border-slate-100 rounded-2xl p-4 mb-6 text-left">
              <p className="text-xs text-slate-500 leading-relaxed">
                💡 <span className="font-semibold text-slate-700">Didn&apos;t receive it?</span> Check your Gmail <strong>Spam</strong> or <strong>Promotions</strong> folder, or wait a minute before requesting another link.
              </p>
            </div>

            <div className="flex flex-col gap-3">
              <Button
                id="reset-back-to-login"
                type="button"
                variant="primary"
                fullWidth
                size="lg"
                onClick={onClose}
              >
                Back to Sign In
              </Button>

              <button
                type="button"
                disabled={cooldown > 0 || loading}
                onClick={() => handleSend()}
                className="inline-flex items-center justify-center gap-2 text-xs font-bold text-indigo-600 hover:text-indigo-700 disabled:text-slate-400 uppercase tracking-widest py-2 transition-colors"
              >
                {loading ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : (
                  <RotateCw className="h-3.5 w-3.5" />
                )}
                {cooldown > 0 ? `Resend in ${cooldown}s` : "Resend reset link"}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
