"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiFetch } from "@/lib/client-utils";
import { GraduationCap, Lock, User, Loader2, ShieldCheck, KeyRound, Phone, Copy, ArrowRight } from "lucide-react";

interface LoginViewProps {
  onLogin: (user: { id: string; username: string; fullName: string; role: string }) => void;
  schoolNameAr: string;
}

type SessionUser = { id: string; username: string; fullName: string; role: string };

export default function LoginView({ onLogin, schoolNameAr }: LoginViewProps) {
  const [setupRequired, setSetupRequired] = useState<boolean | null>(null);
  const [checkingSetup, setCheckingSetup] = useState(true);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [setupKey, setSetupKey] = useState("");
  const [phone, setPhone] = useState("");
  const [recoveryMode, setRecoveryMode] = useState(false);
  const [recoveryCode, setRecoveryCode] = useState("");
  const [recoveryPassword, setRecoveryPassword] = useState("");
  const [recoveryConfirm, setRecoveryConfirm] = useState("");
  const [visibleRecoveryCode, setVisibleRecoveryCode] = useState("");
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let active = true;
    apiFetch<{ setupRequired: boolean }>("/api/auth/setup-status")
      .then((result) => { if (active) setSetupRequired(result.setupRequired); })
      .catch((err) => { if (active) setError(err instanceof Error ? err.message : "تعذر فحص إعداد النظام"); })
      .finally(() => { if (active) setCheckingSetup(false); });
    return () => { active = false; };
  }, []);

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const data = await apiFetch<{ user: SessionUser }>("/api/auth/login", {
        method: "POST",
        body: JSON.stringify({ username, password }),
      });
      onLogin(data.user);
    } catch (err) {
      setError(err instanceof Error ? err.message : "فشل تسجيل الدخول");
    } finally {
      setLoading(false);
    }
  }

  async function handleSetup(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (password !== confirmPassword) {
      setError("تأكيد كلمة المرور غير مطابق");
      return;
    }
    setLoading(true);
    try {
      const result = await apiFetch<{ success: boolean; recoveryCode: string }>("/api/auth/setup", {
        method: "POST",
        body: JSON.stringify({ setupKey, username, password, confirmPassword, phone }),
      });
      setSetupRequired(false);
      setNotice("تم إنشاء مدير النظام. سجّل الدخول بالبيانات التي اخترتها.");
      setSetupKey("");
      setVisibleRecoveryCode(result.recoveryCode);
    } catch (err) {
      setError(err instanceof Error ? err.message : "تعذر إنشاء مدير النظام");
    } finally {
      setLoading(false);
    }
  }

  async function handleRecover(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (recoveryPassword !== recoveryConfirm) { setError("تأكيد كلمة المرور غير مطابق"); return; }
    setLoading(true);
    try {
      const result = await apiFetch<{ recoveryCode: string }>("/api/auth/recover", {
        method: "POST",
        body: JSON.stringify({ phone, recoveryCode, password: recoveryPassword }),
      });
      setVisibleRecoveryCode(result.recoveryCode);
      setNotice("تم تغيير كلمة المرور. احفظ رمز الاسترداد الجديد قبل متابعة الدخول.");
      setRecoveryMode(false);
      setRecoveryCode("");
      setRecoveryPassword("");
      setRecoveryConfirm("");
    } catch (err) {
      setError(err instanceof Error ? err.message : "تعذر استرداد الحساب");
    } finally {
      setLoading(false);
    }
  }

  const isSetup = setupRequired === true;

  return (
    <div className="min-h-screen flex flex-col lg:flex-row">
      <div className="lg:flex-1 bg-gradient-to-br from-primary via-teal-800 to-emerald-950 text-primary-foreground p-8 lg:p-14 flex flex-col justify-between relative overflow-hidden">
        <div className="absolute -top-24 -left-24 w-72 h-72 rounded-full bg-white/10 animate-pulse" aria-hidden />
        <div className="absolute bottom-0 right-0 w-96 h-96 rounded-full bg-white/5 translate-y-1/3" aria-hidden />
        <div className="relative z-10">
          <div className="flex items-center gap-3 mb-10">
            <div className="w-14 h-14 rounded-2xl bg-white/15 flex items-center justify-center backdrop-blur"><GraduationCap className="w-8 h-8" /></div>
            <div><h1 className="text-2xl font-bold leading-tight">{schoolNameAr}</h1><p className="text-sm text-primary-foreground/80 font-medium">نظام إدارة الشؤون المالية والطلابية</p></div>
          </div>
          <h2 className="text-3xl lg:text-4xl font-extrabold leading-snug mb-4 tracking-tight">إدارة ذكية وسريعة<br />للأقساط والإيرادات والتقارير</h2>
          <p className="text-primary-foreground/85 leading-relaxed max-w-lg mb-8">نظام متكامل لتسجيل الطلبة ومتابعة الأقساط والإيرادات والمصروفات، مع تقارير قابلة للتصدير وسجل حركات آمن.</p>
          <ul className="grid grid-cols-2 gap-3 max-w-lg text-sm">
            {["دفع مباشر سريع", "أكواد طلبة تلقائية", "ميزانية لحظية", "صلاحيات متعددة"].map((f) => <li key={f} className="flex items-center gap-2 bg-white/10 rounded-lg px-3 py-2 backdrop-blur"><ShieldCheck className="w-4 h-4 shrink-0" /><span>{f}</span></li>)}
          </ul>
        </div>
        <p className="relative z-10 text-xs text-primary-foreground/60 mt-10">School Finance &amp; Student Management System · Responsive Web App</p>
      </div>

      <div className="lg:w-[460px] flex items-center justify-center p-6 bg-background">
        <Card className="w-full max-w-md border-white/60 shadow-2xl shadow-emerald-950/10">
          <CardHeader className="text-center">
            <div className="mx-auto w-12 h-12 rounded-xl bg-primary/10 text-primary flex items-center justify-center mb-2">{isSetup ? <KeyRound className="w-6 h-6" /> : <Lock className="w-6 h-6" />}</div>
            <CardTitle className="text-xl font-bold">{checkingSetup ? "جارٍ تجهيز النظام" : isSetup ? "إنشاء مدير النظام" : recoveryMode ? "استرداد كلمة المرور" : "تسجيل الدخول"}</CardTitle>
            <CardDescription>{checkingSetup ? "يرجى الانتظار قليلًا" : isSetup ? "هذه أول مرة؛ أنشئ حساب مدير النظام للبدء" : recoveryMode ? "أدخل هاتف الحساب ورمز الاسترداد الذي احتفظت به" : "أدخل بيانات حسابك للوصول إلى النظام"}</CardDescription>
          </CardHeader>
          <CardContent>
            {checkingSetup ? <div className="py-8 flex justify-center"><Loader2 className="w-6 h-6 animate-spin text-primary" /></div> : (
              <form onSubmit={isSetup ? handleSetup : recoveryMode ? handleRecover : handleLogin} className="space-y-4">
                {isSetup ? (
                  <>
                    <div className="space-y-2"><Label htmlFor="setupKey">مفتاح الإعداد</Label><Input id="setupKey" type="password" value={setupKey} onChange={(e) => setSetupKey(e.target.value)} autoComplete="off" required /><p className="text-xs text-muted-foreground">تحصل عليه من مسؤول النظام.</p></div>
                    <div className="space-y-2"><Label htmlFor="phone">رقم الهاتف</Label><div className="relative"><Phone className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /><Input id="phone" type="tel" className="pr-9" value={phone} onChange={(e) => setPhone(e.target.value)} dir="ltr" placeholder="+9647XXXXXXXXX" required /></div></div>
                    <div className="space-y-2"><Label htmlFor="username">اسم المستخدم</Label><Input id="username" value={username} onChange={(e) => setUsername(e.target.value)} dir="ltr" placeholder="schooladmin" autoComplete="username" minLength={3} required /><p className="text-xs text-muted-foreground">أحرف إنجليزية صغيرة أو أرقام أو . _ -</p></div>
                    <div className="space-y-2"><Label htmlFor="password">كلمة المرور (12 حرفاً على الأقل)</Label><Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" minLength={12} required /></div>
                    <div className="space-y-2"><Label htmlFor="confirmPassword">تأكيد كلمة المرور</Label><Input id="confirmPassword" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} autoComplete="new-password" minLength={12} required /></div>
                  </>
                ) : recoveryMode ? (
                  <>
                    <div className="space-y-2"><Label htmlFor="recovery-phone">رقم الهاتف</Label><Input id="recovery-phone" type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} dir="ltr" placeholder="+9647XXXXXXXXX" required /></div>
                    <div className="space-y-2"><Label htmlFor="recovery-code">رمز الاسترداد</Label><Input id="recovery-code" value={recoveryCode} onChange={(e) => setRecoveryCode(e.target.value)} dir="ltr" className="font-mono tracking-wider" autoComplete="off" required /></div>
                    <div className="space-y-2"><Label htmlFor="recovery-password">كلمة المرور الجديدة (12 حرفاً على الأقل)</Label><Input id="recovery-password" type="password" value={recoveryPassword} onChange={(e) => setRecoveryPassword(e.target.value)} minLength={12} required /></div>
                    <div className="space-y-2"><Label htmlFor="recovery-confirm">تأكيد كلمة المرور</Label><Input id="recovery-confirm" type="password" value={recoveryConfirm} onChange={(e) => setRecoveryConfirm(e.target.value)} minLength={12} required /></div>
                  </>
                ) : (
                  <>
                    <div className="space-y-2"><Label htmlFor="username">اسم المستخدم</Label><div className="relative"><User className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /><Input id="username" className="pr-9" value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" required /></div></div>
                    <div className="space-y-2"><Label htmlFor="password">كلمة المرور</Label><div className="relative"><Lock className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /><Input id="password" type="password" className="pr-9" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" required /></div></div>
                  </>
                )}
                {error && <div role="alert" className="text-sm text-destructive bg-destructive/10 border border-destructive/20 rounded-lg px-3 py-2">{error}</div>}
                {notice && <div role="status" className="text-sm text-green-700 bg-green-50 border border-green-200 rounded-lg px-3 py-2">{notice}</div>}
                {visibleRecoveryCode && <div className="rounded-xl border border-primary/30 bg-primary/5 p-3 text-sm"><p className="font-semibold">احفظ رمز الاسترداد الآن، لن يظهر مرة أخرى:</p><div className="mt-2 rounded-lg bg-background p-3 text-center font-mono text-sm tracking-wider select-all" dir="ltr">{visibleRecoveryCode}</div><Button type="button" variant="outline" className="mt-2 w-full" onClick={() => navigator.clipboard.writeText(visibleRecoveryCode)}><Copy className="h-4 w-4" /> نسخ الرمز</Button><Button type="button" variant="ghost" className="mt-1 w-full" onClick={() => setVisibleRecoveryCode("")}>أخفيت الرمز وحفظته</Button></div>}
                {!isSetup && !recoveryMode && <Button type="button" variant="link" className="w-full" onClick={() => { setRecoveryMode(true); setError(""); setNotice(""); }}>نسيت كلمة المرور؟ استخدم رمز الاسترداد</Button>}
                {recoveryMode && <Button type="button" variant="ghost" className="w-full" onClick={() => { setRecoveryMode(false); setError(""); }}><ArrowRight className="h-4 w-4" /> العودة لتسجيل الدخول</Button>}
                <Button type="submit" className="w-full h-11 text-base font-semibold" disabled={loading || Boolean(visibleRecoveryCode)}>{loading ? <><Loader2 className="w-4 h-4 ml-2 animate-spin" /> جارٍ الحفظ...</> : isSetup ? "إنشاء حساب المدير" : recoveryMode ? "تغيير كلمة المرور" : "دخول إلى النظام"}</Button>
              </form>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
