'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { todayIsoIn } from '@/features/list-page/listZone';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { cn } from '@/lib/utils/cn';
import { useEscapeLayer } from './primitives';
import {
  PERF_PRESETS,
  calendarCells,
  monthTitle,
  pickDay,
  resolvePreset,
  type PerfPreset,
} from '../performance';

const WEEKDAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];

function monthOf(day: string, fallback: string): { y: number; m: number } {
  const [y, m] = (/^\d{4}-\d{2}-\d{2}$/.test(day) ? day : fallback).split('-').map(Number);
  return { y: y!, m: m! - 1 };
}

/**
 * DI-3: the design's date range picker (`.seq-dp`, PHP:384-405; `PerfDateRangePicker`,
 * JS:781-983). Dates are ISO days; "today" and the presets are the user's zone. `onChange` fires
 * when both ends are picked, on a preset and on Clear (with two empty strings), as the design.
 */
export function SegDateRangePicker({
  start,
  end,
  onChange,
  allTimeStart,
  startId,
  endId,
}: {
  start: string;
  end: string;
  onChange: (start: string, end: string) => void;
  /** The first day "All time" uses (the design had sample dates there). */
  allTimeStart?: string;
  startId?: string;
  endId?: string;
}) {
  const { timeZone } = useUserPrefs();
  const today = todayIsoIn(timeZone);
  const root = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState<'from' | 'to'>('from');
  const [from, setFrom] = useState(start);
  const [to, setTo] = useState(end);
  const [preset, setPreset] = useState<PerfPreset | null>(null);
  const [view, setView] = useState(() => monthOf(end || start, today));

  useEffect(() => {
    setFrom(start);
    setTo(end);
  }, [start, end]);

  useEscapeLayer(open, () => setOpen(false));
  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (!root.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, [open]);

  const onTrigger = (e: React.MouseEvent) => {
    const inp = (e.target as HTMLElement).closest<HTMLElement>('[data-dp-input]');
    if (inp) setActive(inp.dataset.dpInput === 'to' ? 'to' : 'from');
    setOpen(true);
  };

  const onDay = (day: string) => {
    const next = pickDay({ active, from, to }, day);
    setFrom(next.from);
    setTo(next.to);
    setActive(next.active);
    setPreset(null);
    if (next.from && next.to) {
      setOpen(false);
      onChange(next.from, next.to);
    }
  };

  const onPreset = (value: PerfPreset) => {
    const r = resolvePreset(value, today, allTimeStart);
    setFrom(r.start);
    setTo(r.end);
    setPreset(value);
    if (r.start) setView(monthOf(r.start, today));
    setActive('from');
    setOpen(false);
    onChange(r.start, r.end);
  };

  const onClear = () => {
    setFrom('');
    setTo('');
    setPreset(null);
    setActive('from');
    onChange('', '');
  };

  const title = monthTitle(view.y, view.m);
  const nav = (delta: number) => {
    const d = new Date(view.y, view.m + delta, 1);
    setView({ y: d.getFullYear(), m: d.getMonth() });
  };

  return (
    <div className="seq-dp" data-dp="" ref={root}>
      <div className="seq-dp__inputs crm-shadow-none" data-dp-inputs-trigger="" onClick={onTrigger}>
        <label
          className={cn('seq-dp__input', open && active === 'from' && 'is-active')}
          data-dp-input-wrap="from"
        >
          <CrmIcon name="calendar" className="iconSize-14" />
          <input
            type="text"
            inputMode="numeric"
            placeholder="YYYY-MM-DD"
            value={from}
            data-dp-input="from"
            id={startId}
            aria-label="Start date"
            readOnly
          />
        </label>
        <span className="cad-date-sep">to</span>
        <label
          className={cn('seq-dp__input', open && active === 'to' && 'is-active')}
          data-dp-input-wrap="to"
        >
          <CrmIcon name="calendar" className="iconSize-14" />
          <input
            type="text"
            inputMode="numeric"
            placeholder="YYYY-MM-DD"
            value={to}
            data-dp-input="to"
            id={endId}
            aria-label="End date"
            readOnly
          />
        </label>
      </div>
      <div
        className="seq-dp__body"
        data-dp-popover=""
        hidden={!open}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="seq-dp__presets" data-dp-presets="">
          {PERF_PRESETS.map((p) => (
            <button
              key={p.value}
              type="button"
              className={cn('seq-dp__preset', preset === p.value && 'is-active')}
              data-dp-preset={p.value}
              onClick={() => onPreset(p.value)}
            >
              {p.label}
            </button>
          ))}
        </div>
        <div className="seq-dp__cal" data-dp-cal="">
          <div className="seq-dp__head">
            <button
              type="button"
              className="seq-dp__nav"
              data-dp-nav="-1"
              aria-label="Previous month"
              onClick={() => nav(-1)}
            >
              ‹
            </button>
            <strong aria-live="polite">{title}</strong>
            <button
              type="button"
              className="seq-dp__nav"
              data-dp-nav="1"
              aria-label="Next month"
              onClick={() => nav(1)}
            >
              ›
            </button>
          </div>
          <div className="seq-dp__grid" role="group" aria-label={title}>
            {WEEKDAYS.map((w) => (
              <span key={w} className="seq-dp__wd">
                {w}
              </span>
            ))}
            {calendarCells(view.y, view.m, from, to, today).map((c) => (
              <button
                key={c.iso}
                type="button"
                className={cn(
                  'seq-dp__day',
                  c.out && 'is-out',
                  c.sel && 'is-sel',
                  c.range && 'is-range',
                  c.today && 'is-today',
                )}
                data-dp-day={c.iso}
                aria-pressed={c.sel}
                aria-label={c.label}
                onClick={() => onDay(c.iso)}
              >
                {c.day}
              </button>
            ))}
          </div>
          <button type="button" className="seq-dp__clear" data-dp-clear="" onClick={onClear}>
            Clear
          </button>
        </div>
      </div>
    </div>
  );
}
