"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { sendOtp, verifyOtp } from "@/lib/api/auth";
import { useAuth, normalizeRole } from "@/lib/stores/auth-store";
import { latinNumber } from "@/lib/utils";
import { ArrowLeft, Phone, ShieldCheck, KeyRound, Loader2 } from "lucide-react";
import Link from "next/link";

export default function AuthPage() {
  const [step, setStep] = useState<"phone" | "otp" | "password">("phone");
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const { login } = useAuth();
  const router = useRouter();

  const handleSendOtp = async () => {
    if (!phone || phone.length < 10) {
      setError("شماره موبایل معتبر وارد کنید");
      return;
    }
    setLoading(true);
    setError("");
    try {
      await sendOtp(phone);
      setStep("otp");
    } catch (e) {
      setError(e instanceof Error ? e.message : "خطا در ارسال کد");
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async () => {
    if (!code || code.length < 4) {
      setError("کد تایید را وارد کنید");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const res = await verifyOtp(phone, code);
      const normalizedUser = { ...res.user, role: normalizeRole(res.user.role) };
      login(res.token, normalizedUser);
      if (!normalizedUser.nationalId || !normalizedUser.fullName) {
        router.push("/auth/setup");
        return;
      }
      const role = normalizedUser.role;
      if (role === "SUPER_ADMIN") router.push("/dashboard/superadmin");
      else if (role === "ADMIN") router.push("/dashboard/admin");
      else if (role === "COACH") router.push("/dashboard/coach");
      else if (role === "JUDGE") router.push("/dashboard/judge");
      else router.push("/dashboard/athlete");
    } catch (e) {
      setError(e instanceof Error ? e.message : "کد نامعتبر است");
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordLogin = async () => {
    if (!phone || phone.length < 10) {
      setError("شماره موبایل معتبر وارد کنید");
      return;
    }
    if (!password) {
      setError("رمز عبور را وارد کنید");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone, password }),
      });
      const data = await res.json();
      if (!res.ok) {
        if (data.hasOtpOption) {
          setError(data.message);
          setStep("otp");
          setPassword("");
          return;
        }
        setError(data.message || "خطا در ورود");
        return;
      }
      const normalizedUser = { ...data.user, role: normalizeRole(data.user.role) };
      login(data.token, normalizedUser);
      if (!normalizedUser.nationalId || !normalizedUser.fullName) {
        router.push("/auth/setup");
        return;
      }
      const role = normalizedUser.role;
      if (role === "SUPER_ADMIN") router.push("/dashboard/superadmin");
      else if (role === "ADMIN") router.push("/dashboard/admin");
      else if (role === "COACH") router.push("/dashboard/coach");
      else if (role === "JUDGE") router.push("/dashboard/judge");
      else router.push("/dashboard/athlete");
    } catch {
      setError("خطا در ارتباط با سرور");
    } finally {
      setLoading(false);
    }
  };

  const phoneValid = phone.length >= 10;

  const Icon = step === "phone" ? Phone : step === "otp" ? ShieldCheck : KeyRound;
  const title = step === "phone" ? "ورود / ثبت‌نام" : step === "otp" ? "کد تایید" : "ورود با رمز عبور";

  return (
    <div className="min-h-[80vh] flex items-center justify-center py-12 px-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <div className="w-16 h-16 rounded-2xl bg-[#2563EB] flex items-center justify-center">
              <Icon className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-2xl font-bold text-gray-900">{title}</h1>
          <p className="text-gray-600 text-sm mt-2">
            {step === "phone"
              ? "شماره موبایل خود را وارد کنید"
              : step === "otp"
              ? `کد تایید به شماره ${phone} ارسال شد`
              : `ورود با رمز عبور برای ${phone}`}
          </p>
        </div>

        <div className="bg-white rounded-xl border p-6 space-y-4">
          {step === "phone" && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  شماره موبایل
                </label>
                <input
                  type="tel"
                  inputMode="numeric"
                  placeholder="مثال: ۰۹۱۲۳۴۵۶۷۸۹"
                  value={phone}
                  onChange={(e) => setPhone(latinNumber(e.target.value))}
                  className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB] focus:border-transparent"
                  dir="ltr"
                />
              </div>
              {error && <p className="text-sm text-red-600">{error}</p>}
              <div className="flex flex-col gap-3">
                <Button
                  className="w-full bg-[#2563EB] hover:bg-[#1D4ED8] flex items-center justify-center gap-2"
                  onClick={() => setStep("password")}
                  disabled={loading || !phoneValid}
                >
                  <KeyRound className="h-4 w-4" />
                  ورود با رمز عبور
                </Button>
                <Button
                  className="w-full bg-white text-[#2563EB] border border-[#2563EB] hover:bg-blue-50 flex items-center justify-center gap-2"
                  onClick={handleSendOtp}
                  disabled={loading || !phoneValid}
                >
                  {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <ShieldCheck className="h-4 w-4" />}
                  {loading ? "در حال ارسال..." : "ورود با کد تایید"}
                </Button>
              </div>
            </>
          )}

          {step === "password" && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  رمز عبور
                </label>
                <input
                  type="password"
                  placeholder="رمز عبور خود را وارد کنید"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB] focus:border-transparent"
                  onKeyDown={(e) => e.key === "Enter" && handlePasswordLogin()}
                />
              </div>
              {error && <p className="text-sm text-red-600">{error}</p>}
              <Button
                className="w-full bg-[#2563EB] hover:bg-[#1D4ED8]"
                onClick={handlePasswordLogin}
                disabled={loading}
              >
                {loading ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : null}
                {loading ? "در حال بررسی..." : "ورود"}
              </Button>
              <Button
                variant="ghost"
                className="w-full flex items-center justify-center gap-1"
                onClick={() => { setStep("phone"); setPassword(""); setError(""); }}
              >
                <ArrowLeft className="h-4 w-4" />
                بازگشت
              </Button>
              <div className="text-center">
                <button
                  onClick={() => { setStep("otp"); setPassword(""); setError(""); handleSendOtp(); }}
                  className="text-sm text-[#2563EB] hover:underline"
                >
                  ورود با کد تایید
                </button>
              </div>
            </>
          )}

          {step === "otp" && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  کد تایید
                </label>
                <input
                  type="text"
                  inputMode="numeric"
                  placeholder="کد ۱۲۳۴"
                  value={code}
                  onChange={(e) => setCode(latinNumber(e.target.value))}
                  className="w-full px-3 py-2.5 border rounded-lg text-sm text-center text-lg tracking-widest focus:outline-none focus:ring-2 focus:ring-[#2563EB] focus:border-transparent"
                  dir="ltr"
                />
              </div>
              {error && <p className="text-sm text-red-600">{error}</p>}
              <Button
                className="w-full bg-[#2563EB] hover:bg-[#1D4ED8]"
                onClick={handleVerifyOtp}
                disabled={loading}
              >
                {loading ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : null}
                {loading ? "در حال بررسی..." : "تایید"}
              </Button>
              <Button
                variant="ghost"
                className="w-full"
                onClick={() => { setStep("phone"); setCode(""); setError(""); }}
              >
                <ArrowLeft className="h-4 w-4 ml-1" />
                ویرایش شماره موبایل
              </Button>
              <div className="text-center">
                <button
                  onClick={() => { setStep("password"); setCode(""); setError(""); }}
                  className="text-sm text-[#2563EB] hover:underline"
                >
                  ورود با رمز عبور
                </button>
              </div>
            </>
          )}
        </div>

        <p className="text-xs text-gray-500 text-center mt-4">
          با ورود به سامانه، <Link href="/about" className="text-[#2563EB] hover:underline">قوانین و مقررات</Link> را می‌پذیرید.
        </p>
      </div>
    </div>
  );
}
