"use client";

import { signIn } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useState, useEffect } from "react";
import { LogIn, Mail, AlertCircle } from "lucide-react";
import { Button, Input, Label } from "@/components/ui";
import type { Locale } from "@/lib/i18n";

const labels = {
  en: {
    email: "Email",
    password: "Password",
    invalidLogin: "Invalid email or password.",
    notVerified: "Please verify your email first. Check your inbox for the verification code.",
    signingIn: "Signing in...",
    signIn: "Sign in",
    resendCode: "Resend verification code"
  },
  ar: {
    email: "البريد الإلكتروني",
    password: "كلمة المرور",
    invalidLogin: "بيانات الدخول غير صحيحة.",
    notVerified: "يرجى التحقق من بريدك الإلكتروني أولاً. تحقق من صندوق الوارد للحصول على رمز التحقق.",
    signingIn: "جاري الدخول...",
    signIn: "دخول",
    resendCode: "إعادة إرسال رمز التحقق"
  }
} as const;

export function LoginForm({ locale, callbackUrl = "/dashboard" }: { locale: Locale; callbackUrl?: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [needsVerification, setNeedsVerification] = useState(false);
  const [verificationEmail, setVerificationEmail] = useState("");
  const [resending, setResending] = useState(false);
  const t = labels[locale];

  // Check if user just registered
  useEffect(() => {
    if (searchParams.get("registered") === "true") {
      setError("Account created! Please verify your email to continue.");
    }
  }, [searchParams]);

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoading(true);
    setError("");
    setNeedsVerification(false);
    const formData = new FormData(event.currentTarget);
    const email = formData.get("email") as string;
    const password = formData.get("password") as string;

    const result = await signIn("credentials", {
      email,
      password,
      redirect: false
    });
    setLoading(false);

    if (result?.error) {
      // Check if error is due to unverified email
      if (result.error === "OTP_VERIFICATION_REQUIRED" ||
          result.error === "Please verify your email first") {
        setNeedsVerification(true);
        setVerificationEmail(email);
        setError(t.notVerified);
      } else {
        setError(t.invalidLogin);
      }
      return;
    }

    router.push(callbackUrl);
    router.refresh();
  }

  async function handleResendOtp() {
    if (!verificationEmail || resending) return;

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

      const data = await response.json();

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

      // Redirect to OTP verification page
      router.push(`/register/verify-otp?email=${encodeURIComponent(verificationEmail)}`);
    } catch (err) {
      setError("Network error. Please try again.");
    } finally {
      setResending(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div>
        <Label htmlFor="email">{t.email}</Label>
        <Input id="email" name="email" type="email" autoComplete="email" required disabled={loading} />
      </div>
      <div>
        <Label htmlFor="password">{t.password}</Label>
        <Input id="password" name="password" type="password" autoComplete="current-password" required disabled={loading} />
      </div>

      {error && (
        <div className={`rounded-md px-3 py-2 text-sm flex items-start gap-2 ${
          needsVerification ? "bg-amber-50 text-amber-700" : "bg-red-50 text-red-700"
        }`}>
          {needsVerification ? (
            <Mail size={16} className="mt-0.5 shrink-0" />
          ) : (
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
          )}
          <div className="flex-1">
            <p>{error}</p>
            {needsVerification && (
              <button
                type="button"
                onClick={handleResendOtp}
                disabled={resending}
                className="mt-2 text-sm font-medium underline hover:no-underline disabled:opacity-50"
              >
                {resending ? "Sending..." : t.resendCode}
              </button>
            )}
          </div>
        </div>
      )}

      <Button className="w-full" disabled={loading}>
        {loading ? (
          <>
            <LogIn size={16} className="animate-spin mr-2" />
            {t.signingIn}
          </>
        ) : (
          <>
            <LogIn size={16} className="mr-2" />
            {t.signIn}
          </>
        )}
      </Button>
    </form>
  );
}
