'use client';

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type CSSProperties,
  type ReactNode,
} from 'react';
import { cn } from '@/lib/utils/cn';

/** Shared pieces of the Legacy Apps page (the design's icons, dropdowns and modals). */

const svg = (d: ReactNode, viewBox = '0 0 24 24') => (
  <svg viewBox={viewBox} aria-hidden="true">
    {d}
  </svg>
);
export const ICON = {
  search: svg(
    <>
      <circle cx="10.8" cy="10.8" r="6.8" />
      <path d="m16 16 5 5" />
    </>,
  ),
  close: svg(<path d="m6 6 12 12M18 6 6 18" />),
  ext: svg(<path d="M14 4h6v6M20 4 11 13M18 13v6H5V6h6" />),
  info: svg(
    <>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 11v5m0-8h.01" />
    </>,
  ),
  back: svg(<path d="m15 18-6-6 6-6" />),
  download: svg(<path d="M12 3v12m-5-5 5 5 5-5M4 17v4h16v-4" />),
  empty: svg(
    <>
      <path
        d="m22 84 58-34 58 34-58 34z"
        fill="var(--surface-3,#eef1f5)"
        stroke="var(--border,#d0d5dd)"
      />
      <path
        d="M48 64V23l48-16v47L48 82z"
        fill="var(--surface-2,#f9fafb)"
        stroke="var(--border-strong,#cbd5e1)"
        strokeWidth="2"
      />
      <path
        d="m48 64 32 19 48-28-32-19z"
        fill="var(--surface,#fff)"
        stroke="var(--border,#d0d5dd)"
      />
    </>,
    '0 0 160 130',
  ),
};

/** Small inline styles for bits the design CSS has no class for. */
export const S = {
  sub: {
    display: 'block',
    marginTop: 4,
    color: 'var(--text-muted)',
    fontSize: 12,
    fontWeight: 400,
  },
  pre: {
    maxHeight: 260,
    overflow: 'auto',
    margin: '6px 0 0',
    padding: 12,
    borderRadius: 8,
    background: 'var(--surface-3,#eef1f5)',
    fontSize: 12,
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-all',
  },
  more: { display: 'flex', justifyContent: 'center', padding: '16px 0' },
  /** Settings tables capitalize every 2nd column (settings-pages.css); keep ours as typed. */
  keep: { textTransform: 'none' },
  soon: { color: 'var(--text-muted)', fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap' },
} satisfies Record<string, CSSProperties>;

/** "Coming soon" marker for design parts with no backend yet. */
export function Soon({ children = 'Coming soon' }: { children?: ReactNode }) {
  return (
    <span className="badge" style={S.soon}>
      {children}
    </span>
  );
}

/** One open dropdown per menu group; a click outside it closes it. */
export function useMenu() {
  const [menu, setMenu] = useState<string | null>(null);
  useEffect(() => {
    if (!menu) return;
    const onClick = (e: MouseEvent) => {
      const t = e.target as Element | null;
      if (!t?.closest(`[data-la-menu="${menu}"]`)) setMenu(null);
    };
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setMenu(null);
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [menu]);
  const toggle = useCallback((id: string) => setMenu((cur) => (cur === id ? null : id)), []);
  const close = useCallback(() => setMenu(null), []);
  return { menu, toggle, close };
}

/** A "Filter by" dropdown of the Logs tab (checkbox options or plain buttons). */
export function LogDropdown({
  id,
  label,
  open,
  onToggle,
  children,
  search = false,
}: {
  id: string;
  label: ReactNode;
  open: string | null;
  onToggle: (id: string) => void;
  children: ReactNode;
  search?: boolean;
}) {
  return (
    <div className="la-dropdown-wrap" data-la-menu={id}>
      <button type="button" aria-expanded={open === id} onClick={() => onToggle(id)}>
        {label} <i />
      </button>
      <div className={cn('la-dropdown', search && 'la-dropdown-search')} hidden={open !== id}>
        {children}
      </div>
    </div>
  );
}

/** Checkbox options that pick one value (clicking the picked one clears it). */
export function PickOne<T extends string>({
  options,
  value,
  onChange,
}: {
  options: ReadonlyArray<{ value: T; label: string }>;
  value: T | '';
  onChange: (value: T | '') => void;
}) {
  return (
    <>
      {options.map((o) => (
        <label key={o.value} className="check">
          <input
            type="checkbox"
            checked={value === o.value}
            onChange={() => onChange(value === o.value ? '' : o.value)}
          />
          <span className="check__box" />
          <span>{o.label}</span>
        </label>
      ))}
    </>
  );
}

/** Dropdown button label: "Method: GET" when something is picked. */
export const pickedLabel = (label: string, picked: string | undefined) =>
  picked ? `${label}: ${picked}` : label;

/** The design's date range; no date filter on the API yet. */
export function DatesSoon() {
  return (
    <div className="la-dates" title="Date range filter: coming soon">
      <input type="date" disabled aria-label="From date (coming soon)" />
      <span>to</span>
      <input type="date" disabled aria-label="To date (coming soon)" />
      <Soon />
    </div>
  );
}

export function NoLogs({
  title = 'No logs match your search.',
  text = 'Change your search criteria and try again.',
}: {
  title?: ReactNode;
  text?: ReactNode;
}) {
  return (
    <div className="la-no-logs">
      {ICON.empty}
      <div>
        <h3>{title}</h3>
        <p>{text}</p>
      </div>
    </div>
  );
}

/** Open modals, newest last: Escape closes only the top one. */
const modalStack: number[] = [];
let modalSeq = 0;

/** The design's modal (backdrop, head with close). Children hold .la-modal-body / -foot. */
export function LaModal({
  open,
  title,
  onClose,
  children,
}: {
  open: boolean;
  title: ReactNode;
  onClose: () => void;
  children: ReactNode;
}) {
  const close = useRef(onClose);
  useEffect(() => {
    close.current = onClose;
  }, [onClose]);
  const [id] = useState(() => ++modalSeq);
  useEffect(() => {
    if (!open) return;
    modalStack.push(id);
    document.body.classList.add('la-modal-open');
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && modalStack[modalStack.length - 1] === id) close.current();
    };
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('keydown', onKey);
      modalStack.splice(modalStack.indexOf(id), 1);
      if (!modalStack.length) document.body.classList.remove('la-modal-open');
    };
  }, [open, id]);
  if (!open) return null;
  return (
    <div className="la-modal-backdrop">
      <section className="la-modal" role="dialog" aria-modal="true" aria-labelledby={`la-m-${id}`}>
        <header className="la-modal-head">
          <h2 id={`la-m-${id}`}>{title}</h2>
          <button
            type="button"
            className="icon-btn icon-btn--ghost"
            aria-label="Close"
            onClick={onClose}
          >
            {ICON.close}
          </button>
        </header>
        {children}
      </section>
    </div>
  );
}

interface Confirm {
  title: string;
  body: ReactNode;
  buttons: Array<{ label: string; primary?: boolean }>;
  done: (action: number | null) => void;
}

/** `ask(title, body, buttons)` resolves with the button index, or null when dismissed. */
export function useConfirm() {
  const [state, setState] = useState<Confirm | null>(null);
  const ask = useCallback(
    (title: string, body: ReactNode, buttons: Confirm['buttons']) =>
      new Promise<number | null>((resolve) =>
        setState({
          title,
          body,
          buttons,
          done: (action) => {
            setState(null);
            resolve(action);
          },
        }),
      ),
    [],
  );
  const element = (
    <LaModal open={state !== null} title={state?.title} onClose={() => state?.done(null)}>
      <div className="la-modal-body">{state?.body}</div>
      <footer className="la-modal-foot">
        {state?.buttons.map((b, i) => (
          <button
            key={b.label}
            type="button"
            className={b.primary ? 'btn-crm btn-crm--primary' : 'btn-crm btn-crm--outline'}
            onClick={() => state?.done(i)}
          >
            {b.label}
          </button>
        ))}
      </footer>
    </LaModal>
  );
  return [ask, element] as const;
}
