import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { Crown, Lock, Mail, ShieldCheck, Loader2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { bootstrapFirstAdmin, hasAnyAdmin } from "@/lib/auth.functions";
import { toast } from "sonner";

export const Route = createFileRoute("/auth")({
  head: () => ({
    meta: [
      { title: "Login — Casino API Provider" },
      { name: "description", content: "Secure admin & client login portal for Casino API Provider." },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: AuthPage,
});

function AuthPage() {
  const navigate = useNavigate();
  const checkAdmin = useServerFn(hasAnyAdmin);
  const bootstrap = useServerFn(bootstrapFirstAdmin);
  const [mode, setMode] = useState<"login" | "setup" | "checking">("checking");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("Super Admin");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // If already signed in, route to the right panel
    supabase.auth.getSession().then(({ data }) => {
      if (data.session) {
        routeAfterLogin();
      }
    });
    checkAdmin().then((r) => setMode(r.exists ? "login" : "setup"));
  }, []);

  async function routeAfterLogin() {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const { data: roles } = await supabase.from("user_roles").select("role").eq("user_id", u.user.id);
    const isStaff = (roles ?? []).some((r) => r.role === "admin" || r.role === "manager");
    navigate({ to: isStaff ? "/admin/dashboard" : "/client/dashboard" });
  }

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    const { error } = await supabase.auth.signInWithPassword({ email, password });
    setLoading(false);
    if (error) return toast.error(error.message);
    toast.success("Welcome back");
    await routeAfterLogin();
  }

  async function handleSetup(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      await bootstrap({ data: { email, password, displayName } });
      // Now sign in
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;
      toast.success("Admin account created. Welcome!");
      navigate({ to: "/admin/dashboard" });
    } catch (e: any) {
      toast.error(e?.message ?? "Setup failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen relative flex items-center justify-center px-4 overflow-hidden">
      <div className="absolute inset-0 pointer-events-none" style={{ background: "var(--gradient-hero)" }} />
      <div className="absolute inset-0 bg-grid pointer-events-none" />
      <div className="relative w-full max-w-md">
        <Link to="/" className="flex items-center justify-center gap-2.5 mb-8">
          <div className="h-10 w-10 rounded-lg grid place-items-center" style={{ background: "var(--gradient-gold)" }}>
            <Crown className="h-5 w-5" style={{ color: "oklch(0.13 0.018 280)" }} />
          </div>
          <div className="leading-tight">
            <div className="font-display text-base font-bold text-gradient">CASINO API PROVIDER</div>
            <div className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground -mt-0.5">
              Secure portal
            </div>
          </div>
        </Link>

        <div className="surface-card-gold p-7">
          {mode === "checking" && (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-primary" />
            </div>
          )}

          {mode === "setup" && (
            <>
              <div className="text-center mb-6">
                <span className="chip mb-3">
                  <ShieldCheck className="h-3.5 w-3.5" /> First-run setup
                </span>
                <h1 className="font-display text-2xl font-bold">Create Super Admin</h1>
                <p className="text-sm text-muted-foreground mt-2">
                  Set up the first admin account. After this, only admins can create new users.
                </p>
              </div>
              <form onSubmit={handleSetup} className="space-y-4">
                <Field label="Display name" value={displayName} onChange={setDisplayName} required />
                <Field label="Email" type="email" icon={Mail} value={email} onChange={setEmail} required />
                <Field
                  label="Password"
                  type="password"
                  icon={Lock}
                  value={password}
                  onChange={setPassword}
                  required
                  hint="Minimum 8 characters"
                />
                <button type="submit" disabled={loading} className="btn-hero w-full">
                  {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Create admin account"}
                </button>
              </form>
            </>
          )}

          {mode === "login" && (
            <>
              <div className="text-center mb-6">
                <span className="chip mb-3">
                  <Lock className="h-3.5 w-3.5" /> Authorized access only
                </span>
                <h1 className="font-display text-2xl font-bold">Sign in</h1>
                <p className="text-sm text-muted-foreground mt-2">
                  Admin and client portal. New accounts are created by your administrator.
                </p>
              </div>
              <form onSubmit={handleLogin} className="space-y-4">
                <Field label="Email" type="email" icon={Mail} value={email} onChange={setEmail} required />
                <Field
                  label="Password"
                  type="password"
                  icon={Lock}
                  value={password}
                  onChange={setPassword}
                  required
                />
                <button type="submit" disabled={loading} className="btn-hero w-full">
                  {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Sign in"}
                </button>
              </form>
              <p className="mt-5 text-xs text-muted-foreground text-center">
                Need an account?{" "}
                <Link to="/contact" className="text-primary hover:underline">
                  Contact our team
                </Link>
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({
  label,
  type = "text",
  value,
  onChange,
  icon: Icon,
  required,
  hint,
}: {
  label: string;
  type?: string;
  value: string;
  onChange: (v: string) => void;
  icon?: React.ComponentType<{ className?: string }>;
  required?: boolean;
  hint?: string;
}) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <div className="mt-1.5 relative">
        {Icon && <Icon className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />}
        <input
          type={type}
          required={required}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={`w-full rounded-lg bg-background/50 border border-border-strong focus:border-primary focus:ring-2 focus:ring-primary/30 outline-none transition px-3 py-2.5 text-sm ${
            Icon ? "pl-9" : ""
          }`}
        />
      </div>
      {hint && <span className="block mt-1 text-[11px] text-muted-foreground">{hint}</span>}
    </label>
  );
}
