import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { format } from "date-fns";
import { toast } from "sonner";
import { AppShell } from "@/components/AppShell";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { supabase } from "@/integrations/supabase/client";
import { useAuth, useIsAdmin } from "@/hooks/useAuth";
import {
  fetchAdminEvents,
  fetchAdminStats,
  fetchSources,
  setEventStatus,
  type EventStatus,
} from "@/lib/hotspots";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/_authenticated/admin")({
  head: () => ({
    meta: [
      { title: "Admin — HOTSPOTS" },
      { name: "description", content: "Review events, manage sources and automation settings." },
      { property: "og:title", content: "Admin — HOTSPOTS" },
      { property: "og:description", content: "HOTSPOTS administration dashboard." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: AdminPage,
});

const AUTOMATION_KEYS: Array<[string, string]> = [
  ["auto_fetch", "Auto-fetch events"],
  ["auto_verification", "Auto-verification"],
  ["auto_approval", "Auto-approval"],
  ["duplicate_detection", "Duplicate detection"],
  ["continuous_verification", "Continuous verification"],
  ["auto_expire", "Auto-expire past events"],
  ["trusted_auto_publish", "Trusted sources auto-publish"],
];

function AdminPage() {
  const { userId } = useAuth();
  const isAdmin = useIsAdmin(userId);
  const qc = useQueryClient();
  const [tab, setTab] = useState<"dashboard" | "pending" | "approved" | "sources" | "automation">(
    "dashboard",
  );

  const stats = useQuery({ queryKey: ["admin-stats"], queryFn: fetchAdminStats, enabled: isAdmin });
  const pending = useQuery({
    queryKey: ["admin-events", "pending"],
    queryFn: () => fetchAdminEvents("pending"),
    enabled: isAdmin,
  });
  const approved = useQuery({
    queryKey: ["admin-events", "approved"],
    queryFn: () => fetchAdminEvents("approved"),
    enabled: isAdmin,
  });
  const sources = useQuery({ queryKey: ["admin-sources"], queryFn: fetchSources, enabled: isAdmin });
  const automation = useQuery({
    queryKey: ["automation"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("app_settings")
        .select("value")
        .eq("key", "automation")
        .maybeSingle();
      if (error) throw error;
      return (data?.value ?? {}) as Record<string, boolean | number>;
    },
    enabled: isAdmin,
  });

  if (!isAdmin) {
    return (
      <AppShell>
        <div className="rounded-2xl border border-border bg-card p-10 text-center">
          <h1 className="font-display text-xl font-bold">Admins only</h1>
          <p className="mt-2 text-sm text-muted-foreground">
            Your account doesn't have administrator access.
          </p>
          <Button asChild className="mt-4 rounded-full">
            <Link to="/">Back home</Link>
          </Button>
        </div>
      </AppShell>
    );
  }

  async function act(id: string, status: EventStatus) {
    await setEventStatus(id, status);
    toast.success(status === "approved" ? "Event approved and published" : "Event rejected");
    qc.invalidateQueries({ queryKey: ["admin-events"] });
    qc.invalidateQueries({ queryKey: ["admin-stats"] });
  }

  async function saveAutomation(next: Record<string, boolean | number>) {
    const { error } = await supabase
      .from("app_settings")
      .update({ value: next, updated_at: new Date().toISOString() })
      .eq("key", "automation");
    if (error) {
      toast.error(error.message);
      return;
    }
    qc.invalidateQueries({ queryKey: ["automation"] });
  }

  return (
    <AppShell>
      <div className="space-y-6">
        <div>
          <h1 className="font-display text-2xl font-extrabold">Admin</h1>
          <p className="text-sm text-muted-foreground">Events, sources and automation.</p>
        </div>

        <div className="hs-scroll-row hide-scrollbar">
          {(["dashboard", "pending", "approved", "sources", "automation"] as const).map((t) => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className={cn(
                "shrink-0 rounded-full border px-4 py-1.5 text-xs font-medium capitalize",
                tab === t ? "border-primary bg-primary/15 text-primary" : "border-border",
              )}
            >
              {t}
            </button>
          ))}
        </div>

        {tab === "dashboard" && (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {Object.entries(stats.data ?? {}).map(([key, value]) => (
              <div key={key} className="surface-card p-5">
                <p className="text-xs uppercase tracking-wide text-muted-foreground">
                  {key.replace(/_/g, " ")}
                </p>
                <p className="mt-1 font-display text-3xl font-extrabold text-primary">{value}</p>
              </div>
            ))}
          </div>
        )}

        {(tab === "pending" || tab === "approved") && (
          <div className="space-y-3">
            {(tab === "pending" ? pending : approved).data?.length === 0 && (
              <p className="rounded-2xl border border-border bg-card p-8 text-center text-sm text-muted-foreground">
                Nothing here right now.
              </p>
            )}
            {(tab === "pending" ? pending : approved).data?.map((e) => (
              <div
                key={e.id}
                className="flex flex-wrap items-center gap-3 rounded-2xl border border-border bg-card p-4"
              >
                <div className="min-w-0 flex-1">
                  <p className="truncate font-semibold">{e.title}</p>
                  <p className="text-xs text-muted-foreground">
                    {format(new Date(e.starts_at), "d MMM yyyy")} · {e.cities?.name ?? "—"} ·
                    confidence {e.confidence}% · {e.verification.replace(/_/g, " ")}
                  </p>
                </div>
                {e.source_url && (
                  <a
                    href={e.source_url}
                    target="_blank"
                    rel="noreferrer"
                    title={e.source_url}
                    className="max-w-52 truncate text-xs text-primary underline underline-offset-4 sm:max-w-72"
                  >
                    {e.source_url.replace(/^https?:\/\/(www\.)?/, "")}
                  </a>
                )}
                {tab === "pending" ? (
                  <>
                    <Button size="sm" className="rounded-full" onClick={() => act(e.id, "approved")}>
                      Approve
                    </Button>
                    <Button
                      size="sm"
                      variant="secondary"
                      className="rounded-full"
                      onClick={() => act(e.id, "rejected")}
                    >
                      Reject
                    </Button>
                  </>
                ) : (
                  <Button
                    size="sm"
                    variant="destructive"
                    className="rounded-full"
                    onClick={() => act(e.id, "rejected")}
                  >
                    Reject
                  </Button>
                )}
              </div>
            ))}
          </div>
        )}

        {tab === "sources" && (
          <div className="space-y-3">
            {sources.data?.map((s) => (
              <div key={s.id} className="flex flex-wrap items-center gap-3 surface-card p-4">
                <div className="min-w-0 flex-1">
                  <p className="font-semibold">{s.name}</p>
                  <p className="text-xs text-muted-foreground">
                    {s.website_url} · reliability {s.reliability}% ·{" "}
                    {s.last_success_at
                      ? `last fetch ${format(new Date(s.last_success_at), "d MMM")}`
                      : "never fetched"}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Label className="text-xs">Active</Label>
                  <Switch
                    checked={s.active}
                    onCheckedChange={async (v) => {
                      await supabase.from("event_sources").update({ active: v }).eq("id", s.id);
                      qc.invalidateQueries({ queryKey: ["admin-sources"] });
                    }}
                  />
                  <Label className="text-xs">Trusted</Label>
                  <Switch
                    checked={s.trusted}
                    onCheckedChange={async (v) => {
                      await supabase.from("event_sources").update({ trusted: v }).eq("id", s.id);
                      qc.invalidateQueries({ queryKey: ["admin-sources"] });
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === "automation" && automation.data && (
          <div className="surface-card max-w-xl space-y-4 p-5">
            {AUTOMATION_KEYS.map(([key, label]) => (
              <div key={key} className="flex items-center justify-between">
                <Label className="text-sm font-normal">{label}</Label>
                <Switch
                  checked={Boolean(automation.data[key])}
                  onCheckedChange={(v) => saveAutomation({ ...automation.data, [key]: v })}
                />
              </div>
            ))}
            <div className="flex items-center justify-between gap-4">
              <Label className="text-sm font-normal">Minimum confidence to auto-approve</Label>
              <Input
                type="number"
                min={0}
                max={100}
                className="w-24"
                defaultValue={Number(automation.data['min_confidence'] ?? 75)}
                onBlur={(e) =>
                  saveAutomation({ ...automation.data, min_confidence: Number(e.target.value) })
                }
              />
            </div>
            <div className="flex items-center justify-between gap-4">
              <Label className="text-sm font-normal">Minimum ratings before showing a score</Label>
              <Input
                type="number"
                min={1}
                className="w-24"
                defaultValue={Number(automation.data['min_ratings_to_display'] ?? 3)}
                onBlur={(e) =>
                  saveAutomation({
                    ...automation.data,
                    min_ratings_to_display: Number(e.target.value),
                  })
                }
              />
            </div>
          </div>
        )}
      </div>
    </AppShell>
  );
}
