import { Flag, FileText } from "lucide-react"

import { cn } from "@/lib/utils"
import { tasks, milestones, reports, timeline } from "@/data/project"

const MONTH_ABBR = [
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
]

// Constrói segmentos de ano a partir do mês inicial (ago/2025) e total de meses.
function buildYearSegments() {
  const segments: { year: number; span: number; startMonthIndex: number }[] = []
  let monthOfYear = timeline.startMonthOfYear // 8 = agosto
  let year = Number(timeline.startYear)
  let current = { year, span: 0, startMonthIndex: 1 }
  for (let m = 1; m <= timeline.totalMonths; m++) {
    if (current.span === 0) current.startMonthIndex = m
    current.span++
    if (monthOfYear === 12) {
      segments.push(current)
      year++
      monthOfYear = 1
      current = { year, span: 0, startMonthIndex: m + 1 }
    } else {
      monthOfYear++
    }
  }
  if (current.span > 0) segments.push(current)
  return segments
}

const pct = (n: number) => (n / timeline.totalMonths) * 100

interface GanttProps {
  activeTaskId?: string | null
  compact?: boolean
}

export function Gantt({ activeTaskId, compact }: GanttProps) {
  const yearSegments = buildYearSegments()

  return (
    <div className="overflow-x-auto rounded-xl border border-border bg-card">
      <div className={cn("min-w-[760px]", compact && "min-w-[680px]")}>
        {/* Year + month axis */}
        <div className="grid grid-cols-[180px_1fr] border-b border-border bg-secondary/40">
          <div className="flex items-end px-4 py-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Task
          </div>
          <div>
            {/* Years */}
            <div className="flex">
              {yearSegments.map((s) => (
                <div
                  key={s.year}
                  className="border-l border-border py-1.5 text-center text-xs font-semibold text-foreground"
                  style={{ width: `${pct(s.span)}%` }}
                >
                  {s.year}
                </div>
              ))}
            </div>
            {/* Months */}
            <div className="flex border-t border-border/60">
              {Array.from({ length: timeline.totalMonths }, (_, i) => {
                const monthOfYear =
                  ((timeline.startMonthOfYear - 1 + i) % 12)
                return (
                  <div
                    key={i}
                    className="border-l border-border/40 py-1 text-center text-[10px] text-muted-foreground"
                    style={{ width: `${pct(1)}%` }}
                  >
                    {MONTH_ABBR[monthOfYear][0]}
                  </div>
                )
              })}
            </div>
          </div>
        </div>

        {/* Task rows */}
        <div className="relative">
          {/* Report vertical lines (over the whole rows area) */}
          <div className="pointer-events-none absolute inset-0 ml-[180px]">
            {reports.map((r) => (
              <div
                key={r.label}
                className="absolute top-0 bottom-0 border-l border-dashed border-brand/50"
                style={{ left: `${pct(r.month)}%` }}
                title={r.label}
              />
            ))}
          </div>

          {tasks.map((t, idx) => {
            const isActive = activeTaskId === t.id
            return (
              <div
                key={t.id}
                className={cn(
                  "grid grid-cols-[180px_1fr] items-center border-b border-border/60 transition-colors",
                  idx % 2 === 1 && "bg-muted/40",
                  isActive && "bg-brand/5"
                )}
              >
                <div className="flex items-center gap-2 px-4 py-3">
                  <span
                    className={cn(
                      "flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[11px] font-bold",
                      isActive
                        ? "bg-brand text-brand-foreground"
                        : "bg-secondary text-primary"
                    )}
                  >
                    {t.id}
                  </span>
                  <span
                    className={cn(
                      "truncate text-xs",
                      isActive
                        ? "font-semibold text-foreground"
                        : "text-muted-foreground"
                    )}
                    title={t.title}
                  >
                    {t.title}
                  </span>
                </div>
                <div className="relative h-10">
                  <div
                    className={cn(
                      "absolute top-1/2 h-3.5 -translate-y-1/2 rounded-full transition-all",
                      isActive
                        ? "bg-brand shadow-sm ring-2 ring-brand/30"
                        : "bg-primary/70"
                    )}
                    style={{
                      left: `${pct(t.startMonth - 1)}%`,
                      width: `${pct(t.endMonth - t.startMonth + 1)}%`,
                    }}
                  />
                </div>
              </div>
            )
          })}

          {/* Milestones row */}
          <div className="grid grid-cols-[180px_1fr] items-center border-b border-border/60">
            <div className="flex items-center gap-1.5 px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
              <Flag className="h-3.5 w-3.5 text-energy" />
              Milestones
            </div>
            <div className="relative h-9">
              {milestones.map((m) => (
                <div
                  key={m.id}
                  className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2"
                  style={{ left: `${pct(m.month - 0.5)}%` }}
                  title={`${m.id} · month ${m.month}`}
                >
                  <div className="flex flex-col items-center">
                    <div className="h-2.5 w-2.5 rotate-45 rounded-[2px] bg-energy" />
                    <span className="mt-0.5 text-[9px] font-medium text-muted-foreground">
                      {m.id}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Reports row */}
          <div className="grid grid-cols-[180px_1fr] items-center">
            <div className="flex items-center gap-1.5 px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
              <FileText className="h-3.5 w-3.5 text-brand" />
              Reports
            </div>
            <div className="relative h-9">
              {reports.map((r) => (
                <div
                  key={r.label}
                  className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap text-center"
                  style={{ left: `${pct(r.month)}%` }}
                >
                  <span className="rounded bg-brand/10 px-1.5 py-0.5 text-[9px] font-medium text-brand">
                    {r.label}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
