import { useEffect } from 'react';
import { Globe2, RefreshCw, Upload, BadgeCheck, Mail, FileDown, PencilLine, Trash2 } from 'lucide-react';
import { useI18n } from '@/lib/i18n';

export type QSOMenuState = { x: number; y: number; ids: number[] } | null;

type Props = {
  menu: QSOMenuState;
  onClose: () => void;
  onUpdateFromCty: (ids: number[]) => void;
  onUpdateFromQRZ: (ids: number[]) => void;
  onUpdateFromClublog?: (ids: number[]) => void;
  onSendTo?: (service: string, ids: number[]) => void;
  onSendRecording?: (ids: number[]) => void;
  onSendEQSL?: (ids: number[]) => void;
  onBulkEdit?: (ids: number[]) => void;
  onExportSelected?: (ids: number[]) => void;
  onExportFiltered?: () => void;
  onExportCabrilloSelected?: (ids: number[]) => void;
  onExportCabrilloFiltered?: () => void;
  onDelete?: (ids: number[]) => void;
};

const UPLOAD_TARGETS: { service: string; name: string }[] = [
  { service: 'qrz', name: 'QRZ.com' },
  { service: 'clublog', name: 'Club Log' },
  { service: 'hrdlog', name: 'HRDLog.net' },
  { service: 'eqsl', name: 'eQSL.cc' },
  { service: 'lotw', name: 'LoTW' },
];

// Lightweight right-click menu for the QSO grids. AG Grid's native context
// menu is an Enterprise feature, so this is a plain floating menu driven by
// onCellContextMenu. Stays open until the user clicks outside, presses Escape,
// or picks a command. (We deliberately do NOT close on scroll/resize: the QSO
// list auto-refreshes and AG Grid fires internal scroll events on refresh,
// which used to dismiss the menu the instant it appeared.)
export function QSOContextMenu({ menu, onClose, onUpdateFromCty, onUpdateFromQRZ, onUpdateFromClublog, onSendTo, onSendRecording, onSendEQSL, onBulkEdit, onExportSelected, onExportFiltered, onExportCabrilloSelected, onExportCabrilloFiltered, onDelete }: Props) {
  const { t } = useI18n();
  useEffect(() => {
    if (!menu) return;
    const close = () => onClose();
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('mousedown', close);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('mousedown', close);
      window.removeEventListener('keydown', onKey);
    };
  }, [menu, onClose]);

  if (!menu) return null;
  const n = menu.ids.length;
  // Keep the menu on-screen near the cursor.
  const x = Math.min(menu.x, window.innerWidth - 248);
  const y = Math.min(menu.y, window.innerHeight - (onSendTo ? 230 : 110));

  return (
    <div
      className="fixed z-[200] min-w-[240px] rounded-md border border-border bg-popover shadow-lg py-1 text-sm"
      style={{ left: x, top: y }}
      onMouseDown={(e) => e.stopPropagation()}
    >
      <div className="px-3 py-1 text-[11px] uppercase tracking-wider text-muted-foreground">
        {t('qctx.selected', { n })}
      </div>
      <button
        className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
        onClick={() => { onUpdateFromCty(menu.ids); onClose(); }}
      >
        <Globe2 className="size-4 text-primary" />
        <span>{t('qctx.fixCountry')}</span>
      </button>
      <button
        className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
        onClick={() => { onUpdateFromQRZ(menu.ids); onClose(); }}
      >
        <RefreshCw className="size-4 text-info" />
        <span>{t('qctx.updateQrz')}</span>
      </button>
      {onUpdateFromClublog && (
        <button
          className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
          onClick={() => { onUpdateFromClublog(menu.ids); onClose(); }}
        >
          <BadgeCheck className="size-4 text-info" />
          <span>{t('qctx.updateClublog')}</span>
        </button>
      )}

      {(onSendRecording || onSendEQSL) && (
        <>
          <div className="my-1 border-t border-border" />
          {onSendEQSL && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onSendEQSL(menu.ids); onClose(); }}
            >
              <Mail className="size-4 text-warning" />
              <span>{t('qctx.sendQslEmail')}</span>
            </button>
          )}
          {onSendRecording && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onSendRecording(menu.ids); onClose(); }}
            >
              <Mail className="size-4 text-danger" />
              <span>{t('qctx.sendRecording')}</span>
            </button>
          )}
        </>
      )}

      {onBulkEdit && (
        <>
          <div className="my-1 border-t border-border" />
          <button
            className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
            onClick={() => { onBulkEdit(menu.ids); onClose(); }}
          >
            <PencilLine className="size-4 text-info" />
            <span>{t('qctx.bulkEdit', { n })}</span>
          </button>
        </>
      )}

      {(onExportSelected || onExportFiltered) && (
        <>
          <div className="my-1 border-t border-border" />
          {onExportSelected && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onExportSelected(menu.ids); onClose(); }}
            >
              <FileDown className="size-4 text-info" />
              <span>{t('qctx.exportSelectedAdif', { n })}</span>
            </button>
          )}
          {onExportFiltered && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onExportFiltered(); onClose(); }}
            >
              <FileDown className="size-4 text-info" />
              <span>{t('qctx.exportFilteredAdif')}</span>
            </button>
          )}
          {onExportCabrilloSelected && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onExportCabrilloSelected(menu.ids); onClose(); }}
            >
              <FileDown className="size-4 text-warning" />
              <span>{t('qctx.exportSelectedCabrillo', { n })}</span>
            </button>
          )}
          {onExportCabrilloFiltered && (
            <button
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onExportCabrilloFiltered(); onClose(); }}
            >
              <FileDown className="size-4 text-warning" />
              <span>{t('qctx.exportFilteredCabrillo')}</span>
            </button>
          )}
        </>
      )}

      {onSendTo && (
        <>
          <div className="my-1 border-t border-border" />
          {UPLOAD_TARGETS.map((target) => (
            <button
              key={target.service}
              className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-accent/50"
              onClick={() => { onSendTo(target.service, menu.ids); onClose(); }}
            >
              <Upload className="size-4 text-success" />
              <span>{t('qctx.sendTo', { name: target.name })}</span>
            </button>
          ))}
        </>
      )}

      {onDelete && (
        <>
          <div className="my-1 border-t border-border" />
          <button
            className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-danger hover:bg-danger-muted"
            onClick={() => { onDelete(menu.ids); onClose(); }}
          >
            <Trash2 className="size-4" />
            <span>{t('qctx.delete', { n })}</span>
          </button>
        </>
      )}
    </div>
  );
}
