"use client";

import { useState, useEffect, useRef } from "react";
import { Mail, Loader2, RefreshCw, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui";

type OtpVerificationFormProps = {
  email: string;
  onVerified?: () => void;
  className?: string;
};

export function OtpVerificationForm({ email, onVerified, className = "" }: OtpVerificationFormProps) {
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [timeLeft, setTimeLeft] = useState(600);
  const [canResend, setCanResend] = useState(false);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    if (timeLeft > 0 && !success) {
      const timer = setInterval(() => {
        setTimeLeft((prev) => {
          if (prev <= 1) {
            setCanResend(true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
      return () => clearInterval(timer);
    }
  }, [timeLeft, success]);

  useEffect(() => {
    if (inputRefs.current[0]) {
      inputRefs.current[0].focus();
    }
  }, []);

  function handleChange(index: number, value: string) {
    const digitsOnly = value.replace(/\D/g, "").slice(0, 1);
    const newOtp = [...otp];
    newOtp[index] = digitsOnly;
    setOtp(newOtp);

    if (digitsOnly && index < 5 && inputRefs.current[index + 1]) {
      inputRefs.current[index + 1]?.focus();
    }

    if (error) setError("");
  }

  function handleKeyDown(index: number, e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
    if (e.key === "Enter" && otp.every((digit) => digit)) {
      e.preventDefault();
      handleSubmit();
    }
  }

  function handlePaste(e: React.ClipboardEvent<HTMLInputElement>) {
    e.preventDefault();
    const pastedData = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
    const newOtp = [...otp];
    for (let i = 0; i < pastedData.length; i++) {
      newOtp[i] = pastedData[i];
    }
    setOtp(newOtp);

    const nextEmptyIndex = newOtp.findIndex((d) => !d);
    if (nextEmptyIndex !== -1) {
      inputRefs.current[nextEmptyIndex]?.focus();
    } else {
      inputRefs.current[5]?.focus();
    }
  }

  async function handleSubmit() {
    const otpCode = otp.join("");
    if (otpCode.length !== 6) {
      setError("Please enter all 6 digits");
      return;
    }

    setLoading(true);
    setError("");

    try {
      const response = await fetch("/api/auth/verify-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, otp: otpCode })
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || "Verification failed");
        setLoading(false);
        return;
      }

      setSuccess(true);
      onVerified?.();
    } catch (err) {
      setError("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  async function handleResend() {
    if (resending || !canResend) return;

    setResending(true);
    setError("");

    try {
      const response = await fetch("/api/auth/send-otp", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email })
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || "Failed to resend code");
        setResending(false);
        return;
      }

      setTimeLeft(600);
      setCanResend(false);
      setOtp(["", "", "", "", "", ""]);
      inputRefs.current[0]?.focus();
    } catch (err) {
      setError("Network error. Please try again.");
    } finally {
      setResending(false);
    }
  }

  function formatTime(seconds: number): string {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  }

  return (
    <div className={className}>
      {/* Email Display */}
      <div className="flex items-center gap-2 mb-4 p-3 bg-slate-100 rounded-lg">
        <Mail size={18} className="text-slate-500" />
        <span className="text-sm text-slate-700">{email}</span>
      </div>

      {/* OTP Input */}
      <div className="mb-4">
        <label className="block text-sm font-medium text-slate-700 mb-3">
          Enter verification code
        </label>
        <div className="flex gap-2 justify-between">
          {otp.map((digit, index) => (
            <input
              key={index}
              ref={(el) => { inputRefs.current[index] = el; }}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={digit}
              onChange={(e) => handleChange(index, e.target.value)}
              onKeyDown={(e) => handleKeyDown(index, e)}
              onPaste={handlePaste}
              className={`w-12 h-14 text-center text-2xl font-bold bg-white border-2 rounded-lg ${
                error ? "border-red-500 focus:border-red-500 focus:ring-red-500" : "border-slate-300 focus:border-amber-500 focus:ring-amber-500"
              } focus:outline-none transition-colors`}
              disabled={loading || success}
            />
          ))}
        </div>
      </div>

      {/* Messages */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-600 text-sm">{error}</p>
        </div>
      )}

      {success && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2">
          <CheckCircle2 size={18} className="text-green-600" />
          <p className="text-green-600 text-sm">Email verified successfully!</p>
        </div>
      )}

      {/* Timer & Resend */}
      <div className="mb-4 text-center">
        {timeLeft > 0 ? (
          <p className="text-slate-500 text-sm">
            Expires in <span className="font-mono font-semibold text-amber-600">{formatTime(timeLeft)}</span>
          </p>
        ) : (
          <p className="text-red-500 text-sm">Code expired</p>
        )}

        {canResend && (
          <button
            type="button"
            onClick={handleResend}
            disabled={resending}
            className="mt-2 text-amber-600 hover:text-amber-700 text-sm font-medium flex items-center gap-1 mx-auto disabled:opacity-50"
          >
            <RefreshCw size={14} className={resending ? "animate-spin" : ""} />
            {resending ? "Sending..." : "Resend code"}
          </button>
        )}
      </div>

      {/* Submit Button */}
      <Button
        onClick={handleSubmit}
        disabled={loading || success || otp.join("").length !== 6}
        className="w-full bg-amber-500 hover:bg-amber-600 text-white font-semibold h-12"
      >
        {loading ? (
          <>
            <Loader2 size={18} className="animate-spin mr-2" />
            Verifying...
          </>
        ) : success ? (
          "Verified!"
        ) : (
          "Verify Email"
        )}
      </Button>
    </div>
  );
}
