import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Shield } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { AuthLayout, Field, submitClass } from "@/components/auth/AuthLayout";
import { resolveAccountType } from "@/lib/portal";

const SUPER_ADMIN_EMAIL = "emmaexclusive.fpi@gmail.com";

export const Route = createFileRoute("/auth/admin")({
  head: () => ({
    meta: [
      { title: "Admin login | Emma Exclusive Teams" },
      { name: "description", content: "Restricted sign in for Emma Exclusive Teams administrators." },
      { property: "og:title", content: "Admin login | Emma Exclusive Teams" },
      { property: "og:description", content: "Internal operations portal for Emma Mold Inspection Services." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: AdminAuth,
});

function AdminAuth() {
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [forgot, setForgot] = useState(false);
  const [setup, setSetup] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (!data.session) return;
      resolveAccountType(data.session.user.id).then((a) => {
        if (a.isAdmin) navigate({ to: "/admin" });
      });
    });
  }, [navigate]);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    try {
      if (forgot) {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: `${window.location.origin}/reset-password`,
        });
        if (error) throw error;
        toast.success("Password reset link sent. Check your inbox.");
        setForgot(false);
        return;
      }
      if (setup) {
        if (email.trim().toLowerCase() !== SUPER_ADMIN_EMAIL) {
          toast.error("Only the Super Admin email can be set up here.");
          return;
        }
        const { error } = await supabase.auth.signUp({
          email: email.trim().toLowerCase(),
          password,
          options: { emailRedirectTo: `${window.location.origin}/auth/admin` },
        });
        if (error) throw error;
        toast.success("Super Admin account created. Sign in with the password you just chose.");
        setSetup(false);
        setPassword("");
        return;
      }
      const { data, error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;
      const account = await resolveAccountType(data.user!.id);
      if (!account.isAdmin) {
        await supabase.auth.signOut();
        toast.error("This account does not have admin access.");
        return;
      }
      navigate({ to: "/admin" });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Something went wrong.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <AuthLayout
      title={forgot ? "Reset admin password" : setup ? "Super Admin setup" : "Admin login"}
      subtitle="Emma Exclusive Teams"
      footer={
        <div className="space-y-2">
          <button
            className="font-semibold text-primary"
            onClick={() => {
              setForgot(!forgot);
              setSetup(false);
            }}
          >
            {forgot ? "Back to sign in" : "Forgot password?"}
          </button>
          <div>
            <button
              className="font-semibold text-primary"
              onClick={() => {
                setSetup(!setup);
                setForgot(false);
                if (!setup) setEmail(SUPER_ADMIN_EMAIL);
              }}
            >
              {setup ? "Back to sign in" : "First-time Super Admin setup"}
            </button>
          </div>
        </div>
      }
    >
      <div className="mt-4 flex items-start gap-2 rounded-2xl bg-muted p-3 text-[11px] text-muted-foreground">
        <Shield className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden />
        <p>
          Admin accounts cannot be registered publicly. Only the Super Admin ({SUPER_ADMIN_EMAIL}) can set up an account
          here, and only once — every further admin account is created by the Super Admin. Passwords are never stored or
          shown in plain text; you choose your own.
        </p>
      </div>
      <form className="mt-4 space-y-3" onSubmit={submit}>
        <Field label="Admin email" value={email} onChange={setEmail} type="email" required />
        {!forgot ? (
          <Field
            label={setup ? "Choose your password" : "Password"}
            value={password}
            onChange={setPassword}
            type="password"
            required
          />
        ) : null}
        <button type="submit" disabled={busy} className={submitClass}>
          {busy ? "Please wait…" : forgot ? "Send reset link" : setup ? "Create Super Admin account" : "Sign in"}
        </button>
      </form>
    </AuthLayout>
  );
}
