import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
import {
  Users,
  ShieldCheck,
  UserX,
  Plus,
  ListChecks,
  ArrowUpRight,
  ArrowDownRight,
  ClipboardCheck,
  Activity,
  Eye,
  EyeOff,
  TrendingUp,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useState } from "react";

export const Route = createFileRoute("/_authenticated/dashboard")({
  component: Dashboard,
});

type AttendanceRow = {
  id: string;
  guard_id: string;
  check_in_at: string | null;
  check_out_at: string | null;
  status: string | null;
  location: string | null;
  shift: string | null;
};

function Dashboard() {
  const qc = useQueryClient();
  const [showBalance, setShowBalance] = useState(true);

  const guards = useQuery({
    queryKey: ["guards-summary"],
    queryFn: async () => {
      const { data, error } = await supabase.from("security_guards").select("id,status,full_name");
      if (error) throw error;
      return data as { id: string; status: string; full_name: string }[];
    },
  });

  const attendance = useQuery({
    queryKey: ["attendance-recent"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("attendance")
        .select("id,guard_id,check_in_at,check_out_at,status,location,shift")
        .order("check_in_at", { ascending: false, nullsFirst: false })
        .limit(8);
      if (error) throw error;
      return data as AttendanceRow[];
    },
  });

  // Realtime: refresh stats and table on attendance/guard changes
  useEffect(() => {
    const ch = supabase
      .channel("dashboard-live")
      .on("postgres_changes", { event: "*", schema: "public", table: "attendance" }, () => {
        qc.invalidateQueries({ queryKey: ["attendance-recent"] });
        qc.invalidateQueries({ queryKey: ["guards-summary"] });
      })
      .on("postgres_changes", { event: "*", schema: "public", table: "security_guards" }, () => {
        qc.invalidateQueries({ queryKey: ["guards-summary"] });
      })
      .subscribe();
    return () => {
      supabase.removeChannel(ch);
    };
  }, [qc]);

  const total = guards.data?.length ?? 0;
  const active = guards.data?.filter((g) => g.status === "active").length ?? 0;
  const inactive = total - active;
  const guardName = (id: string) =>
    guards.data?.find((g) => g.id === id)?.full_name ?? "Unknown guard";

  const todayCount =
    attendance.data?.filter((a) => {
      if (!a.check_in_at) return false;
      const d = new Date(a.check_in_at);
      const t = new Date();
      return d.toDateString() === t.toDateString();
    }).length ?? 0;

  const stats = [
    { label: "Active Today", value: todayCount, icon: Activity, trend: "+12%", up: true },
    { label: "Active Guards", value: active, icon: ShieldCheck, trend: "+3%", up: true },
    { label: "Off Duty", value: inactive, icon: UserX, trend: "-2%", up: false },
  ];

  return (
    <div className="space-y-6">
      {/* Banking-style balance card */}
      <section className="relative overflow-hidden rounded-3xl border bg-gradient-primary text-primary-foreground shadow-elegant">
        <div className="absolute inset-0 bg-grid opacity-30" aria-hidden />
        <div className="absolute -top-16 -right-16 h-64 w-64 rounded-full bg-white/10 blur-3xl" aria-hidden />
        <div className="relative p-6 sm:p-8 grid gap-6 md:grid-cols-[1.4fr_1fr] md:items-end">
          <div className="min-w-0">
            <div className="flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-primary-foreground/80">
              <span className="inline-block h-2 w-2 rounded-full bg-emerald-300 animate-pulse-dot" />
              Live workforce balance
            </div>
            <div className="mt-3 flex items-center gap-3">
              <h1 className="text-4xl sm:text-5xl font-extrabold tracking-tight tabular-nums">
                {showBalance ? total.toLocaleString() : "•••"}
                <span className="ml-2 text-base font-medium text-primary-foreground/70">guards</span>
              </h1>
              <button
                onClick={() => setShowBalance((v) => !v)}
                className="grid h-8 w-8 place-items-center rounded-full bg-white/10 hover:bg-white/20 transition"
                aria-label="Toggle balance visibility"
              >
                {showBalance ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
              </button>
            </div>
            <div className="mt-2 flex items-center gap-2 text-sm text-primary-foreground/85">
              <TrendingUp className="h-4 w-4" /> {active} active right now · {todayCount} checked in today
            </div>
          </div>
          <div className="flex flex-wrap gap-2 md:justify-end">
            <Button asChild size="sm" variant="secondary" className="rounded-full">
              <Link to="/guards/new"><Plus className="h-4 w-4 mr-1" /> Add Guard</Link>
            </Button>
            <Button asChild size="sm" variant="secondary" className="rounded-full bg-white/15 text-primary-foreground hover:bg-white/25 border-0">
              <Link to="/attendance"><ClipboardCheck className="h-4 w-4 mr-1" /> Attendance</Link>
            </Button>
            <Button asChild size="sm" variant="secondary" className="rounded-full bg-white/15 text-primary-foreground hover:bg-white/25 border-0">
              <Link to="/guards"><ListChecks className="h-4 w-4 mr-1" /> Roster</Link>
            </Button>
          </div>
        </div>
      </section>

      {/* Stat tiles */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {stats.map((s) => (
          <Card key={s.label} className="shadow-elegant border-border/60 hover:-translate-y-0.5 transition rounded-2xl">
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{s.label}</CardTitle>
              <div className="h-9 w-9 rounded-xl bg-gradient-primary grid place-items-center">
                <s.icon className="h-4 w-4 text-primary-foreground" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="flex items-baseline justify-between">
                <div className="text-3xl font-bold tabular-nums">{guards.isLoading ? "—" : s.value}</div>
                <span
                  className={`inline-flex items-center gap-1 text-xs font-medium rounded-full px-2 py-0.5 ${
                    s.up
                      ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
                      : "bg-destructive/10 text-destructive"
                  }`}
                >
                  {s.up ? <ArrowUpRight className="h-3 w-3" /> : <ArrowDownRight className="h-3 w-3" />}
                  {s.trend}
                </span>
              </div>
              <p className="text-xs text-muted-foreground mt-1">vs. last 7 days</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Recent activity table */}
      <Card className="shadow-elegant border-border/60 rounded-2xl overflow-hidden">
        <CardHeader className="flex flex-row items-center justify-between gap-2">
          <div className="min-w-0">
            <CardTitle className="truncate">Recent Activity</CardTitle>
            <CardDescription>Live check-ins and check-outs</CardDescription>
          </div>
          <Button asChild size="sm" variant="ghost">
            <Link to="/attendance">View all <ArrowUpRight className="h-4 w-4 ml-1" /></Link>
          </Button>
        </CardHeader>
        <CardContent className="p-0">
          {/* Mobile cards */}
          <ul className="divide-y sm:hidden">
            {attendance.isLoading && (
              <li className="p-4 text-sm text-muted-foreground">Loading…</li>
            )}
            {!attendance.isLoading && (attendance.data?.length ?? 0) === 0 && (
              <li className="p-4 text-sm text-muted-foreground">No activity yet.</li>
            )}
            {attendance.data?.map((row) => (
              <li key={row.id} className="p-4 flex items-center gap-3">
                <div
                  className={`h-9 w-9 shrink-0 rounded-full grid place-items-center ${
                    row.check_out_at
                      ? "bg-muted text-muted-foreground"
                      : "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400"
                  }`}
                >
                  {row.check_out_at ? <ArrowDownRight className="h-4 w-4" /> : <ArrowUpRight className="h-4 w-4" />}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="font-medium truncate">{guardName(row.guard_id)}</div>
                  <div className="text-xs text-muted-foreground truncate">
                    {row.location || row.shift || "—"} ·{" "}
                    {row.check_in_at ? new Date(row.check_in_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "—"}
                  </div>
                </div>
                <StatusPill status={row.status} />
              </li>
            ))}
          </ul>

          {/* Desktop table */}
          <div className="hidden sm:block overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
                <tr>
                  <th className="text-left font-medium px-4 py-3">Guard</th>
                  <th className="text-left font-medium px-4 py-3">Location</th>
                  <th className="text-left font-medium px-4 py-3">Check-in</th>
                  <th className="text-left font-medium px-4 py-3">Check-out</th>
                  <th className="text-left font-medium px-4 py-3">Status</th>
                </tr>
              </thead>
              <tbody>
                {attendance.isLoading && (
                  <tr><td colSpan={5} className="px-4 py-6 text-muted-foreground">Loading…</td></tr>
                )}
                {!attendance.isLoading && (attendance.data?.length ?? 0) === 0 && (
                  <tr><td colSpan={5} className="px-4 py-6 text-muted-foreground">No activity yet.</td></tr>
                )}
                {attendance.data?.map((row) => (
                  <tr key={row.id} className="border-t hover:bg-muted/30 transition">
                    <td className="px-4 py-3 font-medium">{guardName(row.guard_id)}</td>
                    <td className="px-4 py-3 text-muted-foreground">{row.location || row.shift || "—"}</td>
                    <td className="px-4 py-3 tabular-nums text-muted-foreground">
                      {row.check_in_at ? new Date(row.check_in_at).toLocaleString([], { dateStyle: "short", timeStyle: "short" }) : "—"}
                    </td>
                    <td className="px-4 py-3 tabular-nums text-muted-foreground">
                      {row.check_out_at ? new Date(row.check_out_at).toLocaleString([], { dateStyle: "short", timeStyle: "short" }) : "—"}
                    </td>
                    <td className="px-4 py-3"><StatusPill status={row.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function StatusPill({ status }: { status: string | null }) {
  const s = (status || "present").toLowerCase();
  const map: Record<string, string> = {
    present: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
    late: "bg-amber-500/10 text-amber-600 dark:text-amber-400",
    absent: "bg-destructive/10 text-destructive",
  };
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${map[s] ?? "bg-muted text-muted-foreground"}`}>
      {s}
    </span>
  );
}