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, MoreHorizontal, Edit, Trash2, CalendarDays, ChevronRight } from "lucide-react";
import RecordImportButton from "@/components/RecordImportButton";
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 { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { format } from "date-fns";

const statusColors: Record<string, string> = {
  active: "border-l-emerald-500",
  "in-progress": "border-l-blue-500",
  completed: "border-l-muted",
  "on-hold": "border-l-amber-500",
};
const statusBadgeColors: 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 ProjectsPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [projects, setProjects] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [boardMembers, setBoardMembers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState({
    title: "", description: "", status: "active", priority: "medium",
    assigned_to: "", budget: "", timeline: "", association_id: "",
    assigned_associations: [] as string[], assigned_board_members: [] as string[],
  });

  const isBoardView = !!boardAssociationIds?.length;

  const fetchData = async () => {
    setLoading(true);
    let projQuery = supabase.from("projects").select("*, associations(name)").order("created_at", { ascending: false });
    let assocQuery = supabase.from("associations").select("id, name").eq("status", "active").order("name");
    let boardQuery = supabase.from("board_members").select("id, member_name, role, association_id").order("member_name");
    if (isBoardView) {
      projQuery = projQuery.in("association_id", boardAssociationIds!);
      assocQuery = assocQuery.in("id", boardAssociationIds!);
      boardQuery = boardQuery.in("association_id", boardAssociationIds!);
    }
    const [projRes, assocRes, boardRes] = await Promise.all([projQuery, assocQuery, boardQuery]);
    setProjects(projRes.data || []);
    setAssociations(assocRes.data || []);
    setBoardMembers(boardRes.data || []);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, [JSON.stringify(boardAssociationIds || [])]);

  const openNew = () => {
    setEditing(null);
    setForm({ title: "", description: "", status: "active", priority: "medium", assigned_to: "", budget: "", timeline: "", association_id: "", assigned_associations: [], assigned_board_members: [] });
    setDialogOpen(true);
  };

  const openEdit = (p: any) => {
    setEditing(p);
    setForm({
      title: p.title, description: p.description || "", status: p.status, priority: p.priority || "medium",
      assigned_to: p.assigned_to || "", budget: p.budget?.toString() || "", timeline: p.timeline || "",
      association_id: p.association_id || "", assigned_associations: p.assigned_associations || [], assigned_board_members: p.assigned_board_members || [],
    });
    setDialogOpen(true);
  };

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

    const payload = {
      title: form.title, description: form.description || null, status: form.status,
      priority: form.priority, assigned_to: form.assigned_to || null,
      budget: form.budget ? parseFloat(form.budget) : null, association_id: assocId,
    };

    if (editing) {
      const { error } = await supabase.from("projects").update(payload).eq("id", editing.id);
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); return; }
      toast({ title: "Project updated" });
    } else {
      const { data: { user } } = await supabase.auth.getUser();
      const { error } = await supabase.from("projects").insert({ ...payload, created_by: user?.id });
      if (error) { toast({ title: "Error", description: error.message, variant: "destructive" }); return; }
      toast({ title: "Project created" });
    }
    setDialogOpen(false);
    fetchData();
  };

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from("projects").delete().eq("id", id);
    if (error) toast({ title: "Error", description: error.message, variant: "destructive" });
    else { toast({ title: "Project deleted" }); fetchData(); }
  };

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

  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">Community Projects</h1>
          <p className="text-sm text-muted-foreground mt-1">View and track ongoing community projects.</p>
        </div>
        <div className="flex gap-2">
          <RecordImportButton
            title="Import Projects"
            description="Upload a CSV or Excel file with project records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "description", label: "Description" },
              { key: "status", label: "Status" },
              { key: "priority", label: "Priority" },
              { key: "budget", label: "Budget" },
            ]}
            onImport={async (rows) => {
              const assocId = associations[0]?.id;
              if (!assocId) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                title: r.title || "Untitled",
                description: r.description || null,
                status: r.status || "active",
                priority: r.priority || "medium",
                budget: r.budget ? parseFloat(r.budget) : null,
                association_id: assocId,
              }));
              const { error } = await supabase.from("projects").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} projects` });
              fetchData();
            }}
            templateFileName="projects_template.xlsx"
          />
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> Add Project</Button>
        </div>
      </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 border-l-4 ${statusColors[p.status] || "border-l-muted"}`}>
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between">
                  <h3 className="font-semibold text-foreground leading-tight">{p.title}</h3>
                  <Badge className={statusBadgeColors[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-3 mt-1">{p.description}</p>}
              </CardHeader>
              <CardContent className="pt-0 space-y-3">
                {p.associations?.name && (
                  <p className="text-xs text-muted-foreground">{p.associations.name}</p>
                )}
                {p.budget && (
                  <p className="text-xs text-muted-foreground">Budget: ${Number(p.budget).toLocaleString()}</p>
                )}
                <div className="flex items-center text-xs text-muted-foreground gap-1">
                  <CalendarDays className="h-3 w-3" />
                  <span>Started: {format(new Date(p.created_at), "MMM d, yyyy")}</span>
                </div>
                <div className="flex items-center justify-between pt-2 border-t">
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="start">
                      <DropdownMenuItem onClick={() => openEdit(p)}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem>
                      <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(p.id)}><Trash2 className="h-4 w-4 mr-2" /> Delete</DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                  <Button variant="default" size="sm" className="gap-1" onClick={() => navigate(isBoardView ? `/homeowner/board/projects/${p.id}` : `/dashboard/projects/${p.id}`)}>
                    View Details <ChevronRight className="h-3 w-3" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit Project" : "Create New Project"}</DialogTitle>
            <DialogDescription>
              {editing ? "Update project details." : "Add a new project to track progress."}
            </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., Roof Replacement 2026" />
            </div>
            <div>
              <Label>Description <span className="text-destructive">*</span></Label>
              <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Briefly describe the project goals..." rows={4} />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Status</Label>
                <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Active</SelectItem>
                    <SelectItem value="in-progress">In Progress</SelectItem>
                    <SelectItem value="completed">Completed</SelectItem>
                    <SelectItem value="on-hold">On Hold</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Budget ($) <span className="text-muted-foreground text-xs">(Optional)</span></Label>
                <Input type="number" value={form.budget} onChange={(e) => setForm({ ...form, budget: e.target.value })} placeholder="0.00" />
              </div>
            </div>
            <div>
              <Label>Timeline / Schedule <span className="text-muted-foreground text-xs">(Optional)</span></Label>
              <Input value={form.timeline || ""} onChange={(e) => setForm({ ...form, timeline: e.target.value })} placeholder="e.g., Q3 2026 - Q4 2026" />
            </div>

            <div className="border-t pt-4">
              <h4 className="font-semibold text-sm mb-3">Assignments (Admin Only)</h4>
              <div>
                <Label>Primary Association (Client ID)</Label>
                <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v })}>
                  <SelectTrigger><SelectValue placeholder="Select Primary Association" /></SelectTrigger>
                  <SelectContent>
                    {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-4 mt-4">
                <div>
                  <Label className="text-sm">Assigned Associations (Clients)</Label>
                  <div className="border rounded-md p-3 max-h-[140px] overflow-y-auto space-y-2 mt-1">
                    {associations.map(a => (
                      <label key={a.id} className="flex items-center gap-2 text-sm cursor-pointer">
                        <Checkbox
                          checked={form.assigned_associations.includes(a.id)}
                          onCheckedChange={(checked) => {
                            setForm(prev => ({
                              ...prev,
                              assigned_associations: checked
                                ? [...prev.assigned_associations, a.id]
                                : prev.assigned_associations.filter(id => id !== a.id)
                            }));
                          }}
                        />
                        <span className="truncate">{a.name}</span>
                      </label>
                    ))}
                  </div>
                </div>
                <div>
                  <Label className="text-sm">Assigned Board Members</Label>
                  <div className="border rounded-md p-3 max-h-[140px] overflow-y-auto space-y-2 mt-1">
                    {boardMembers.map(bm => (
                      <label key={bm.id} className="flex items-center gap-2 text-sm cursor-pointer">
                        <Checkbox
                          checked={form.assigned_board_members.includes(bm.id)}
                          onCheckedChange={(checked) => {
                            setForm(prev => ({
                              ...prev,
                              assigned_board_members: checked
                                ? [...prev.assigned_board_members, bm.id]
                                : prev.assigned_board_members.filter(id => id !== bm.id)
                            }));
                          }}
                        />
                        <span className="truncate">{bm.member_name || "Unnamed"}</span>
                      </label>
                    ))}
                    {boardMembers.length === 0 && <p className="text-xs text-muted-foreground">No board members found.</p>}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
