'use client';

import { useEffect, useRef, useState } from 'react';

/**
 * The design's travel-date picker (createCalendar in flight-approval.js):
 * a preset list, a month grid with departure dots, two-click range picking
 * and a "Full month" action. Markup and class names are the design's.
 *
 * Generalised in LEIS-993 so the Travel Policy change log can use it too. Its
 * three variable parts are the PRESETS, the empty label and the dot counts —
 * an approval queue filters on travel dates in the future, a change log on
 * edits in the past, and "Next 30 days" would be an empty filter there. The
 * calendar itself, including click-outside and Escape to close, is the same.
 */
export type DateRange = { from: string; to: string } | null;

const pad = (n: number) => String(n).padStart(2, '0');
const iso = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
const parse = (s: string) => {
  const [y, m, d] = s.split('-').map(Number);
  return new Date(y, m - 1, d);
};

function monthRange(offset: number): { from: string; to: string } {
  const n = new Date();
  const a = new Date(n.getFullYear(), n.getMonth() + offset, 1);
  const b = new Date(n.getFullYear(), n.getMonth() + offset + 1, 0);
  return { from: iso(a), to: iso(b) };
}

export interface DatePreset {
  key: string;
  text: string;
  range: () => DateRange;
}

/** Travel dates: what the approval queue filters on — mostly ahead of today. */
export const TRAVEL_PRESETS: DatePreset[] = [
  { key: 'all', text: 'All dates', range: () => null },
  { key: 'last', text: 'Last month', range: () => monthRange(-1) },
  { key: 'this', text: 'This month', range: () => monthRange(0) },
  { key: 'next', text: 'Next month', range: () => monthRange(1) },
  {
    key: 'n30',
    text: 'Next 30 days',
    range: () => {
      const n = new Date();
      const e = new Date(n);
      e.setDate(e.getDate() + 30);
      return { from: iso(n), to: iso(e) };
    },
  },
];

/** Edit dates: what a change log filters on — always behind today. */
export const PAST_PRESETS: DatePreset[] = [
  { key: 'all', text: 'All dates', range: () => null },
  {
    key: 'l7',
    text: 'Last 7 days',
    range: () => {
      const n = new Date();
      const s = new Date(n);
      s.setDate(s.getDate() - 6);
      return { from: iso(s), to: iso(n) };
    },
  },
  {
    key: 'l30',
    text: 'Last 30 days',
    range: () => {
      const n = new Date();
      const s = new Date(n);
      s.setDate(s.getDate() - 29);
      return { from: iso(s), to: iso(n) };
    },
  },
  { key: 'this', text: 'This month', range: () => monthRange(0) },
  { key: 'last', text: 'Last month', range: () => monthRange(-1) },
];

const sameRange = (a: DateRange, b: DateRange) => (!a && !b) || (!!a && !!b && a.from === b.from && a.to === b.to);

export function dateLabel(
  r: DateRange,
  presets: readonly DatePreset[] = TRAVEL_PRESETS,
  emptyLabel = 'All travel dates',
): string {
  if (!r) return emptyLabel;
  // Index 0 is the "everything" preset, whose range is null and would never
  // match a real one.
  for (let i = 1; i < presets.length; i++) {
    if (sameRange(presets[i].range(), r)) return presets[i].text;
  }
  const opt: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' };
  const a = parse(r.from);
  const b = parse(r.to);
  if (r.from === r.to) return a.toLocaleDateString('en-US', opt);
  return `${a.toLocaleDateString('en-US', opt)} – ${b.toLocaleDateString('en-US', opt)}`;
}

interface DateCalendarProps {
  value: DateRange;
  /** Departures per day, for the dots on the grid. Omit where the rows being
   *  filtered have no per-day meaning worth showing. */
  counts?: Record<string, number>;
  onChange: (range: DateRange) => void;
  /** Defaults to the travel-date set. See the file comment. */
  presets?: readonly DatePreset[];
  /** Shown on the toggle when nothing is selected. */
  emptyLabel?: string;
  ariaLabel?: string;
}

export default function DateCalendar({
  value,
  counts = {},
  onChange,
  presets = TRAVEL_PRESETS,
  emptyLabel = 'All travel dates',
  ariaLabel = 'Travel dates',
}: DateCalendarProps) {
  const root = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [view, setView] = useState(() => {
    const d = new Date();
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });
  const [pickStart, setPickStart] = useState<string | null>(null);
  const [hoverDay, setHoverDay] = useState<string | null>(null);

  useEffect(() => {
    const onDoc = (e: MouseEvent) => {
      if (root.current && !root.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
    document.addEventListener('click', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, []);

  const toggleOpen = () => {
    if (!open) {
      if (value) {
        const f = parse(value.from);
        setView(new Date(f.getFullYear(), f.getMonth(), 1));
      }
      setPickStart(null);
    }
    setOpen(!open);
  };

  const apply = (r: DateRange) => {
    onChange(r);
    setPickStart(null);
    setOpen(false);
  };

  const y = view.getFullYear();
  const m = view.getMonth();
  const first = new Date(y, m, 1).getDay();
  const daysIn = new Date(y, m + 1, 0).getDate();
  const today = iso(new Date());
  const from = pickStart ?? value?.from ?? null;
  const to = pickStart ? (hoverDay && hoverDay >= pickStart ? hoverDay : pickStart) : (value?.to ?? null);

  const hasCounts = Object.keys(counts).length > 0;

  const days: React.ReactNode[] = [];
  for (let i = 0; i < first; i++) days.push(<span key={`b${i}`} className="fra-cal-blank" />);
  for (let d = 1; d <= daysIn; d++) {
    const key = iso(new Date(y, m, d));
    const cls = ['fra-cal-day'];
    if (key === today) cls.push('is-today');
    if (from && to && key >= from && key <= to) cls.push('in-range');
    if (key === from) cls.push('is-start');
    if (key === to) cls.push('is-end');
    const n = counts[key];
    days.push(
      <button
        key={key}
        type="button"
        className={cls.join(' ')}
        data-day={key}
        title={n ? `${n} departure${n > 1 ? 's' : ''}` : undefined}
        onClick={() => {
          if (!pickStart) {
            setPickStart(key);
            setHoverDay(key);
          } else if (key < pickStart) {
            setPickStart(key);
          } else {
            apply({ from: pickStart, to: key });
          }
        }}
        onMouseOver={() => {
          if (pickStart && hoverDay !== key) setHoverDay(key);
        }}
      >
        <span>{d}</span>
        {n ? <i className="fra-cal-dot" /> : null}
      </button>,
    );
  }

  return (
    <div ref={root} className={`fra-cal${open ? ' open' : ''}${value ? ' has-value' : ''}`}>
      <button type="button" className="fra-dd-toggle fra-cal-toggle" aria-haspopup="dialog" aria-expanded={open} aria-label={ariaLabel} onClick={toggleOpen}>
        <i className="bi bi-calendar3" />
        <span className="fra-dd-label">{dateLabel(value, presets, emptyLabel)}</span>
        <i className="bi bi-chevron-down fra-dd-caret" />
      </button>
      {open && (
        <div className="fra-cal-pop" role="dialog" aria-label={`Choose ${ariaLabel.toLowerCase()}`}>
          <div className="fra-cal-presets">
            {presets.map((p) => {
              const on = sameRange(p.range(), value) && !pickStart;
              return (
                <button key={p.key} type="button" className={`fra-cal-preset${on ? ' active' : ''}`} data-preset={p.key} onClick={() => apply(p.range())}>
                  {p.text}
                </button>
              );
            })}
          </div>
          <div className="fra-cal-main">
            <div className="fra-cal-head">
              <button type="button" className="fra-cal-nav" aria-label="Previous month" onClick={() => setView(new Date(y, m - 1, 1))}>
                <i className="bi bi-chevron-left" />
              </button>
              <strong>{view.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}</strong>
              <button type="button" className="fra-cal-nav" aria-label="Next month" onClick={() => setView(new Date(y, m + 1, 1))}>
                <i className="bi bi-chevron-right" />
              </button>
            </div>
            <div className="fra-cal-week">
              <span>Su</span>
              <span>Mo</span>
              <span>Tu</span>
              <span>We</span>
              <span>Th</span>
              <span>Fr</span>
              <span>Sa</span>
            </div>
            <div className="fra-cal-grid">{days}</div>
            <div className="fra-cal-foot">
              <span className="fra-cal-hint">
                {pickStart ? (
                  'Now pick the end date'
                ) : hasCounts ? (
                  <>
                    <i className="fra-cal-dot" /> Has departures &middot; click two dates for a range
                  </>
                ) : (
                  // No dots on the grid, so no legend to explain. The change
                  // log has nothing per-day worth counting, and "Has
                  // departures" beside an empty swatch reads as a broken
                  // feature rather than a hint.
                  'Click two dates for a range'
                )}
              </span>
              <button
                type="button"
                className="fra-cal-apply"
                onClick={() => apply({ from: iso(new Date(y, m, 1)), to: iso(new Date(y, m + 1, 0)) })}
              >
                Full month
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
