import { useEffect, useState } from 'react';
import type { PeriodOption } from './time-range';

interface Props {
  periods: PeriodOption[];
  activeKey: string;
  onPick: (key: string) => void;
}

export function PeriodSlider({ periods, activeKey, onPick }: Props) {
  const sorted = [...periods].reverse();
  const activeIdx = Math.max(0, sorted.findIndex((p) => p.key === activeKey));
  const last = sorted.length - 1;
  const [idx, setIdx] = useState(activeIdx);
  useEffect(() => { setIdx(activeIdx); }, [activeIdx]);
  const previewed = sorted[idx] ?? sorted[activeIdx];

  const commit = (nextIdx: number) => {
    const period = sorted[nextIdx];
    if (period && period.key !== activeKey) onPick(period.key);
  };

  return (
    <div className="flex flex-col gap-2 rounded-xl border border-border bg-card p-3 mb-4">
      <div className="flex justify-center mb-0.5">
        <span className="text-sm font-bold text-foreground">{previewed?.longLabel ?? ''}</span>
      </div>
      <input
        type="range"
        min={0}
        max={last}
        step={1}
        value={idx}
        onChange={(e) => setIdx(Number(e.target.value))}
        onMouseUp={() => commit(idx)}
        onTouchEnd={() => commit(idx)}
        onKeyUp={() => commit(idx)}
        className="w-full cursor-pointer accent-emerald-600"
        aria-label="Select period"
      />
      <div className="grid -mt-0.5 text-[10px] text-muted-foreground" style={{ gridTemplateColumns: `repeat(${sorted.length}, 1fr)` }}>
        {sorted.map((p, i) => {
          const stride = Math.max(1, Math.ceil(sorted.length / 8));
          const visible = i === 0 || i === last || i === idx || i % stride === 0;
          return (
            <span
              key={p.key}
              className={(i === idx ? 'font-bold text-emerald-700 ' : '') + 'text-center whitespace-nowrap overflow-hidden text-ellipsis'}
              style={{ visibility: visible ? 'visible' : 'hidden' }}
            >
              {p.label}
            </span>
          );
        })}
      </div>
    </div>
  );
}
