import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useNavigate } from "react-router-dom";
import { CheckSquare, ArrowRight } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatShortDateEST } from "@/lib/timezoneUtils";

export function TasksListWidget() {
  const [tasks, setTasks] = useState<any[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    supabase.from("tasks").select("id, title, status, priority, due_date, assigned_to")
      .neq("status", "completed").order("due_date", { ascending: true }).limit(8)
      .then(({ data }) => setTasks(data || []));
  }, []);

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 pt-4 pb-2 flex items-center justify-between">
        <div className="flex items-center gap-2 text-[15px] font-semibold">
          <CheckSquare className="w-4 h-4 text-primary" /> Tasks
        </div>
        <Badge variant="secondary" className="text-2xs h-5">{tasks.length}</Badge>
      </div>
      <div className="divide-y divide-border flex-1 overflow-auto">
        {tasks.length === 0 ? (
          <p className="p-4 text-[13px] text-muted-foreground text-center">No tasks</p>
        ) : tasks.map((t) => (
          <div key={t.id} className="px-4 py-2.5 flex items-center justify-between gap-2 hover:bg-muted/50 transition-colors cursor-pointer" onClick={() => navigate("/dashboard/tasks")}>
            <div className="min-w-0 flex-1">
              <p className="text-[13px] font-medium text-foreground truncate">{t.title}</p>
              <div className="flex items-center gap-1.5 mt-0.5">
                {t.priority && <Badge variant="outline" className="text-2xs py-0 h-4">{t.priority}</Badge>}
              </div>
            </div>
            {t.due_date && <span className="text-2xs text-muted-foreground">{formatShortDateEST(t.due_date)}</span>}
          </div>
        ))}
      </div>
      <Button variant="ghost" className="w-full text-muted-foreground text-[11px] font-semibold h-8 hover:text-primary rounded-t-none border-t" onClick={() => navigate("/dashboard/tasks")}>
        View All Tasks <ArrowRight className="w-3 h-3 ml-1" />
      </Button>
    </div>
  );
}
