'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { type LexicalEditor } from 'lexical';
import { TOGGLE_LINK_COMMAND } from '@lexical/link';
import { normalizeUrl, isValidUrl, INVALID_URL_MESSAGE } from './link-utils';

// Link insert popover component — portaled to document.body so it renders
// above Puck's iframe preview (sidebar z-index can't beat an iframe).
export function LinkInsertPopover({
  editor,
  onClose,
  triggerRef,
}: {
  editor: LexicalEditor;
  onClose: () => void;
  triggerRef: React.RefObject<HTMLElement | null>;
}) {
  const [url, setUrl] = useState('');
  const [openInNewTab, setOpenInNewTab] = useState(true);
  const [error, setError] = useState('');
  const popoverRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);

  // Position relative to trigger using fixed coordinates, clamped to viewport
  useEffect(() => {
    const trigger = triggerRef.current;
    if (!trigger) return;
    const rect = trigger.getBoundingClientRect();
    const popoverWidth = 332; // minWidth (300) + padding (16 * 2)
    const left = Math.max(0, Math.min(rect.left, window.innerWidth - popoverWidth));
    setPos({ top: rect.bottom + 4, left });
  }, [triggerRef]);

  useEffect(() => {
    inputRef.current?.focus();
  }, [pos]);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
        onClose();
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [onClose]);

  const handleApply = useCallback(() => {
    const normalized = normalizeUrl(url);
    if (!normalized) return;

    if (!isValidUrl(normalized)) {
      setError(INVALID_URL_MESSAGE);
      return;
    }

    editor.focus();
    editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
      url: normalized,
      target: openInNewTab ? '_blank' : null,
      rel: openInNewTab ? 'noopener noreferrer' : null,
    });
    onClose();
  }, [editor, url, openInNewTab, onClose]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        handleApply();
      } else if (e.key === 'Escape') {
        onClose();
      }
    },
    [handleApply, onClose]
  );

  if (!pos) return null;

  const popover = (
    <div
      ref={popoverRef}
      style={{
        position: 'fixed',
        top: `${pos.top}px`,
        left: `${pos.left}px`,
        zIndex: 99999,
        background: '#1e293b',
        backdropFilter: 'blur(8px)',
        border: '1px solid rgba(148, 163, 184, 0.25)',
        borderRadius: '12px',
        padding: '16px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
        minWidth: '300px',
      }}
    >
      <input
        ref={inputRef}
        type="text"
        value={url}
        onChange={(e) => {
          setUrl(e.target.value);
          setError('');
        }}
        onKeyDown={handleKeyDown}
        placeholder="Enter URL"
        aria-label="URL"
        style={{
          width: '100%',
          padding: '12px 16px',
          background: 'rgba(15, 23, 42, 0.75)',
          border: `1px solid ${error ? '#f87171' : 'rgba(148, 163, 184, 0.25)'}`,
          borderRadius: '8px',
          color: '#f8fafc',
          fontSize: '16px',
        }}
      />
      {error && (
        <div
          role="alert"
          style={{
            color: '#f87171',
            fontSize: '14px',
            marginTop: '4px',
          }}
        >
          {error}
        </div>
      )}
      <label
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          marginTop: '8px',
          color: '#f8fafc',
          fontSize: '14px',
          cursor: 'pointer',
        }}
      >
        <input
          type="checkbox"
          checked={openInNewTab}
          onChange={(e) => setOpenInNewTab(e.target.checked)}
          aria-label="Open in new tab"
          style={{ cursor: 'pointer', accentColor: '#38bdf8', width: '20px', height: '20px' }}
        />
        Open in new tab
      </label>
      <div style={{ display: 'flex', gap: '8px', marginTop: '12px', justifyContent: 'flex-end' }}>
        <button
          type="button"
          onClick={onClose}
          aria-label="Cancel"
          style={{
            padding: '8px 16px',
            background: 'transparent',
            border: '1px solid #38bdf8',
            borderRadius: '8px',
            color: '#38bdf8',
            cursor: 'pointer',
            fontSize: '14px',
            fontWeight: 600,
          }}
        >
          Cancel
        </button>
        <button
          type="button"
          onClick={handleApply}
          disabled={!url.trim() || !!error}
          aria-label="Apply"
          style={{
            padding: '8px 16px',
            background: url.trim() && !error ? '#38bdf8' : 'rgba(71, 85, 105, 0.4)',
            border: 'none',
            borderRadius: '8px',
            color: url.trim() && !error ? '#0f172a' : 'rgba(226, 232, 240, 0.65)',
            cursor: url.trim() && !error ? 'pointer' : 'not-allowed',
            fontSize: '14px',
            fontWeight: 600,
          }}
        >
          Apply
        </button>
      </div>
    </div>
  );

  return createPortal(popover, document.body);
}
