import { useState } from "react"
import { CalendarRange } from "lucide-react"

import { Section } from "@/components/layout/Section"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Gantt } from "@/components/sections/Gantt"
import { WorkPlanCard } from "@/components/sections/WorkPlanCard"
import { tasks } from "@/data/project"

export function WorkPlan() {
  const [activeTaskId, setActiveTaskId] = useState<string | null>(null)
  const [openTaskId, setOpenTaskId] = useState<string | null>(null)

  const openTask = tasks.find((t) => t.id === openTaskId) ?? null

  return (
    <Section
      id="work-plan"
      eyebrow="Work plan"
      title="Seven tasks across 36 months"
      description="Hover a task to highlight it on the timeline, or open it to focus its schedule. The chart follows the project Gantt — months, milestones (M1–M10) and progress reports."
      className="bg-muted/40"
    >
      {/* Task cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {tasks.map((t, i) => (
          <WorkPlanCard
            key={t.id}
            task={t}
            index={i}
            active={activeTaskId === t.id}
            onActivate={() => setActiveTaskId(t.id)}
            onDeactivate={() => setActiveTaskId((cur) => (cur === t.id ? null : cur))}
            onOpen={() => setOpenTaskId(t.id)}
          />
        ))}
      </div>

      {/* Inline Gantt (desktop hover highlight) */}
      <div className="mt-10">
        <div className="mb-4 flex items-center gap-2 text-sm font-semibold uppercase tracking-widest text-muted-foreground">
          <CalendarRange className="h-4 w-4 text-brand" />
          Project timeline
        </div>
        <Gantt activeTaskId={activeTaskId} />
      </div>

      {/* Focused dialog (mobile click / any click) */}
      <Dialog
        open={openTaskId !== null}
        onOpenChange={(o) => !o && setOpenTaskId(null)}
      >
        <DialogContent className="max-w-3xl">
          {openTask && (
            <>
              <DialogHeader>
                <div className="mb-1">
                  <Badge variant="brand">{openTask.id}</Badge>
                </div>
                <DialogTitle>{openTask.title}</DialogTitle>
                <DialogDescription>{openTask.description}</DialogDescription>
              </DialogHeader>
              <div className="mt-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                Scheduled: month {openTask.startMonth} → {openTask.endMonth}
              </div>
              <Gantt activeTaskId={openTask.id} compact />
            </>
          )}
        </DialogContent>
      </Dialog>
    </Section>
  )
}
