"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useAuth, normalizeRole } from "@/lib/stores/auth-store";
import { latinNumber } from "@/lib/utils";
import { User, KeyRound, Loader2 } from "lucide-react";

export default function SetupPage() {
  const { user, token, login, isAuthenticated } = useAuth();
  const router = useRouter();
  const [nationalId, setNationalId] = useState("");
  const [fullName, setFullName] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!isAuthenticated) {
      router.replace("/auth");
    }
  }, [isAuthenticated, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!nationalId || nationalId.length < 10) {
      setError("کد ملی معتبر وارد کنید");
      return;
    }
    if (!fullName || fullName.length < 3) {
      setError("نام و نام خانوادگی را وارد کنید");
      return;
    }
    if (!password || password.length < 4) {
      setError("رمز عبور حداقل ۴ کاراکتر باشد");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const res = await fetch("/api/users/me", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ nationalId, fullName, password }),
      });
      const data = await res.json();
      if (!data.success) {
        setError(data.message || "خطا در ذخیره اطلاعات");
        return;
      }

      // Fetch fresh user data from DB to get correct role
      const meRes = await fetch("/api/auth/me", {
        headers: { Authorization: `Bearer ${token}` },
      });
      const me = await meRes.json();

      login(token!, {
        ...user!,
        nationalId,
        fullName,
        role: me.role || user?.role,
        profile: me.profile || { ...user?.profile, fullName },
      });
      const role = normalizeRole(me.role || user?.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);
    }
  };

  if (!user) return null;

  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">
              <User className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-2xl font-bold text-gray-900">تکمیل اطلاعات</h1>
          <p className="text-gray-600 text-sm mt-2">
            برای ادامه، لطفاً اطلاعات زیر را تکمیل کنید
          </p>
        </div>

        <form onSubmit={handleSubmit} className="bg-white rounded-xl border p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              کد ملی
            </label>
            <input
              type="text"
              inputMode="numeric"
              placeholder="مثال: ۲۹۹۱۹۹۹۹۹۹"
              value={nationalId}
              onChange={(e) => setNationalId(latinNumber(e.target.value).replace(/\D/g, "").slice(0, 10))}
              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"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              نام و نام خانوادگی
            </label>
            <input
              type="text"
              placeholder="مثال: علی محمدی"
              value={fullName}
              onChange={(e) => setFullName(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"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1 flex items-center gap-1">
              <KeyRound className="h-4 w-4" />
              رمز عبور (برای ورودهای بعدی)
            </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"
              required
              minLength={4}
            />
          </div>

          {error && <p className="text-sm text-red-600">{error}</p>}

          <Button
            type="submit"
            className="w-full bg-[#2563EB] hover:bg-[#1D4ED8]"
            disabled={loading}
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin ml-1" /> : null}
            {loading ? "در حال ذخیره..." : "تکمیل اطلاعات"}
          </Button>
        </form>
      </div>
    </div>
  );
}
