import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { FolderKanban, Plus, Search, CalendarDays, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { format } from "date-fns";

const statusBadge: Record<string, string> = {
  active: "bg-emerald-100 text-emerald-700",
  "in-progress": "bg-blue-100 text-blue-700",
  completed: "bg-muted text-muted-foreground",
  "on-hold": "bg-amber-100 text-amber-700",
};

export default function ClientProjectsPage() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [projects, setProjects] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState({ title: "", description: "", association_id: "" });

  const fetchData = async () => {
    setLoading(true);
    const [projRes, assocRes] = await Promise.all([
      supabase.from("projects").select("*, associations(name)").order("created_at", { ascending: false }),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
    ]);
    setProjects(projRes.data || []);
    setAssociations(assocRes.data || []);
    setLoading(false);
  };

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

  const filtered = projects.filter((p) => p.title.toLowerCase().includes(search.toLowerCase()));

  const handleCreate = async () => {
    if (!form.title) { toast({ variant: "destructive", title: "Project name is required" }); return; }
    const assocId = form.association_id || (associations.length ? associations[0].id : null);
    if (!assocId) { toast({ variant: "destructive", title: "Select an association" }); return; }

    const { data: { user } } = await supabase.auth.getUser();

    const { error } = await supabase.from("projects").insert({
      title: form.title,
      description: form.description || null,
      association_id: assocId,
      created_by: user?.id,
    });
    if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
    toast({ title: "Project created" });
    setDialogOpen(false);
    setForm({ title: "", description: "", association_id: "" });
    fetchData();
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <FolderKanban className="w-6 h-6 text-primary" /> Projects
          </h1>
          <p className="text-sm text-muted-foreground mt-1">View and create community projects.</p>
        </div>
        <Button className="gap-2" onClick={() => { setForm({ title: "", description: "", association_id: associations[0]?.id || "" }); setDialogOpen(true); }}>
          <Plus className="h-4 w-4" /> New Project
        </Button>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input placeholder="Search projects..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No projects found.</CardContent></Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((p) => (
            <Card key={p.id} className="group hover:shadow-md transition-shadow cursor-pointer" onClick={() => navigate(`/client/projects/${p.id}`)}>
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between">
                  <h3 className="font-semibold text-foreground leading-tight">{p.title}</h3>
                  <Badge className={statusBadge[p.status] || "bg-muted text-muted-foreground"} variant="secondary">
                    {p.status === "in-progress" ? "In Progress" : p.status?.charAt(0).toUpperCase() + p.status?.slice(1)}
                  </Badge>
                </div>
                {p.description && <p className="text-sm text-muted-foreground line-clamp-2 mt-1">{p.description}</p>}
              </CardHeader>
              <CardContent className="pt-0 space-y-2">
                {p.associations?.name && <p className="text-xs text-muted-foreground">{p.associations.name}</p>}
                <div className="flex items-center justify-between">
                  <div className="flex items-center text-xs text-muted-foreground gap-1">
                    <CalendarDays className="h-3 w-3" />
                    <span>{format(new Date(p.created_at), "MMM d, yyyy")}</span>
                  </div>
                  <Button variant="ghost" size="sm" className="gap-1 text-xs">
                    View <ChevronRight className="h-3 w-3" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Create New Project</DialogTitle>
            <DialogDescription>Submit a new project request.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div><Label>Project Name <span className="text-destructive">*</span></Label>
              <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="e.g., Pool Renovation" />
            </div>
            <div><Label>Description</Label>
              <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Describe the project..." rows={3} />
            </div>
            <div><Label>Association</Label>
              <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v })}>
                <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
                <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleCreate}>Create Project</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
