import { useState, useCallback, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useChecklists } from "@/hooks/useChecklists";
import { CheckSquare, RefreshCw, CheckCircle2, Clock, ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Progress } from "@/components/ui/progress";
import { Checkbox } from "@/components/ui/checkbox";
import RecordImportButton from "@/components/RecordImportButton";

import TaskListSection from "@/components/tasks/TaskListSection";
import WorkflowProgressDashboard from "@/components/tasks/WorkflowProgressDashboard";
import WorkflowTemplateList from "@/components/tasks/WorkflowTemplateList";

export default function TasksPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const [activeTab, setActiveTab] = useState("my-tasks");

  // ─── Checklists state ───
  const { fetchChecklists, updateChecklist, loading: checklistsLoading } = useChecklists();
  const [checklists, setChecklists] = useState<any[]>([]);
  const [expandedCards, setExpandedCards] = useState<Set<string>>(new Set());

  const loadChecklists = useCallback(async () => {
    const data = await fetchChecklists();
    setChecklists(data);
  }, [fetchChecklists]);

  useEffect(() => {
    if (activeTab === "checklists") loadChecklists();
  }, [activeTab]);

  const toggleExpanded = (id: string) => {
    setExpandedCards(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const toggleItem = async (checklistId: string, itemIdx: number) => {
    const checklist = checklists.find(c => c.id === checklistId);
    if (!checklist) return;
    const items = [...((checklist.items as any[]) || [])];
    items[itemIdx] = { ...items[itemIdx], done: !items[itemIdx].done };

    // Optimistic update
    setChecklists(prev => prev.map(c => c.id === checklistId ? { ...c, items } : c));

    const allDone = items.length > 0 && items.every((i: any) => i.done);
    try {
      await updateChecklist(checklistId, { items, status: allDone ? "completed" : "active" });
    } catch {
      loadChecklists(); // revert on error
    }
  };

  const handleImportTasks = async (rows: Record<string, string>[]) => {
    const { data: assocs } = await supabase.from("associations").select("id, name").eq("status", "active");
    const assocMap = new Map((assocs || []).map((a: any) => [a.name.toLowerCase(), a.id]));

    const toInsert = rows.map((row) => {
      const assocId = assocMap.get((row.association_name || "").toLowerCase()) || "";
      return {
        association_id: assocId,
        title: row.title || "Untitled Task",
        description: row.description || null,
        status: row.status || "pending",
        priority: row.priority || "medium",
        due_date: row.due_date || null,
      };
    }).filter((r) => r.association_id);

    if (!toInsert.length) throw new Error("No valid rows to import.");
    const { error } = await supabase.from("tasks").insert(toInsert);
    if (error) throw error;
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <CheckSquare className="h-6 w-6 text-primary" /> Task Management
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Manage tasks, checklists, and automated workflows.</p>
        </div>
        <div className="flex gap-2">
          <RecordImportButton
            title="Import Tasks"
            description="Upload a CSV or Excel file with task records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "association_name", label: "Association Name", required: true },
              { key: "description", label: "Description" },
              { key: "status", label: "Status" },
              { key: "priority", label: "Priority" },
              { key: "due_date", label: "Due Date" },
            ]}
            onImport={handleImportTasks}
            templateFileName="tasks_import_template.csv"
          />
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList>
          <TabsTrigger value="my-tasks">My Tasks</TabsTrigger>
          <TabsTrigger value="workflows">Active Workflows</TabsTrigger>
          <TabsTrigger value="templates">Workflow Templates</TabsTrigger>
          <TabsTrigger value="checklists">Checklists</TabsTrigger>
        </TabsList>

        <TabsContent value="my-tasks">
          <TaskListSection />
        </TabsContent>

        <TabsContent value="workflows">
          <WorkflowProgressDashboard />
        </TabsContent>

        <TabsContent value="templates">
          <WorkflowTemplateList />
        </TabsContent>

        <TabsContent value="checklists" className="space-y-4">
          <div className="flex justify-end">
            <Button variant="outline" size="sm" onClick={loadChecklists}>
              <RefreshCw className="h-4 w-4 mr-2" /> Refresh
            </Button>
          </div>

          {checklistsLoading ? (
            <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>
          ) : checklists.length === 0 ? (
            <Card>
              <CardContent className="py-12 text-center text-muted-foreground">
                No checklists found. Create them from the Checklists page.
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-2">
              {checklists.map((cl: any) => {
                const items: { text: string; done: boolean }[] = Array.isArray(cl.items) ? cl.items : [];
                const totalItems = items.length;
                const completedItems = items.filter((i) => i.done).length;
                const pct = totalItems > 0 ? Math.round((completedItems / totalItems) * 100) : 0;
                const expanded = expandedCards.has(cl.id);

                return (
                  <Card key={cl.id}>
                    <CardContent className="py-3 px-4">
                      <div
                        className="flex items-center justify-between cursor-pointer"
                        onClick={() => toggleExpanded(cl.id)}
                      >
                        <div className="flex items-center gap-3">
                          {pct === 100 ? (
                            <CheckCircle2 className="h-5 w-5 text-emerald-500 shrink-0" />
                          ) : (
                            <Clock className="h-5 w-5 text-muted-foreground shrink-0" />
                          )}
                          <div>
                            <p className={`font-medium ${pct === 100 ? "line-through text-muted-foreground" : "text-foreground"}`}>
                              {cl.title}
                            </p>
                            {cl.description && <p className="text-xs text-muted-foreground">{cl.description}</p>}
                          </div>
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="text-sm text-muted-foreground whitespace-nowrap">
                            {completedItems}/{totalItems}
                          </span>
                          <Progress value={pct} className="w-32 h-2" />
                          {expanded ? <ChevronUp className="h-4 w-4 text-muted-foreground" /> : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
                        </div>
                      </div>

                      {expanded && items.length > 0 && (
                        <div className="mt-3 ml-8 space-y-2 border-t pt-3">
                          {items.map((item, idx) => (
                            <div key={idx} className="flex items-center gap-2">
                              <Checkbox
                                checked={item.done}
                                onCheckedChange={() => toggleItem(cl.id, idx)}
                              />
                              <span className={`text-sm ${item.done ? "line-through text-muted-foreground" : "text-foreground"}`}>
                                {item.text}
                              </span>
                            </div>
                          ))}
                        </div>
                      )}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}