import { useCallback, useEffect, useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { Download, Loader2, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { listApplicants, type ApplicantRow } from "@/lib/applicants";
import { LOCATIONS, ROLES } from "@/lib/careers";

export const Route = createFileRoute("/staff")({ component: StaffPage });

function labelLocation(id: string) {
  return LOCATIONS.find((l) => l.id === id)?.label ?? id;
}

function labelRole(id: string) {
  return ROLES.find((r) => r.id === id)?.title ?? id;
}

function StaffPage() {
  const [rows, setRows] = useState<ApplicantRow[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await listApplicants();
      setRows(data);
    } catch {
      toast.error("Could not load applications.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <main className="min-h-dvh bg-field-noise px-4 py-10 sm:px-6">
      <div className="mx-auto max-w-6xl space-y-6">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
          <div className="space-y-2">
            <Badge variant="secondary">Staff</Badge>
            <h1 className="font-display text-3xl font-semibold tracking-tight sm:text-4xl">
              Job applications
            </h1>
            <p className="text-sm text-[var(--color-fg-muted)]">
              Every submission is stored and can be downloaded as an Excel spreadsheet.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button type="button" variant="outline" onClick={() => void load()} disabled={loading}>
              {loading ? <Loader2 className="size-4 animate-spin" /> : <RefreshCw className="size-4" />}
              Refresh
            </Button>
            <Button asChild>
              <a href="/api/applicants/export" download>
                <Download className="size-4" />
                Download Excel
              </a>
            </Button>
            <Button asChild variant="secondary">
              <Link to="/">Back to careers</Link>
            </Button>
          </div>
        </div>

        <Card>
          <CardHeader className="flex-row items-center justify-between gap-3 space-y-0">
            <div>
              <CardTitle className="text-xl">Applicants</CardTitle>
              <CardDescription>
                {loading ? "Loading…" : `${rows.length} application${rows.length === 1 ? "" : "s"}`}
              </CardDescription>
            </div>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="flex items-center gap-2 py-10 text-sm text-[var(--color-fg-muted)]">
                <Loader2 className="size-4 animate-spin" />
                Loading applications…
              </div>
            ) : rows.length === 0 ? (
              <p className="py-10 text-sm text-[var(--color-fg-muted)]">
                No applications yet. Submit one from the careers form to see it here.
              </p>
            ) : (
              <div className="overflow-x-auto rounded-[var(--radius-lg)] border border-[var(--color-border)]">
                <table className="w-full min-w-[720px] text-left text-sm">
                  <thead className="bg-[var(--color-bg-elevated)] text-[var(--color-fg-subtle)]">
                    <tr>
                      <th className="px-3 py-2.5 font-medium">Name</th>
                      <th className="px-3 py-2.5 font-medium">Email</th>
                      <th className="px-3 py-2.5 font-medium">Phone</th>
                      <th className="px-3 py-2.5 font-medium">Age</th>
                      <th className="px-3 py-2.5 font-medium">Location</th>
                      <th className="px-3 py-2.5 font-medium">Role</th>
                      <th className="px-3 py-2.5 font-medium">Submitted</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((row) => (
                      <tr key={row.id} className="border-t border-[var(--color-border)]">
                        <td className="px-3 py-2.5 font-medium text-[var(--color-fg)]">{row.name}</td>
                        <td className="px-3 py-2.5 text-[var(--color-fg-muted)]">{row.email}</td>
                        <td className="px-3 py-2.5 text-[var(--color-fg-muted)]">{row.phone}</td>
                        <td className="px-3 py-2.5 tabular-nums text-[var(--color-fg-muted)]">{row.age}</td>
                        <td className="px-3 py-2.5 text-[var(--color-fg-muted)]">
                          {labelLocation(row.location)}
                        </td>
                        <td className="px-3 py-2.5 text-[var(--color-fg-muted)]">
                          {labelRole(row.role)}
                        </td>
                        <td className="px-3 py-2.5 tabular-nums text-[var(--color-fg-subtle)]">
                          {new Date(row.created_at).toLocaleString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </main>
  );
}
