import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { toast } from "sonner";
import { CflMark } from "@/components/cfl-mark";
import { RolePreviewBar } from "@/components/role-bar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { DEMO_ACCOUNTS, ROLE_LABEL, verifyDemoLogin } from "@/lib/identity";
import { useRoleStore } from "@/lib/role-store";
import { ORG_ADDRESS_FULL, ORG_NAME } from "@/lib/constants";

export const Route = createFileRoute("/login")({ component: Login });

function Login() {
  const navigate = useNavigate();
  const signIn = useRoleStore((s) => s.signIn);
  const [email, setEmail] = useState("mjones@sprowtt.com");
  const [password, setPassword] = useState("ForgeAdmin2026");

  function enter(account: ReturnType<typeof verifyDemoLogin>) {
    if (!account) {
      toast.error("That email and password do not match a preview account.");
      return;
    }
    signIn(account);
    toast.success(`Signed in as ${account.name}`);
    void navigate({ to: account.role === "public" ? "/public" : "/" });
  }

  function submit(e: React.FormEvent) {
    e.preventDefault();
    enter(verifyDemoLogin(email, password));
  }

  return (
    <div className="min-h-dvh bg-background">
      <RolePreviewBar />
      <main className="mx-auto flex max-w-5xl flex-col gap-8 px-4 pt-20 pb-16 sm:px-6">
        <div className="club-hero">
          <CflMark variant="hero" />
          <h1 className="mt-4 font-display text-4xl">Sign in to the league</h1>
          <p className="mt-2 max-w-xl text-sm text-muted-foreground">
            Use a preview account to see the public member view, a donor desk, the student desk, the instructor desk, or
            Super Admin. The tabs at the top also switch roles without a password.
          </p>
          <div className="mt-4 flex flex-wrap gap-2">
            <Button asChild variant="outline">
              <Link to="/public">Visit the public site</Link>
            </Button>
          </div>
          <p className="mt-3 text-xs text-muted-foreground">
            {ORG_NAME}
            <br />
            {ORG_ADDRESS_FULL}
            <br />
            Registered agent: Mark Jones · mjones@sprowtt.com
          </p>
        </div>

        <div className="grid gap-6 lg:grid-cols-5">
          <Card className="lg:col-span-2">
            <CardContent className="pt-5">
              <form className="space-y-4" onSubmit={submit}>
                <div className="space-y-1.5">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    autoComplete="username"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="password">Password</Label>
                  <Input
                    id="password"
                    type="password"
                    autoComplete="current-password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
                <Button type="submit" className="w-full">
                  Sign in
                </Button>
              </form>
            </CardContent>
          </Card>

          <Card className="lg:col-span-3">
            <CardContent className="pt-5">
              <h2 className="font-display text-xl">Preview accounts</h2>
              <p className="mt-1 text-sm text-muted-foreground">
                Demo passwords for this preview only. Contractor names are not stored in this directory.
              </p>
              <ul className="mt-4 space-y-3">
                {DEMO_ACCOUNTS.map((a) => (
                  <li
                    key={a.email}
                    className="flex flex-col gap-3 rounded-lg bg-muted/70 px-3 py-3 sm:flex-row sm:items-center sm:justify-between"
                  >
                    <div className="min-w-0">
                      <div className="flex flex-wrap items-center gap-2">
                        <p className="font-medium">{a.name}</p>
                        <Badge variant="outline">{ROLE_LABEL[a.role]}</Badge>
                      </div>
                      <p className="mt-1 font-mono text-xs text-muted-foreground">{a.email}</p>
                      <p className="font-mono text-xs text-muted-foreground">{a.password}</p>
                    </div>
                    <Button
                      type="button"
                      size="sm"
                      onClick={() => enter(a)}
                    >
                      Open {a.role === "public" ? "public view" : `${a.role} desk`}
                    </Button>
                  </li>
                ))}
              </ul>
            </CardContent>
          </Card>
        </div>
      </main>
    </div>
  );
}
