import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useServerFn } from "@tanstack/react-start";
import { resolveAdminLogin } from "@/lib/admin.functions";
import { toast } from "sonner";
import { Shield, Smartphone, KeyRound, Loader2 } from "lucide-react";
import { useAppSettings } from "@/hooks/useAppSettings";

export const Route = createFileRoute("/admin/login")({
  ssr: false,
  component: AdminLogin,
});

function AdminLogin() {
  const [phone, setPhone] = useState("");
  const [pin, setPin] = useState("");
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const resolve = useServerFn(resolveAdminLogin);
  const { settings } = useAppSettings();

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      const { email, password } = await resolve({ data: { phone, pin } });
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw new Error("ভুল ফোন নম্বর বা পিন");
      toast.success("অ্যাডমিন প্যানেলে স্বাগতম");
      navigate({ to: "/admin" });
    } catch (err: any) {
      toast.error(err?.message ?? "লগইন ব্যর্থ");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 grid place-items-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-6 text-white">
          <div className="inline-flex h-14 w-14 rounded-2xl bg-primary/20 backdrop-blur items-center justify-center ring-1 ring-primary/40 overflow-hidden">
            {settings.app_logo_url ? (
              <img src={settings.app_logo_url} alt={settings.app_name} className="h-full w-full object-cover" />
            ) : (
              <Shield className="h-7 w-7 text-primary-foreground" />
            )}
          </div>
          <h1 className="text-2xl font-extrabold mt-3 tracking-tight">{settings.app_name} Admin</h1>
          <p className="text-sm text-slate-400 mt-1">অনুমোদিত অ্যাডমিনদের জন্য</p>
        </div>

        <form onSubmit={onSubmit} className="bg-card rounded-2xl shadow-2xl p-6 space-y-4">
          <Field icon={Smartphone} label="ফোন নম্বর">
            <input
              value={phone}
              onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))}
              placeholder="01XXXXXXXXX"
              inputMode="numeric"
              className="w-full bg-transparent outline-none text-base tracking-wider"
              required
            />
          </Field>
          <Field icon={KeyRound} label="অ্যাডমিন পিন">
            <input
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, "").slice(0, 5))}
              placeholder="• • • • •"
              inputMode="numeric"
              type="password"
              className="w-full bg-transparent outline-none text-base tracking-[0.4em]"
              required
            />
          </Field>
          <button
            disabled={loading || phone.length !== 11 || pin.length !== 5}
            className="w-full h-12 rounded-full font-bold text-primary-foreground disabled:opacity-50 active:scale-[0.98] transition flex items-center justify-center gap-2"
            style={{ background: "var(--gradient-primary)" }}
          >
            {loading && <Loader2 className="h-4 w-4 animate-spin" />}
            অ্যাডমিন লগইন
          </button>

          <p className="text-center text-xs text-muted-foreground pt-2">
            ইউজার? <Link to="/auth" className="text-primary font-semibold">নরমাল লগইন</Link>
          </p>
        </form>
      </div>
    </div>
  );
}

function Field({ icon: Icon, label, children }: { icon: any; label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="text-xs font-semibold text-muted-foreground">{label}</span>
      <div className="mt-1 flex items-center gap-3 px-4 h-12 rounded-xl border border-input bg-background focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20 transition">
        <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
        {children}
      </div>
    </label>
  );
}
