"use client";



import { useEffect, useRef, useState } from "react";

import { createPortal } from "react-dom";



type DrawingTextEditorModalProps = {

  open: boolean;

  title: string;

  initialText?: string;

  initialColor?: string;

  initialFontSize?: number;

  onCancel: () => void;

  onSubmit: (payload: { text: string; color: string; fontSize: number }) => void;

};



export function DrawingTextEditorModal({

  open,

  title,

  initialText = "",

  initialColor = "#131722",

  initialFontSize = 14,

  onCancel,

  onSubmit,

}: DrawingTextEditorModalProps) {

  const [text, setText] = useState(initialText);

  const [color, setColor] = useState(initialColor);

  const [fontSize, setFontSize] = useState(initialFontSize);

  const inputRef = useRef<HTMLInputElement>(null);



  useEffect(() => {

    if (!open) {

      return;

    }

    setText(initialText);

    setColor(initialColor);

    setFontSize(initialFontSize);

    inputRef.current?.focus();

  }, [open, initialColor, initialFontSize, initialText]);



  useEffect(() => {

    if (!open) {

      return;

    }

    const onKey = (e: KeyboardEvent) => {

      if (e.key === "Escape") {

        e.preventDefault();

        onCancel();

      }

    };

    window.addEventListener("keydown", onKey);

    return () => window.removeEventListener("keydown", onKey);

  }, [open, onCancel]);



  if (!open) {

    return null;

  }



  if (typeof document === "undefined") {

    return null;

  }



  return createPortal(

    <>

      <div

        className="catalog-modal-backdrop drawing-text-backdrop"

        onClick={onCancel}

        aria-hidden

      />

      <div

        className="drawing-text-modal"

        role="dialog"

        aria-labelledby="drawing-text-title"

        aria-modal="true"

        onMouseDown={(e) => e.stopPropagation()}

        onClick={(e) => e.stopPropagation()}

      >

        <h2 id="drawing-text-title">{title}</h2>

        <label className="toolbar-field">

          <span className="toolbar-label">Text</span>

          <input

            ref={inputRef}

            type="text"

            className="toolbar-input drawing-text-input"

            value={text}

            onChange={(e) => setText(e.target.value)}

            onKeyDown={(e) => {

              if (e.key === "Enter") {

                e.preventDefault();

                if (text.trim()) {

                  onSubmit({ text: text.trim(), color, fontSize });

                }

              }

            }}

          />

        </label>

        <label className="toolbar-field">

          <span className="toolbar-label">Color</span>

          <input type="color" value={color} onChange={(e) => setColor(e.target.value)} />

        </label>

        <label className="toolbar-field">

          <span className="toolbar-label">Size</span>

          <select

            value={fontSize}

            onChange={(e) => setFontSize(Number.parseInt(e.target.value, 10))}

          >

            {[11, 12, 14, 16, 18, 22, 28].map((n) => (

              <option key={n} value={n}>

                {n}px

              </option>

            ))}

          </select>

        </label>

        <div className="alert-modal-actions">

          <button type="button" className="toolbar-btn" onClick={onCancel}>

            Cancel

          </button>

          <button

            type="button"

            className="toolbar-btn"

            disabled={!text.trim()}

            onClick={() => onSubmit({ text: text.trim(), color, fontSize })}

          >

            Place on chart

          </button>

        </div>

      </div>

    </>,

    document.body,

  );

}


