import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { GuardForm } from "@/components/guard-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { CalendarDays, ClipboardList, Clock, LogIn, LogOut, AlertTriangle } from "lucide-react";

export const Route = createFileRoute("/_authenticated/guards/$id")({
  component: EditGuard,
});

function EditGuard() {
  const { id } = Route.useParams();
  const { data, isLoading, error } = useQuery({
    queryKey: ["guard", id],
    queryFn: async () => {
      const { data, error } = await supabase.from("security_guards").select("*").eq("id", id).maybeSingle();
      if (error) throw error;
      return data;
    },
  });

  return (
    <div className="max-w-4xl mx-auto space-y-4">
      <h1 className="text-3xl font-bold tracking-tight">Edit Guard</h1>
      {isLoading && <p className="text-muted-foreground">Loading…</p>}
      {error && <p className="text-destructive">{(error as Error).message}</p>}
      {data && <GuardForm guardId={id} initial={data as never} />}
      {data && <GuardDutyStats guardId={id} />}
      {!isLoading && !data && <p className="text-muted-foreground">Guard not found.</p>}
    </div>
  );
}

function GuardDutyStats({ guardId }: { guardId: string }) {
  const [days, setDays] = useState<7 | 30 | 90>(30);
  const { since, sinceDate } = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() - days);
    const iso = d.toISOString();
    return { since: iso, sinceDate: iso.slice(0, 10) };
  }, [days]);

  const att = useQuery({
    queryKey: ["guard-att", guardId, sinceDate],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("attendance")
        .select("id, check_in_at, check_out_at, status, shift, duty_post_id, duty_posts(name)")
        .eq("guard_id", guardId)
        .gte("check_in_at", since)
        .order("check_in_at", { ascending: false });
      if (error) throw error;
      return data ?? [];
    },
  });

  const ros = useQuery({
    queryKey: ["guard-ros", guardId, sinceDate],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("duty_rosters")
        .select("id, shift_date, shift_start, shift_end, status, duty_posts(name)")
        .eq("guard_id", guardId)
        .gte("shift_date", sinceDate)
        .order("shift_date", { ascending: false });
      if (error) throw error;
      return data ?? [];
    },
  });

  const lv = useQuery({
    queryKey: ["guard-lv", guardId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("leave_requests")
        .select("id, leave_type, start_date, end_date, status")
        .eq("guard_id", guardId)
        .order("start_date", { ascending: false })
        .limit(20);
      if (error) throw error;
      return data ?? [];
    },
  });

  const stats = useMemo(() => {
    const rows = att.data ?? [];
    let hours = 0;
    let open = 0;
    let flagged = 0;
    for (const r of rows) {
      if (r.status === "flagged") flagged++;
      if (!r.check_out_at) { open++; continue; }
      hours += (new Date(r.check_out_at).getTime() - new Date(r.check_in_at).getTime()) / 36e5;
    }
    const scheduled = (ros.data ?? []).length;
    const completed = (ros.data ?? []).filter((r) => r.status === "completed").length;
    const pendingLeave = (lv.data ?? []).filter((l) => l.status === "pending").length;
    const approvedLeave = (lv.data ?? []).filter((l) => l.status === "approved").length;
    return { shifts: rows.length, hours: hours.toFixed(1), open, flagged, scheduled, completed, pendingLeave, approvedLeave };
  }, [att.data, ros.data, lv.data]);

  const loading = att.isLoading || ros.isLoading || lv.isLoading;

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
        <CardTitle className="flex items-center gap-2"><ClipboardList className="h-5 w-5" /> Duty Summary (last {days} days)</CardTitle>
        <div className="flex gap-1">
          {[7, 30, 90].map((d) => (
            <Button key={d} size="sm" variant={days === d ? "default" : "outline"} onClick={() => setDays(d as 7 | 30 | 90)}>
              {d}d
            </Button>
          ))}
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {loading ? (
          <p className="text-sm text-muted-foreground">Loading…</p>
        ) : (
          <>
            <div className="grid gap-3 sm:grid-cols-2 md:grid-cols-4">
              <Stat icon={<LogIn className="h-4 w-4" />} label="Attended shifts" value={stats.shifts} />
              <Stat icon={<Clock className="h-4 w-4" />} label="Hours on duty" value={stats.hours} />
              <Stat icon={<LogOut className="h-4 w-4" />} label="Open (not checked out)" value={stats.open} />
              <Stat icon={<AlertTriangle className="h-4 w-4" />} label="Flagged" value={stats.flagged} />
              <Stat icon={<CalendarDays className="h-4 w-4" />} label="Scheduled shifts" value={stats.scheduled} />
              <Stat icon={<CalendarDays className="h-4 w-4" />} label="Completed shifts" value={stats.completed} />
              <Stat icon={<ClipboardList className="h-4 w-4" />} label="Leaves approved" value={stats.approvedLeave} />
              <Stat icon={<ClipboardList className="h-4 w-4" />} label="Leaves pending" value={stats.pendingLeave} />
            </div>

            <Section title="Recent attendance">
              {(att.data ?? []).length === 0 ? (
                <p className="text-sm text-muted-foreground">No attendance records.</p>
              ) : (
                <ul className="divide-y rounded-md border">
                  {(att.data ?? []).slice(0, 8).map((r) => {
                    const post = (r as { duty_posts?: { name?: string } | null }).duty_posts?.name ?? r.shift ?? "—";
                    const dur = r.check_out_at
                      ? ((new Date(r.check_out_at).getTime() - new Date(r.check_in_at).getTime()) / 36e5).toFixed(1) + "h"
                      : "open";
                    return (
                      <li key={r.id} className="flex items-center justify-between px-3 py-2 text-sm">
                        <span className="truncate">{new Date(r.check_in_at).toLocaleString()} · {post}</span>
                        <span className="flex items-center gap-2">
                          <span className="text-muted-foreground">{dur}</span>
                          <Badge variant={r.status === "flagged" ? "destructive" : "secondary"}>{r.status}</Badge>
                        </span>
                      </li>
                    );
                  })}
                </ul>
              )}
            </Section>

            <Section title="Upcoming / recent roster">
              {(ros.data ?? []).length === 0 ? (
                <p className="text-sm text-muted-foreground">No roster entries.</p>
              ) : (
                <ul className="divide-y rounded-md border">
                  {(ros.data ?? []).slice(0, 8).map((r) => {
                    const post = (r as { duty_posts?: { name?: string } | null }).duty_posts?.name ?? "—";
                    return (
                      <li key={r.id} className="flex items-center justify-between px-3 py-2 text-sm">
                        <span className="truncate">{r.shift_date} · {r.shift_start}–{r.shift_end} · {post}</span>
                        <Badge variant="secondary">{r.status}</Badge>
                      </li>
                    );
                  })}
                </ul>
              )}
            </Section>
          </>
        )}
      </CardContent>
    </Card>
  );
}

function Stat({ icon, label, value }: { icon: React.ReactNode; label: string; value: React.ReactNode }) {
  return (
    <div className="rounded-md border p-3">
      <div className="flex items-center gap-2 text-xs text-muted-foreground">{icon}<span>{label}</span></div>
      <div className="mt-1 text-2xl font-semibold">{value}</div>
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold">{title}</h3>
      {children}
    </div>
  );
}