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

export function ProjectsListWidget() {
  const [projects, setProjects] = useState<any[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    supabase.from("projects").select("id, title, status, priority, due_date, associations(name)")
      .neq("status", "completed").order("due_date", { ascending: true }).limit(8)
      .then(({ data }) => setProjects(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">
          <FolderOpen className="w-4 h-4 text-purple-600" /> Projects
        </div>
        <Badge variant="secondary" className="text-2xs h-5">{projects.length}</Badge>
      </div>
      <div className="divide-y divide-border flex-1 overflow-auto">
        {projects.length === 0 ? (
          <p className="p-4 text-[13px] text-muted-foreground text-center">No projects</p>
        ) : projects.map((p) => (
          <div key={p.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/projects/${p.id}`)}>
            <div className="min-w-0 flex-1">
              <p className="text-[13px] font-medium text-foreground truncate">{p.title}</p>
              <div className="flex items-center gap-1.5 mt-0.5">
                <Badge variant="outline" className="text-2xs py-0 h-4">{p.status}</Badge>
                {p.associations?.name && <span className="text-2xs text-muted-foreground truncate">{p.associations.name}</span>}
              </div>
            </div>
            {p.due_date && <span className="text-2xs text-muted-foreground">{formatShortDateEST(p.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/projects")}>
        View All Projects <ArrowRight className="w-3 h-3 ml-1" />
      </Button>
    </div>
  );
}
