"use client";

import { useEffect, useRef, useState } from "react";
import { Link2, ExternalLink, Trash2 } from "lucide-react";
import { type EditorComponentProps } from "./types";
import { usePopoverPosition, PopoverPortal } from "./usePopoverPosition";

/**
 * Toolbar control for inserting, editing, opening, and removing links.
 * Opens a small popover with a URL input rather than a native prompt().
 *
 * Portaled to `document.body` with auto-flip positioning so it's never
 * clipped by a parent modal's overflow.
 */
export default function LinkPopover({ editor }: EditorComponentProps) {
  const [open, setOpen] = useState(false);
  const [url, setUrl] = useState("");

  const triggerRef = useRef<HTMLButtonElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const position = usePopoverPosition(triggerRef, open, popoverRef, {
    estimatedWidth: 288,
    estimatedHeight: 110,
  });

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      const target = e.target as Node;
      if (
        triggerRef.current &&
        !triggerRef.current.contains(target) &&
        popoverRef.current &&
        !popoverRef.current.contains(target)
      ) {
        setOpen(false);
      }
    }
    function handleEscape(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleEscape);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, []);

  useEffect(() => {
    if (open) {
      // Wait a tick so the portal has mounted before focusing.
      const id = window.setTimeout(() => inputRef.current?.focus(), 0);
      return () => window.clearTimeout(id);
    }
  }, [open]);

  if (!editor) return null;

  const isActive = editor.isActive("link");
  const currentHref: string = editor.getAttributes("link").href ?? "";

  const handleOpen = () => {
    setUrl(currentHref);
    setOpen(true);
  };

  const applyLink = () => {
    const trimmed = url.trim();
    if (!trimmed) {
      editor.chain().focus().extendMarkRange("link").unsetLink().run();
      setOpen(false);
      return;
    }
    const href = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
    editor
      .chain()
      .focus()
      .extendMarkRange("link")
      .setLink({ href })
      .run();
    setOpen(false);
  };

  const removeLink = () => {
    editor.chain().focus().extendMarkRange("link").unsetLink().run();
    setOpen(false);
  };

  return (
    <div className="relative shrink-0">
      <button
        ref={triggerRef}
        type="button"
        onClick={handleOpen}
        title="Insert link"
        aria-pressed={isActive}
        className={`
          inline-flex h-8 w-8 sm:h-9 sm:w-9 items-center justify-center rounded-md
          text-zinc-600 transition-colors hover:bg-zinc-100
          
          ${isActive ? "bg-indigo-100 text-indigo-700 " : ""}
        `}
      >
        <Link2 className="h-4 w-4" />
      </button>

      <PopoverPortal open={open} position={position} popoverRef={popoverRef}>
        <div
          className="
            w-64 sm:w-72 rounded-md border border-zinc-200 bg-white p-3
            shadow-lg 
          "
        >
          <label className="mb-1.5 block text-xs font-medium text-zinc-500 ">
            Link URL
          </label>
          <div className="flex items-center gap-2">
            <input
              ref={inputRef}
              type="text"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  applyLink();
                }
              }}
              placeholder="https://example.com"
              className="
                w-full rounded-md border border-zinc-300 bg-white px-2.5 py-1.5
                text-sm text-zinc-900 outline-none
                focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500
                 
              "
            />
          </div>

          <div className="mt-3 flex items-center justify-between gap-2">
            <div className="flex gap-1">
              {isActive && currentHref && (
                <>
                  <a
                    href={currentHref}
                    target="_blank"
                    rel="noopener noreferrer"
                    title="Open link"
                    className="
                      inline-flex h-7 w-7 items-center justify-center rounded-md
                      text-zinc-500 hover:bg-zinc-100  
                    "
                  >
                    <ExternalLink className="h-3.5 w-3.5" />
                  </a>
                  <button
                    type="button"
                    onClick={removeLink}
                    title="Remove link"
                    className="
                      inline-flex h-7 w-7 items-center justify-center rounded-md
                      text-red-500 hover:bg-red-50
                    "
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </>
              )}
            </div>
            <button
              type="button"
              onClick={applyLink}
              className="
                rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white
                transition-colors hover:bg-indigo-700
              "
            >
              Apply
            </button>
          </div>
        </div>
      </PopoverPortal>
    </div>
  );
}
