import { Button, Input } from '@learnitive/ui-components';
import React from 'react';

export function LatexVisualLinkEditor({
  anchor,
  initialHref,
  canRemove,
  onApply,
  onRemove,
  onClose,
}: {
  anchor?: { left: number; top: number; bottom: number; right: number };
  initialHref?: string;
  canRemove?: boolean;
  onApply: (href: string) => void;
  onRemove?: () => void;
  onClose: () => void;
}) {
  const [href, setHref] = React.useState(initialHref ?? 'https://');
  const rootRef = React.useRef<HTMLDivElement | null>(null);

  React.useEffect(() => {
    const onPointer = (event: PointerEvent) => {
      if (rootRef.current?.contains(event.target as Node)) return;
      onClose();
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    document.addEventListener('pointerdown', onPointer, true);
    document.addEventListener('keydown', onKey, true);
    return () => {
      document.removeEventListener('pointerdown', onPointer, true);
      document.removeEventListener('keydown', onKey, true);
    };
  }, [onClose]);

  const base = anchor ?? { left: 24, right: 24, top: 24, bottom: 24 };
  const left = Math.min(Math.max(8, base.left), Math.max(8, window.innerWidth - 344));
  const top = base.bottom + 8 + 112 < window.innerHeight
    ? base.bottom + 8
    : Math.max(8, base.top - 120);

  const apply = () => {
    const value = href.trim();
    if (!/^https?:\/\//i.test(value) || /[{}]/.test(value)) return;
    onApply(value);
  };

  return (
    <div
      ref={rootRef}
      className="fixed z-[120] w-80 rounded-lg border bg-popover p-3 text-popover-foreground shadow-xl"
      style={{ left, top }}
      role="dialog"
      aria-label="Edit link"
      data-testid="latex-visual-link-editor"
      onMouseDown={(event) => event.stopPropagation()}
    >
      <div className="mb-2 text-xs font-medium">Link URL</div>
      <Input
        autoFocus
        value={href}
        onChange={(event) => setHref(event.currentTarget.value)}
        onKeyDown={(event) => {
          if (event.key === 'Enter') {
            event.preventDefault();
            apply();
          }
        }}
        placeholder="https://example.com"
        aria-label="Link URL"
      />
      <div className="mt-3 flex justify-between gap-2">
        <div>
          {canRemove && onRemove && (
            <Button variant="ghost" size="sm" onClick={onRemove}>
              Remove link
            </Button>
          )}
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={onClose}>Cancel</Button>
          <Button size="sm" onClick={apply} disabled={!/^https?:\/\//i.test(href.trim()) || /[{}]/.test(href)}>
            Apply
          </Button>
        </div>
      </div>
    </div>
  );
}
