'use client';

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type PointerEvent as ReactPointerEvent,
} from 'react';
import { ComposerWindow, type ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';

type Size = 'md' | 'lg' | 'xl';

const SIZE_CLASS: Record<Size, string> = {
  md: 'activity-popup--md',
  lg: 'activity-popup--lg',
  xl: 'activity-popup--xl',
};

type PopupProps = {
  id: string;
  open: boolean;
  onClose: () => void;
  title: React.ReactNode;
  size?: Size;
  children: React.ReactNode | ((ctx: { maximized: boolean }) => React.ReactNode);
  footer?: React.ReactNode;
  className?: string;
  onMaximizedChange?: (maximized: boolean) => void;
  /** When true (or returns true), ask before discarding the draft. */
  confirmClose?: boolean | (() => boolean);
  /** Contacts only: the design's floating window. The page holds this ref to ask it first. */
  composer?: React.RefObject<ComposerWindowHandle | null>;
};

/** Activity popup: the design's floating window when `composer` is set, else centered. */
export function DraggablePopup({ composer, ...props }: PopupProps) {
  return composer ? (
    <ComposerWindow {...props} composer={composer} />
  ) : (
    <CenteredPopup {...props} />
  );
}

/**
 * HubSpot-style centered activity popup: drag by the header handle, maximize expands
 * and stays centered (drag disabled while maximized). Backdrop click / Esc closes.
 */
function CenteredPopup({
  id,
  open,
  onClose,
  title,
  size = 'md',
  children,
  footer,
  className,
  onMaximizedChange,
  confirmClose,
}: Omit<PopupProps, 'composer'>) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [maximized, setMaximized] = useState(false);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const drag = useRef<{ startX: number; startY: number; originX: number; originY: number } | null>(
    null,
  );

  const requestClose = useCallback(() => {
    const dirty = typeof confirmClose === 'function' ? confirmClose() : !!confirmClose;
    if (dirty && typeof window !== 'undefined' && !window.confirm('Discard this draft?')) {
      return;
    }
    onClose();
  }, [confirmClose, onClose]);

  useEffect(() => {
    if (!open) {
      setMaximized(false);
      setOffset({ x: 0, y: 0 });
      onMaximizedChange?.(false);
      return;
    }
    document.body.style.overflow = 'hidden';
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') requestClose();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, requestClose, onMaximizedChange]);

  const onPointerDown = useCallback(
    (e: ReactPointerEvent<HTMLButtonElement>) => {
      if (maximized || e.button !== 0) return;
      e.preventDefault();
      drag.current = {
        startX: e.clientX,
        startY: e.clientY,
        originX: offset.x,
        originY: offset.y,
      };
      e.currentTarget.setPointerCapture(e.pointerId);
    },
    [maximized, offset.x, offset.y],
  );

  const onPointerMove = useCallback((e: ReactPointerEvent<HTMLButtonElement>) => {
    if (!drag.current) return;
    const dx = e.clientX - drag.current.startX;
    const dy = e.clientY - drag.current.startY;
    setOffset({ x: drag.current.originX + dx, y: drag.current.originY + dy });
  }, []);

  const onPointerUp = useCallback((e: ReactPointerEvent<HTMLButtonElement>) => {
    if (!drag.current) return;
    drag.current = null;
    try {
      e.currentTarget.releasePointerCapture(e.pointerId);
    } catch {
      /* already released */
    }
  }, []);

  const toggleMaximize = () => {
    setMaximized((m) => {
      const next = !m;
      if (next) setOffset({ x: 0, y: 0 });
      onMaximizedChange?.(next);
      return next;
    });
  };

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

  if (!open) return null;

  return (
    <div
      className={cn('modal-backdrop activity-popup-backdrop is-open')}
      id={id}
      aria-hidden={false}
      onClick={(e) => {
        if (e.target === e.currentTarget) requestClose();
      }}
    >
      <div
        ref={panelRef}
        className={cn(
          'modal activity-popup',
          SIZE_CLASS[size],
          maximized && 'is-maximized',
          className,
        )}
        role="dialog"
        aria-modal="true"
        aria-labelledby={`${id}-title`}
        style={maximized ? undefined : { transform: `translate(${offset.x}px, ${offset.y}px)` }}
      >
        <div className="activity-popup__header">
          <h2 className="activity-popup__title" id={`${id}-title`}>
            {title}
          </h2>
          <button
            type="button"
            className={cn('activity-popup__drag', maximized && 'is-disabled')}
            aria-label="Drag window"
            disabled={maximized}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={onPointerUp}
          >
            <CrmIcon name="grip" className="iconSize-18" />
          </button>
          <div className="activity-popup__actions">
            <button
              type="button"
              className="activity-popup__icon-btn"
              aria-label={maximized ? 'Restore' : 'Maximize'}
              onClick={toggleMaximize}
            >
              <CrmIcon name={maximized ? 'minimize' : 'maximize'} className="iconSize-18" />
            </button>
            <button
              type="button"
              className="activity-popup__icon-btn"
              aria-label="Close"
              onClick={requestClose}
            >
              <CrmIcon name="x" className="iconSize-18" />
            </button>
          </div>
        </div>
        <div className="activity-popup__body">{body}</div>
        {footer ? <div className="activity-popup__footer">{footer}</div> : null}
      </div>
    </div>
  );
}
