'use client';

import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { cn } from '@/lib/utils/cn';
import { Icon } from './icons';

/* ------------------------------------------------------------ menus */

/** Closes an open menu on a click outside `ref` or on Escape (base.js `[data-dropdown]`). */
export function useDismiss(
  ref: React.RefObject<HTMLElement | null>,
  open: boolean,
  close: () => void,
) {
  const closeRef = useRef(close);
  closeRef.current = close;
  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) closeRef.current();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeRef.current();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open, ref]);
}

/**
 * The design's `<div class="dropdown" data-dropdown>`: a toggle button and a
 * `.dropdown__menu` (rendered by `children`, which gets `close`).
 */
export function DesignDropdown({
  className,
  toggleClassName,
  toggleLabel,
  toggle,
  menuClassName,
  floating = false,
  children,
}: {
  className?: string;
  toggleClassName: string;
  toggleLabel?: string;
  toggle: React.ReactNode;
  menuClassName?: string;
  /**
   * HUB-745 (QA #924): the menu floats over the page (fixed, right-aligned to the button,
   * upwards when there is no room below), so a table's scroll box can't cut it off.
   */
  floating?: boolean;
  children: (close: () => void) => React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const toggleRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [place, setPlace] = useState<React.CSSProperties | undefined>(undefined);
  useDismiss(ref, open, () => setOpen(false));
  useLayoutEffect(() => {
    if (!floating || !open) return;
    const position = () => {
      const btn = toggleRef.current?.getBoundingClientRect();
      const menu = menuRef.current;
      if (!btn || !menu) return;
      const height = menu.offsetHeight;
      const below = window.innerHeight - btn.bottom;
      const up = below < height + 8 && btn.top > below;
      setPlace({
        position: 'fixed',
        right: Math.max(8, window.innerWidth - btn.right),
        left: 'auto',
        top: up ? Math.max(8, btn.top - height - 4) : btn.bottom + 4,
        zIndex: 1100,
      });
    };
    position();
    window.addEventListener('scroll', position, true);
    window.addEventListener('resize', position);
    return () => {
      window.removeEventListener('scroll', position, true);
      window.removeEventListener('resize', position);
    };
  }, [floating, open]);
  return (
    <div className={cn('dropdown', className)} data-dropdown ref={ref}>
      <button
        ref={toggleRef}
        type="button"
        className={toggleClassName}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={toggleLabel}
        onClick={() => setOpen((v) => !v)}
      >
        {toggle}
      </button>
      <div
        className={cn('dropdown__menu', menuClassName)}
        role="menu"
        data-dropdown-menu
        hidden={!open}
        ref={menuRef}
        style={floating && open ? place : undefined}
      >
        {children(() => setOpen(false))}
      </div>
    </div>
  );
}

/* ---------------------------------------------------------- dialogs */

/**
 * A native `<dialog>` opened with showModal(), as the design's own `ca-*-modal` dialogs. A click
 * on the backdrop (outside the box) and Escape close it.
 */
export function NativeDialog({
  open,
  onClose,
  className,
  labelledBy,
  children,
}: {
  open: boolean;
  onClose: () => void;
  className: string;
  labelledBy: string;
  children: React.ReactNode;
}) {
  const ref = useRef<HTMLDialogElement>(null);
  useEffect(() => {
    const d = ref.current;
    if (!d) return;
    // The app shell resets <dialog> insets, so centre it in pixels (as SetDialog does).
    const center = () => {
      if (!d.open) return;
      d.style.top = `${Math.max(16, (window.innerHeight - d.offsetHeight) / 2)}px`;
      d.style.left = `${Math.max(16, (window.innerWidth - d.offsetWidth) / 2)}px`;
      d.style.right = 'auto';
      d.style.bottom = 'auto';
      d.style.margin = '0';
      d.style.transform = 'none';
    };
    if (open && !d.open) {
      d.showModal();
      requestAnimationFrame(center);
    } else if (!open && d.open) {
      d.close();
    }
    if (!open) return;
    const ro = new ResizeObserver(() => requestAnimationFrame(center));
    ro.observe(d);
    window.addEventListener('resize', center);
    return () => {
      ro.disconnect();
      window.removeEventListener('resize', center);
    };
  }, [open]);
  return (
    <dialog
      ref={ref}
      className={className}
      aria-labelledby={labelledBy}
      onClose={onClose}
      // HUB-745 (QA #938): Escape closes it wherever focus is (the browser's own cancel is skipped
      // in a search box, and after a quick second press).
      onCancel={(e) => {
        e.preventDefault();
        onClose();
      }}
      onKeyDown={(e) => {
        if (e.key !== 'Escape' || e.defaultPrevented) return;
        e.preventDefault();
        onClose();
      }}
      onClick={(e) => {
        // A click on the backdrop (or the dialog box itself, outside its content) closes it.
        if (e.target === e.currentTarget) onClose();
      }}
    >
      {open ? children : null}
    </dialog>
  );
}

/* ------------------------------------------------------ date range picker */

const PRESETS = [
  { value: 'today', label: 'Today' },
  { value: 'yesterday', label: 'Yesterday' },
  { value: 'this-week', label: 'This week' },
  { value: 'last-week', label: 'Last week' },
  { value: 'this-month', label: 'This month' },
  { value: 'last-month', label: 'Last month' },
  { value: 'last-30-days', label: 'Last 30 days' },
  { value: 'last-3-months', label: 'Last 3 months' },
  { value: 'this-quarter', label: 'This quarter' },
  { value: 'last-quarter', label: 'Last quarter' },
  { value: 'this-year', label: 'This year' },
  { value: 'last-year', label: 'Last year' },
  { value: 'all-time', label: 'All time' },
];

const pad = (n: number) => String(n).padStart(2, '0');
export const toISO = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
export const toMDY = (iso: string) =>
  iso && iso.length >= 10 ? `${iso.slice(5, 7)}/${iso.slice(8, 10)}/${iso.slice(0, 4)}` : '';

function parseISO(iso: string) {
  const parts = iso.split('-');
  if (parts.length !== 3) return null;
  return new Date(Number(parts[0]), parseInt(parts[1] ?? '1', 10) - 1, Number(parts[2]));
}

function parseMDY(text: string) {
  const m = text.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!m) return null;
  const d = new Date(Number(m[3]), Number(m[1]) - 1, Number(m[2]));
  return d.getMonth() === Number(m[1]) - 1 ? toISO(d) : null;
}

/** resolvePresetDates() of settings-connected-apps.js. */
function resolvePreset(preset: string) {
  const t = new Date();
  t.setHours(0, 0, 0, 0);
  const d = (y: number, m: number, day: number) => new Date(y, m, day);
  const y = t.getFullYear();
  const m = t.getMonth();
  const q = Math.floor(m / 3);
  const sow = new Date(t);
  sow.setDate(t.getDate() - t.getDay());
  let s = t;
  let e = t;
  switch (preset) {
    case 'today':
      break;
    case 'yesterday': {
      const a = new Date(t);
      a.setDate(t.getDate() - 1);
      s = a;
      e = a;
      break;
    }
    case 'this-week': {
      const end = new Date(sow);
      end.setDate(sow.getDate() + 6);
      s = sow;
      e = end;
      break;
    }
    case 'last-week': {
      const a = new Date(sow);
      a.setDate(sow.getDate() - 7);
      const end = new Date(sow);
      end.setDate(sow.getDate() - 1);
      s = a;
      e = end;
      break;
    }
    case 'this-month':
      s = d(y, m, 1);
      e = d(y, m + 1, 0);
      break;
    case 'last-month':
      s = d(y, m - 1, 1);
      e = d(y, m, 0);
      break;
    case 'last-30-days': {
      const a = new Date(t);
      a.setDate(t.getDate() - 29);
      s = a;
      break;
    }
    case 'last-3-months': {
      const a = new Date(t);
      a.setMonth(t.getMonth() - 3);
      s = a;
      break;
    }
    case 'this-quarter':
      s = d(y, q * 3, 1);
      e = d(y, q * 3 + 3, 0);
      break;
    case 'last-quarter':
      s = d(y, q * 3 - 3, 1);
      e = d(y, q * 3, 0);
      break;
    case 'this-year':
      s = d(y, 0, 1);
      e = d(y, 11, 31);
      break;
    case 'last-year':
      s = d(y - 1, 0, 1);
      e = d(y - 1, 11, 31);
      break;
    default:
      return { start: '2026-09-16', end: '2026-10-15' };
  }
  return { start: toISO(s), end: toISO(e) };
}

/**
 * The CRM date-range picker of the Connected Apps pages (`DateRangePicker` in
 * settings-connected-apps.js): two MM/DD/YYYY inputs, a preset list and a month calendar.
 * `onChange` runs with ISO dates once a range is complete (or both empty after Clear).
 */
export function DateRangePicker({
  id,
  className = 'cad-date-picker-wrap quick-filters-container ca-date-picker-wrap',
  from: initialFrom,
  to: initialTo,
  fromLabel = 'Start date',
  toLabel = 'End date',
  onChange,
  presets: presetValues,
  initialPreset = 'last-30-days',
  initialView,
}: {
  id: string;
  className?: string;
  /** MM/DD/YYYY, as the design's input values. */
  from: string;
  to: string;
  fromLabel?: string;
  toLabel?: string;
  onChange?: (from: string, to: string) => void;
  /** Only these presets, in this order (Data integration's App syncs: the first 8). Default: all. */
  presets?: readonly string[];
  /** The preset marked at first. */
  initialPreset?: string | null;
  /** The month the calendar opens on. Default: October 2026, as the Connected Apps design. */
  initialView?: Date;
}) {
  const shownPresets = presetValues
    ? presetValues
        .map((v) => PRESETS.find((p) => p.value === v))
        .filter((p): p is (typeof PRESETS)[number] => p !== undefined)
    : PRESETS;
  const ref = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState<'from' | 'to'>('from');
  const [shownActive, setShownActive] = useState(false);
  const [from, setFrom] = useState(() => parseMDY(initialFrom) || '2026-09-16');
  const [to, setTo] = useState(() => parseMDY(initialTo) || '2026-10-15');
  const [fromText, setFromText] = useState(initialFrom);
  const [toText, setToText] = useState(initialTo);
  const [preset, setPreset] = useState<string | null>(initialPreset);
  const [view, setView] = useState(() => initialView ?? new Date(2026, 9, 1));
  useDismiss(ref, open, () => setOpen(false));

  const sync = (f: string, t: string) => {
    setFromText(toMDY(f));
    setToText(toMDY(t));
  };

  const cells = useMemo(() => {
    const first = new Date(view.getFullYear(), view.getMonth(), 1);
    const start = new Date(first);
    start.setDate(1 - first.getDay());
    const today = toISO(new Date());
    return Array.from({ length: 42 }, (_, i) => {
      const c = new Date(start);
      c.setDate(start.getDate() + i);
      const k = toISO(c);
      const sel = k === from || k === to;
      return {
        k,
        day: c.getDate(),
        label: c.toDateString(),
        cls: cn(
          'seq-dp__day',
          c.getMonth() !== view.getMonth() && 'is-out',
          sel && 'is-sel',
          Boolean(from && to && k > from && k < to) && 'is-range',
          k === today && 'is-today',
        ),
        sel,
        // Sheet 24 Nov: a report runs up to today, so later days can't be picked.
        future: k > today,
      };
    });
  }, [view, from, to]);

  const title = view.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });

  const pickDay = (k: string) => {
    if (k > toISO(new Date())) return;
    let f = from;
    let t = to;
    if (active === 'from') {
      f = k;
      if (t && t < k) t = '';
      setActive('to');
    } else {
      if (f && k < f) {
        t = f;
        f = k;
      } else {
        t = k;
      }
      setActive('from');
    }
    setFrom(f);
    setTo(t);
    setPreset(null);
    setShownActive(true);
    sync(f, t);
    if (f && t) onChange?.(f, t);
  };

  const typed = (which: 'from' | 'to', text: string) => {
    const today = toISO(new Date());
    const read = parseMDY(text);
    if (!read) return;
    const parsed = read > today ? today : read;
    if (parsed !== read) (which === 'from' ? setFromText : setToText)(toMDY(parsed));
    const f = which === 'from' ? parsed : from;
    const t = which === 'to' ? parsed : to;
    setFrom(f);
    setTo(t);
    setPreset(null);
    onChange?.(f, t);
  };

  const input = (which: 'from' | 'to') => (
    <label
      className={cn('seq-dp__input', shownActive && active === which && 'is-active')}
      data-dp-input-wrap={which}
    >
      <Icon name="calendar" size={14} />
      <input
        type="text"
        inputMode="numeric"
        placeholder="MM/DD/YYYY"
        value={which === 'from' ? fromText : toText}
        data-dp-input={which}
        aria-label={which === 'from' ? fromLabel : toLabel}
        onChange={(e) => (which === 'from' ? setFromText : setToText)(e.target.value)}
        onBlur={(e) => typed(which, e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') typed(which, e.currentTarget.value);
        }}
      />
    </label>
  );

  return (
    <div className={className} id={id} ref={ref}>
      <div className="seq-dp" data-dp>
        <div
          className="seq-dp__inputs"
          data-dp-inputs-trigger
          onClick={(e) => {
            const inp = (e.target as HTMLElement).closest<HTMLElement>('[data-dp-input]');
            if (inp) {
              setActive(inp.dataset.dpInput === 'to' ? 'to' : 'from');
              setShownActive(true);
            }
            setOpen(true);
          }}
        >
          {input('from')}
          <span className="cad-date-sep">to</span>
          {input('to')}
        </div>
        <div className="seq-dp__body" data-dp-popover hidden={!open}>
          <div className="seq-dp__presets" data-dp-presets>
            {shownPresets.map((p) => (
              <button
                key={p.value}
                type="button"
                className={cn('seq-dp__preset', preset === p.value && 'is-active')}
                data-dp-preset={p.value}
                onClick={() => {
                  const r = resolvePreset(p.value);
                  setFrom(r.start);
                  setTo(r.end);
                  setPreset(p.value);
                  const pd = parseISO(r.start);
                  if (pd) setView(new Date(pd.getFullYear(), pd.getMonth(), 1));
                  setActive('from');
                  setShownActive(true);
                  sync(r.start, r.end);
                  setOpen(false);
                  onChange?.(r.start, r.end);
                }}
              >
                {p.label}
              </button>
            ))}
          </div>
          <div className="seq-dp__cal" data-dp-cal>
            <div className="seq-dp__head">
              <button
                type="button"
                className="seq-dp__nav"
                aria-label="Previous month"
                onClick={() => setView(new Date(view.getFullYear(), view.getMonth() - 1, 1))}
              >
                ‹
              </button>
              <strong aria-live="polite">{title}</strong>
              <button
                type="button"
                className="seq-dp__nav"
                aria-label="Next month"
                onClick={() => setView(new Date(view.getFullYear(), view.getMonth() + 1, 1))}
              >
                ›
              </button>
            </div>
            <div className="seq-dp__grid" role="group" aria-label={title}>
              {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((w) => (
                <span key={w} className="seq-dp__wd">
                  {w}
                </span>
              ))}
              {cells.map((c) => (
                <button
                  key={c.k}
                  type="button"
                  className={c.cls}
                  aria-pressed={c.sel}
                  aria-label={c.label}
                  disabled={c.future}
                  onClick={() => pickDay(c.k)}
                >
                  {c.day}
                </button>
              ))}
            </div>
            <button
              type="button"
              className="seq-dp__clear"
              onClick={() => {
                setFrom('');
                setTo('');
                setPreset(null);
                setActive('from');
                setShownActive(true);
                sync('', '');
                onChange?.('', '');
              }}
            >
              Clear
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------- Chart.js */

/** The subset of Chart.js 4 used here. */
export interface ChartInstance {
  data: {
    labels?: unknown[];
    datasets: Array<{ label?: string; data: number[]; hidden?: boolean; [k: string]: unknown }>;
  };
  update: () => void;
  resize: () => void;
  destroy: () => void;
}
export type ChartCtor = new (ctx: CanvasRenderingContext2D, config: unknown) => ChartInstance;

/** Chart.js (the design's 4.4.8), loaded with the page that draws a chart. */
let chartPromise: Promise<ChartCtor | null> | null = null;

function loadChartJs(): Promise<ChartCtor | null> {
  chartPromise ??= import('chart.js/auto').then(
    (m) => m.default as unknown as ChartCtor,
    () => {
      chartPromise = null;
      return null;
    },
  );
  return chartPromise;
}

/** Chart.js constructor once it has loaded (null until then). */
export function useChartJs() {
  const [ctor, setCtor] = useState<ChartCtor | null>(null);
  useEffect(() => {
    let alive = true;
    loadChartJs().then((c) => {
      if (alive && c) setCtor(() => c);
    });
    return () => {
      alive = false;
    };
  }, []);
  return ctor;
}

export const isDarkTheme = () =>
  typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';

/* ---------------------------------------------------- Owl-style carousel */

const OWL_RESPONSIVE: Array<[number, number, number]> = [
  // [min viewport width, items, margin]
  [1280, 4, 18],
  [992, 3, 16],
  [576, 2, 14],
  [0, 1, 12],
];

/**
 * The recommendations carousel (Owl Carousel 2 with `rewind`, `nav`, no dots), rendered with Owl's
 * markup so settings-connected-apps.css styles it the same.
 */
export function OwlCarousel({ children }: { children: React.ReactNode[] }) {
  const outer = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  const [vw, setVw] = useState(1440);
  const [index, setIndex] = useState(0);

  useLayoutEffect(() => {
    const el = outer.current;
    if (!el) return;
    const measure = () => {
      setWidth(el.clientWidth);
      setVw(window.innerWidth);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    window.addEventListener('resize', measure);
    return () => {
      ro.disconnect();
      window.removeEventListener('resize', measure);
    };
  }, []);

  const [, items, margin] = OWL_RESPONSIVE.find(([min]) => vw >= min) ?? [0, 1, 12];
  const count = children.length;
  const maxIndex = Math.max(0, count - items);
  const at = Math.min(index, maxIndex);
  const itemWidth = width ? (width + margin) / items - margin : 0;
  const step = itemWidth + margin;

  return (
    <div
      className="owl-carousel owl-theme ca-owl-carousel owl-loaded owl-drag"
      data-rec-owl-carousel
      style={{ display: 'block', position: 'relative', width: '100%', zIndex: 1 }}
    >
      <div
        className="owl-stage-outer"
        ref={outer}
        style={{ position: 'relative', overflow: 'hidden' }}
      >
        <div
          className="owl-stage"
          style={{
            transform: `translate3d(${-at * step}px, 0px, 0px)`,
            transition: 'all 0.25s ease 0s',
            width: step * count || undefined,
            position: 'relative',
          }}
        >
          {children.map((child, i) => (
            <div
              key={i}
              className={cn('owl-item', i >= at && i < at + items && 'active')}
              style={{
                width: itemWidth || `calc(${100 / items}% - ${margin}px)`,
                marginRight: margin,
                flex: 'none',
              }}
            >
              <div className="item">{child}</div>
            </div>
          ))}
        </div>
      </div>
      <div className={cn('owl-nav', count <= items && 'disabled')}>
        <button
          type="button"
          role="presentation"
          className="owl-prev"
          aria-label="Previous"
          onClick={() => setIndex(at <= 0 ? maxIndex : at - 1)}
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>
        <button
          type="button"
          role="presentation"
          className="owl-next"
          aria-label="Next"
          onClick={() => setIndex(at >= maxIndex ? 0 : at + 1)}
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </button>
      </div>
    </div>
  );
}

/* ------------------------------------------------------ coming soon */

/**
 * Banner at the top of a screen that has no backend yet: what it shows is the design's sample
 * data, so nobody mistakes it for the account's real numbers.
 */
export function SampleDataBanner({
  title = 'Coming soon — sample data',
  children,
}: {
  title?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="alert alert--warning ca-sample-banner" role="note">
      <span className="alert__icon" aria-hidden="true">
        <Icon name="info" size={16} />
      </span>
      <span>
        <strong>{title}.</strong> {children}
      </span>
    </div>
  );
}
