'use client';

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type MouseEvent as ReactMouseEvent,
  type PointerEvent as ReactPointerEvent,
  type ReactNode,
  type RefObject,
} from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';

/** Below this width the window docks to the bottom of the screen and can't be dragged. */
const MOBILE_WIDTH = 768;
/** Stays reachable however far it is dragged. */
const KEEP_ON_SCREEN = 120;

/** What a page holds to ask the open window before it opens something else. */
export interface ComposerWindowHandle {
  /**
   * Brings the window back. True when the page must leave it open: `same` asks for this window
   * again, or it holds a draft, which also shows the discard bar.
   */
  holdOpen: (same: boolean) => boolean;
}

export function ComposerWindow({
  open,
  onClose,
  title,
  children,
  footer,
  className,
  confirmClose,
  onMaximizedChange,
  composer,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  title: ReactNode;
  size?: string;
  children: ReactNode | ((ctx: { maximized: boolean }) => ReactNode);
  footer?: ReactNode;
  className?: string;
  confirmClose?: boolean | (() => boolean);
  onMaximizedChange?: (maximized: boolean) => void;
  composer: RefObject<ComposerWindowHandle | null>;
}) {
  const panelRef = useRef<HTMLElement>(null);
  const headRef = useRef<HTMLElement>(null);
  const [minimized, setMinimized] = useState(false);
  const [maximized, setMaximized] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
  const drag = useRef<{ dx: number; dy: number } | null>(null);
  /** Anything typed, ticked or picked counts as a draft, as in the design. */
  const touched = useRef(false);

  const dirty = useCallback(
    () => touched.current || (typeof confirmClose === 'function' ? confirmClose() : !!confirmClose),
    [confirmClose],
  );

  const askToDiscard = useCallback(() => {
    setMinimized(false);
    setConfirming(true);
  }, []);

  const requestClose = useCallback(() => {
    if (dirty()) askToDiscard();
    else onClose();
  }, [dirty, onClose, askToDiscard]);

  // A page mounts every composer closed, so only the open one takes the ref.
  useEffect(() => {
    if (!open) return;
    const handle: ComposerWindowHandle = {
      holdOpen: (same) => {
        setMinimized(false);
        if (same) return true;
        if (!dirty()) return false;
        setConfirming(true);
        return true;
      },
    };
    composer.current = handle;
    return () => {
      if (composer.current === handle) composer.current = null;
    };
  }, [open, dirty, composer]);

  // The page behind stays usable, so leaving it mustn't drop a draft without asking.
  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      const link = (e.target as Element).closest?.('a[href]');
      if (!link || panelRef.current?.contains(link)) return;
      if (e.metaKey || e.ctrlKey || e.shiftKey || link.getAttribute('target') === '_blank') return;
      // These stay on the page.
      if (/^(mailto:|tel:|#)/.test(link.getAttribute('href') ?? '')) return;
      if (link.hasAttribute('download')) return;
      if (!dirty()) return;
      e.preventDefault();
      e.stopPropagation();
      askToDiscard();
    };
    const onUnload = (e: BeforeUnloadEvent) => {
      if (dirty()) e.preventDefault();
    };
    document.addEventListener('click', onClick, true);
    window.addEventListener('beforeunload', onUnload);
    return () => {
      document.removeEventListener('click', onClick, true);
      window.removeEventListener('beforeunload', onUnload);
    };
  }, [open, dirty, askToDiscard]);

  useEffect(() => {
    if (open) return;
    touched.current = false;
    drag.current = null;
    setMinimized(false);
    setMaximized(false);
    setConfirming(false);
    setPos(null);
    onMaximizedChange?.(false);
  }, [open, onMaximizedChange]);

  // Docked low over the middle column, right of the record card.
  useLayoutEffect(() => {
    const panel = panelRef.current;
    if (!open || !panel || window.innerWidth < MOBILE_WIDTH) return;
    setPos({
      left: Math.max(16, window.innerWidth - panel.offsetWidth - 160),
      top: Math.max(64, window.innerHeight - panel.offsetHeight - 56),
    });
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const t = window.setTimeout(() => {
      const panel = panelRef.current;
      const first = panel?.querySelector<HTMLElement>('.acx-input--title, .task-compose__title');
      (first ?? panel?.querySelector<HTMLElement>('[contenteditable]'))?.focus();
    }, 60);
    return () => window.clearTimeout(t);
  }, [open]);

  const setMax = useCallback(
    (next: boolean) => {
      setMaximized(next);
      setMinimized(false);
      onMaximizedChange?.(next);
    },
    [onMaximizedChange],
  );

  const clamp = useCallback((left: number, top: number) => {
    const panel = panelRef.current;
    const width = panel?.offsetWidth ?? 580;
    const headHeight = headRef.current?.offsetHeight ?? 48;
    return {
      left: Math.max(KEEP_ON_SCREEN - width, Math.min(left, window.innerWidth - KEEP_ON_SCREEN)),
      top: Math.max(8, Math.min(top, window.innerHeight - headHeight - 8)),
    };
  }, []);

  useEffect(() => {
    if (!open) return;
    const onResize = () => setPos((p) => (p ? clamp(p.left, p.top) : p));
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [open, clamp]);

  // As the editor grows, the window moves up so its submit button stays on screen.
  useEffect(() => {
    const panel = panelRef.current;
    if (!open || !panel || maximized) return;
    const keepFooter = () =>
      setPos((p) => {
        if (!p || drag.current) return p;
        const top = Math.max(8, window.innerHeight - panel.offsetHeight - 8);
        return p.top > top ? { ...p, top } : p;
      });
    const observer = new ResizeObserver(keepFooter);
    observer.observe(panel);
    return () => observer.disconnect();
  }, [open, maximized]);

  // Only when focus is in the window or nowhere: Esc in a cell editor behind it isn't for us.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape' || e.defaultPrevented) return;
      const focus = document.activeElement;
      if (focus !== document.body && !panelRef.current?.contains(focus)) return;
      if (maximized) setMax(false);
      else requestClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, maximized, setMax, requestClose]);

  const fromButton = (target: EventTarget) =>
    Boolean((target as Element).closest?.('button, input, select, textarea, a'));

  const onPointerDown = (e: ReactPointerEvent<HTMLElement>) => {
    if (e.button !== 0 || maximized || fromButton(e.target) || !panelRef.current) return;
    if (window.innerWidth < MOBILE_WIDTH) return;
    const r = panelRef.current.getBoundingClientRect();
    drag.current = { dx: e.clientX - r.left, dy: e.clientY - r.top };
    e.currentTarget.setPointerCapture(e.pointerId);
  };

  const onPointerMove = (e: ReactPointerEvent<HTMLElement>) => {
    if (!drag.current) return;
    setPos(clamp(e.clientX - drag.current.dx, e.clientY - drag.current.dy));
  };

  const onPointerUp = (e: ReactPointerEvent<HTMLElement>) => {
    if (!drag.current) return;
    drag.current = null;
    if (e.currentTarget.hasPointerCapture(e.pointerId)) {
      e.currentTarget.releasePointerCapture(e.pointerId);
    }
  };

  const onHeadDoubleClick = (e: ReactMouseEvent<HTMLElement>) => {
    if (!fromButton(e.target)) setMax(!maximized);
  };

  const body = typeof children === 'function' ? children({ maximized }) : children;

  if (!open) return null;

  const kind = typeof title === 'string' ? title.toLowerCase() : 'draft';

  return (
    <section
      ref={panelRef}
      className={cn(
        'acx is-open',
        minimized && 'is-min',
        maximized && 'pw-max',
        drag.current && 'pw-dragging',
        className,
      )}
      role="dialog"
      aria-label={typeof title === 'string' ? title : undefined}
      style={!maximized && pos ? { left: pos.left, top: pos.top } : undefined}
      onInput={() => {
        touched.current = true;
      }}
      onChange={() => {
        touched.current = true;
      }}
      onClick={(e) => {
        const target = e.target as Element;
        const picked = '.acx-chip button, .acx-attendee button, [role=listbox] button';
        if (target.closest(`${picked}, .meeting-week__col`)) touched.current = true;
      }}
      onKeyDown={(e) => {
        // Backspace in an empty address box removes the last chip.
        if (e.key === 'Backspace' && (e.target as Element).closest('.acx-chips')) {
          touched.current = true;
        }
      }}
    >
      <header
        ref={headRef}
        className="acx__head"
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
        onDoubleClick={onHeadDoubleClick}
      >
        <span className="acx__grip" aria-hidden />
        <button
          type="button"
          className="acx__icon"
          aria-label={minimized ? 'Expand window' : 'Minimize window'}
          title={minimized ? 'Expand' : 'Minimize'}
          onClick={() => {
            if (maximized) {
              setMaximized(false);
              onMaximizedChange?.(false);
            }
            setMinimized((m) => !m);
          }}
        >
          <CrmIcon name="chevron-down" className="iconSize-18" />
        </button>
        <h3 className="acx__title">{title}</h3>
        <button
          type="button"
          className="acx__icon"
          aria-label={maximized ? 'Restore' : 'Maximize'}
          title={maximized ? 'Restore' : 'Maximize'}
          onClick={() => setMax(!maximized)}
        >
          <CrmIcon name={maximized ? 'minimize' : 'maximize'} className="iconSize-18" />
        </button>
        <button
          type="button"
          className="acx__icon"
          aria-label="Close window"
          title="Close"
          onClick={requestClose}
        >
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="acx__body">{body}</div>
      {confirming ? (
        <div className="acx-confirm">
          <p>
            <strong>Discard this {kind}?</strong> Your changes will be lost.
          </p>
          <button
            type="button"
            className="acx-btn acx-btn--sm"
            autoFocus
            onClick={() => setConfirming(false)}
          >
            Keep editing
          </button>
          <button type="button" className="acx-btn acx-btn--sm acx-btn--danger" onClick={onClose}>
            Discard
          </button>
        </div>
      ) : null}
      {footer ? <footer className="acx__foot">{footer}</footer> : null}
    </section>
  );
}
