import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Trash2, Timer, Search } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { format } from "date-fns";

interface TimeEntry {
  id: string;
  user_id: string;
  association_id: string | null;
  description: string | null;
  start_time: string;
  end_time: string | null;
  duration_seconds: number | null;
  is_running: boolean;
  associations?: { name: string } | null;
  profiles?: { full_name: string | null } | null;
}

function formatDuration(seconds: number | null) {
  if (!seconds && seconds !== 0) return "—";
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) return `${h}h ${m}m ${s}s`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

export default function TimeTrackingPage() {
  const { toast } = useToast();
  const [entries, setEntries] = useState<TimeEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  const fetchEntries = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("time_entries")
      .select("*, associations(name)")
      .order("start_time", { ascending: false })
      .limit(500);

    if (error) {
      toast({ title: "Error loading entries", description: error.message, variant: "destructive" });
    } else {
      // Fetch profile names separately
      const userIds = [...new Set((data || []).map((d: any) => d.user_id))];
      const { data: profiles } = await supabase
        .from("profiles")
        .select("user_id, full_name")
        .in("user_id", userIds);
      const profileMap = new Map((profiles || []).map((p: any) => [p.user_id, p.full_name]));
      setEntries(
        (data || []).map((e: any) => ({
          ...e,
          profiles: { full_name: profileMap.get(e.user_id) || null },
        }))
      );
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchEntries();
  }, []);

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this time entry?")) return;
    const { error } = await supabase.from("time_entries").delete().eq("id", id);
    if (error) {
      toast({ title: "Delete failed", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Entry deleted" });
      fetchEntries();
    }
  };

  const filtered = entries.filter((e) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      (e.description || "").toLowerCase().includes(q) ||
      (e.associations?.name || "").toLowerCase().includes(q) ||
      (e.profiles?.full_name || "").toLowerCase().includes(q)
    );
  });

  const totalSeconds = filtered.reduce((sum, e) => sum + (e.duration_seconds || 0), 0);

  return (
    <div className="p-6 space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold flex items-center gap-2">
            <Timer className="h-6 w-6" /> Time Tracking
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            All time entries logged from the timer in the top bar.
          </p>
        </div>
        <div className="text-right">
          <p className="text-xs text-muted-foreground">Total tracked</p>
          <p className="text-xl font-mono font-semibold">{formatDuration(totalSeconds)}</p>
        </div>
      </div>

      <Card className="p-3">
        <div className="relative max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
          <Input
            placeholder="Search description, client, or user…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-8 pl-9 text-[13px]"
          />
        </div>
      </Card>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="text-[12px]">User</TableHead>
              <TableHead className="text-[12px]">Client</TableHead>
              <TableHead className="text-[12px]">Description</TableHead>
              <TableHead className="text-[12px]">Start</TableHead>
              <TableHead className="text-[12px]">End</TableHead>
              <TableHead className="text-[12px]">Duration</TableHead>
              <TableHead className="text-[12px] w-12"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground text-sm">Loading…</TableCell></TableRow>
            ) : filtered.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground text-sm">No time entries yet.</TableCell></TableRow>
            ) : (
              filtered.map((e) => (
                <TableRow key={e.id}>
                  <TableCell className="text-[13px]">{e.profiles?.full_name || "—"}</TableCell>
                  <TableCell className="text-[13px]">{e.associations?.name || <span className="text-muted-foreground">—</span>}</TableCell>
                  <TableCell className="text-[13px] max-w-md truncate">{e.description || <span className="text-muted-foreground">—</span>}</TableCell>
                  <TableCell className="text-[12px] text-muted-foreground">{format(new Date(e.start_time), "MMM d, yyyy h:mm a")}</TableCell>
                  <TableCell className="text-[12px] text-muted-foreground">
                    {e.end_time ? format(new Date(e.end_time), "MMM d, yyyy h:mm a") : <Badge variant="default" className="text-[10px]">Running</Badge>}
                  </TableCell>
                  <TableCell className="text-[13px] font-mono">{formatDuration(e.duration_seconds)}</TableCell>
                  <TableCell>
                    <Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive" onClick={() => handleDelete(e.id)}>
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
