import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { usePermissions } from "@/hooks/use-permissions";
import { format } from "date-fns";

export const Route = createFileRoute("/_authenticated/staff-attendance")({
  component: AttendancePage,
});

const STATUSES = ["present", "absent", "late", "half_day", "leave"];

function AttendancePage() {
  const qc = useQueryClient();
  const { isAdmin } = usePermissions();
  const [date, setDate] = useState(format(new Date(), "yyyy-MM-dd"));

  const { data: staff = [] } = useQuery({
    queryKey: ["staff-active"],
    queryFn: async () => {
      const { data } = await supabase.from("staff").select("id,staff_id,name,photo_url,role")
        .is("deleted_at", null).eq("status", "active").order("name");
      return data ?? [];
    },
  });

  const { data: attendance = [] } = useQuery({
    queryKey: ["attendance", date],
    queryFn: async () => {
      const { data } = await supabase.from("staff_attendance").select("*").eq("date", date);
      return data ?? [];
    },
  });

  const byStaff = new Map(attendance.map((a: any) => [a.staff_id, a]));

  const upsertMutation = useMutation({
    mutationFn: async (input: { staff_id: string; status?: string; check_in?: string | null; check_out?: string | null }) => {
      const { staff_id, ...rest } = input;
      const existing = byStaff.get(staff_id);
      const payload: any = { staff_id, date, ...rest };
      if (existing) {
        const { error } = await supabase.from("staff_attendance").update(payload).eq("id", existing.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("staff_attendance").insert({ status: "present", ...payload });
        if (error) throw error;
      }
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["attendance", date] }),
    onError: (e: Error) => toast.error(e.message),
  });

  const markAllPresent = useMutation({
    mutationFn: async () => {
      const rows = staff.filter((s: any) => !byStaff.has(s.id)).map((s: any) => ({
        staff_id: s.id, date, status: "present", check_in: new Date().toISOString(),
      }));
      if (!rows.length) return;
      const { error } = await supabase.from("staff_attendance").insert(rows);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("All marked present");
      qc.invalidateQueries({ queryKey: ["attendance", date] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const counts = {
    present: attendance.filter((a: any) => a.status === "present").length,
    late: attendance.filter((a: any) => a.status === "late").length,
    absent: attendance.filter((a: any) => a.status === "absent").length,
    leave: attendance.filter((a: any) => a.status === "leave").length,
  };

  return (
    <PageLayout title="Staff Attendance" subtitle="Daily check-in / check-out and status">
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-4">
        <Card className="p-3"><div className="text-xs text-muted-foreground">Total</div><div className="text-xl font-bold">{staff.length}</div></Card>
        <Card className="p-3"><div className="text-xs text-muted-foreground">Present</div><div className="text-xl font-bold text-green-600">{counts.present}</div></Card>
        <Card className="p-3"><div className="text-xs text-muted-foreground">Late</div><div className="text-xl font-bold text-amber-600">{counts.late}</div></Card>
        <Card className="p-3"><div className="text-xs text-muted-foreground">Absent</div><div className="text-xl font-bold text-destructive">{counts.absent}</div></Card>
        <Card className="p-3"><div className="text-xs text-muted-foreground">Leave</div><div className="text-xl font-bold">{counts.leave}</div></Card>
      </div>

      <Card className="p-4">
        <div className="flex flex-wrap gap-3 mb-4 items-end">
          <div>
            <label className="text-xs text-muted-foreground">Date</label>
            <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="w-[180px]" />
          </div>
          {isAdmin && <Button onClick={() => markAllPresent.mutate()} variant="outline">Mark All Present</Button>}
        </div>

        <div className="border rounded-lg overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Staff</TableHead>
                <TableHead>Role</TableHead>
                <TableHead>Check In</TableHead>
                <TableHead>Check Out</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {staff.length === 0 ? (
                <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No active staff</TableCell></TableRow>
              ) : staff.map((s: any) => {
                const att = byStaff.get(s.id);
                return (
                  <TableRow key={s.id}>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        {s.photo_url ? (
                          <img src={s.photo_url} className="h-8 w-8 rounded-full object-cover" alt="" />
                        ) : (
                          <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs">{s.name.slice(0,2).toUpperCase()}</div>
                        )}
                        <div>
                          <div className="font-medium text-sm">{s.name}</div>
                          <div className="text-xs text-muted-foreground font-mono">{s.staff_id}</div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell><Badge variant="secondary">{s.role}</Badge></TableCell>
                    <TableCell>
                      {att?.check_in ? (
                        <span className="text-sm">{format(new Date(att.check_in), "HH:mm")}</span>
                      ) : isAdmin ? (
                        <Button size="sm" variant="outline" onClick={() => upsertMutation.mutate({ staff_id: s.id, check_in: new Date().toISOString(), status: "present" })}>Check In</Button>
                      ) : "-"}
                    </TableCell>
                    <TableCell>
                      {att?.check_out ? (
                        <span className="text-sm">{format(new Date(att.check_out), "HH:mm")}</span>
                      ) : att?.check_in && isAdmin ? (
                        <Button size="sm" variant="outline" onClick={() => upsertMutation.mutate({ staff_id: s.id, check_out: new Date().toISOString() })}>Check Out</Button>
                      ) : "-"}
                    </TableCell>
                    <TableCell>
                      {isAdmin ? (
                        <Select value={att?.status ?? ""} onValueChange={(v) => upsertMutation.mutate({ staff_id: s.id, status: v })}>
                          <SelectTrigger className="w-[130px]"><SelectValue placeholder="—" /></SelectTrigger>
                          <SelectContent>
                            {STATUSES.map((s) => <SelectItem key={s} value={s}>{s}</SelectItem>)}
                          </SelectContent>
                        </Select>
                      ) : att?.status ? <Badge>{att.status}</Badge> : "-"}
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </Card>
    </PageLayout>
  );
}
