import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { FIELD_HELP } from '../help/settingHelp';
import './HelpTip.css';

interface HelpTipProps {
  field: string;
  label?: string;
}

export function HelpTip({ field, label }: HelpTipProps) {
  const text = FIELD_HELP[field];
  const triggerRef = useRef<HTMLButtonElement>(null);
  const popupRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [pinned, setPinned] = useState(false);
  const [pos, setPos] = useState({ top: 0, left: 0 });

  const reposition = useCallback(() => {
    const el = triggerRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const popupW = 280;
    let left = rect.left;
    if (left + popupW > window.innerWidth - 12) {
      left = window.innerWidth - popupW - 12;
    }
    left = Math.max(12, left);
    setPos({ top: rect.bottom + 8, left });
  }, []);

  const show = useCallback(() => {
    reposition();
    setOpen(true);
  }, [reposition]);

  const hide = useCallback(() => {
    if (!pinned) setOpen(false);
  }, [pinned]);

  const togglePin = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
      if (pinned) {
        setPinned(false);
        setOpen(false);
      } else {
        reposition();
        setPinned(true);
        setOpen(true);
      }
    },
    [pinned, reposition],
  );

  useEffect(() => {
    if (!pinned) return;
    const onDocClick = (e: MouseEvent) => {
      const t = e.target as Node;
      if (triggerRef.current?.contains(t) || popupRef.current?.contains(t)) return;
      setPinned(false);
      setOpen(false);
    };
    document.addEventListener('mousedown', onDocClick);
    return () => document.removeEventListener('mousedown', onDocClick);
  }, [pinned]);

  useEffect(() => {
    if (!open) return;
    const onScroll = () => reposition();
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', onScroll);
    };
  }, [open, reposition]);

  if (!text) return null;

  return (
    <>
      <button
        ref={triggerRef}
        type="button"
        className="help-tip-trigger"
        aria-label={`Help: ${field}`}
        aria-expanded={open}
        onMouseEnter={show}
        onMouseLeave={hide}
        onClick={togglePin}
        onFocus={show}
        onBlur={hide}
      >
        <span className="help-tip-icon">?</span>
        {label && <span className="help-tip-label">{label}</span>}
      </button>
      {open &&
        createPortal(
          <div
            ref={popupRef}
            className={`help-tip-popup${pinned ? ' help-tip-popup-pinned' : ''}`}
            style={{ top: pos.top, left: pos.left }}
            role="tooltip"
            onMouseEnter={() => setOpen(true)}
            onMouseLeave={hide}
          >
            {text}
          </div>,
          document.body,
        )}
    </>
  );
}

/** @deprecated Use HelpTip on the label instead — hints are shown on ? hover/click only. */
export function FieldHint(_props: { field: string }) {
  return null;
}
