import React, { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ArrowDown, ArrowUp, ArrowUpDown, CircleHelp } from 'lucide-react';

const HEADER_TIP_MAX_WIDTH = 300;
const HEADER_TIP_VIEWPORT_MARGIN = 12;

export function TableHeaderTip({ tip, title }: { tip: string; title: string }) {
  const anchorRef = useRef<HTMLSpanElement>(null);
  const [visible, setVisible] = useState(false);
  const [style, setStyle] = useState<React.CSSProperties>({});

  const reposition = useCallback(() => {
    const el = anchorRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const maxWidth = Math.min(HEADER_TIP_MAX_WIDTH, window.innerWidth - HEADER_TIP_VIEWPORT_MARGIN * 2);
    let left = rect.left;
    left = Math.max(
      HEADER_TIP_VIEWPORT_MARGIN,
      Math.min(left, window.innerWidth - HEADER_TIP_VIEWPORT_MARGIN - maxWidth),
    );
    setStyle({ top: rect.bottom + 6, left, maxWidth });
  }, []);

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

  return (
    <>
      <span
        ref={anchorRef}
        className="ldb-th-tip"
        tabIndex={0}
        aria-label={`${title}说明`}
        onClick={(e) => e.stopPropagation()}
        onMouseEnter={() => { reposition(); setVisible(true); }}
        onMouseLeave={() => setVisible(false)}
        onFocus={() => { reposition(); setVisible(true); }}
        onBlur={() => setVisible(false)}
      >
        <CircleHelp size={14} aria-hidden />
      </span>
      {visible && createPortal(
        <div className="ldb-kpi-tooltip ldb-kpi-tooltip--portal" style={style} role="tooltip">
          {tip}
        </div>,
        document.body,
      )}
    </>
  );
}

export function HeaderWithTip({
  title,
  tip,
  sortable,
  sortActive,
  sortDir,
  onSort,
}: {
  title: string;
  tip?: string;
  sortable?: boolean;
  sortActive?: boolean;
  sortDir?: 'asc' | 'desc';
  onSort?: () => void;
}) {
  const label = (
    <span className={`ldb-th-label ${tip ? 'ldb-th-with-tip' : ''}`}>
      {title}
      {tip ? <TableHeaderTip tip={tip} title={title} /> : null}
    </span>
  );

  if (!sortable || !onSort) return label;

  return (
    <button
      type="button"
      className={`ldb-th-sort ${sortActive ? 'is-active' : ''}`}
      onClick={onSort}
    >
      {label}
      <span className="ldb-th-sort-icon" aria-hidden>
        {sortActive
          ? (sortDir === 'asc' ? <ArrowUp size={14} /> : <ArrowDown size={14} />)
          : <ArrowUpDown size={14} />}
      </span>
    </button>
  );
}
