"use client";

import { motion } from "motion/react";
import { ChartFrame } from "@/components/charts/chart-frame";
import { linearScale } from "@/lib/chart-utils";

export type GanttTask = { label: string; start: number; end: number };

type GanttChartProps = {
  tasks: GanttTask[];
  /** Tick labels along the time axis (aligned to integer time units). */
  ticks?: { at: number; label: string }[];
  today?: number;
  width?: number;
  height?: number;
  className?: string;
};

const M = { top: 28, right: 18, bottom: 12, left: 132 };

/** GanttChart — bars positioned on a time scale, growing scaleX from their start, staggered top→down. */
export function GanttChart({ tasks, ticks, today, width = 720, height, className }: GanttChartProps) {
  const min = Math.min(...tasks.map((t) => t.start));
  const max = Math.max(...tasks.map((t) => t.end));
  const sx = linearScale([min, max], [M.left, width - M.right]);
  const rowH = 34;
  const h = height ?? M.top + M.bottom + tasks.length * rowH;

  return (
    <ChartFrame width={width} height={h} label="Diagrama de Gantt" className={className}>
      {({ inView, reduce }) => (
        <>
          {ticks?.map((t) => (
            <g key={t.label}>
              <line x1={sx(t.at)} x2={sx(t.at)} y1={M.top - 6} y2={h - M.bottom} stroke="var(--ink-100)" />
              <text x={sx(t.at)} y={M.top - 12} textAnchor="middle" fontSize={11} fill="var(--ink-500)">{t.label}</text>
            </g>
          ))}
          {today != null && (
            <line x1={sx(today)} x2={sx(today)} y1={M.top - 6} y2={h - M.bottom} stroke="var(--accent-500)" strokeWidth={1.5} strokeDasharray="4 3" />
          )}
          {tasks.map((t, i) => {
            const y = M.top + i * rowH;
            const x0 = sx(t.start);
            const x1 = sx(t.end);
            return (
              <g key={t.label}>
                <text x={M.left - 12} y={y + rowH / 2} textAnchor="end" dominantBaseline="middle" fontSize={12} fill="var(--ink-700)">{t.label}</text>
                <motion.rect
                  x={x0} y={y + 5} width={Math.max(x1 - x0, 2)} height={rowH - 12} rx={5}
                  fill="var(--accent-500)"
                  initial={reduce ? false : { scaleX: 0 }}
                  animate={inView ? { scaleX: 1 } : { scaleX: 0 }}
                  transition={{ duration: 0.55, delay: 0.1 + i * 0.1, ease: [0.22, 1, 0.36, 1] }}
                  style={{ transformOrigin: `${x0}px 0px` }}
                />
              </g>
            );
          })}
        </>
      )}
    </ChartFrame>
  );
}
