"use client";

import { useEffect, useRef, useState } from "react";
import { PackagePlus, X } from "lucide-react";
import { saveModule } from "@/lib/api";

export type NewDocumentKind = "scenario" | "class";

interface NewModelModalProps {
  isOpen: boolean;
  onClose: () => void;
  /** Kept for callers; always creates a model in the workspace. */
  defaultKind?: NewDocumentKind;
  onScenarioCreated?: (name: string, clearCanvas: boolean) => void;
  onClassCreated: (className: string) => void;
}

/**
 * Create a model inside the Workspace.
 * Writes an empty .ekmod (CLI SubsystemTemplate) and opens it for editing.
 */
export default function NewModelModal({
  isOpen,
  onClose,
  onClassCreated,
}: NewModelModalProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!isOpen) return;
    setName("");
    setDescription("");
    setLoading(false);
    setError(null);
    const t = window.setTimeout(() => inputRef.current?.focus(), 50);
    return () => window.clearTimeout(t);
  }, [isOpen]);

  const cleanName = name.trim();

  const handleValidate = async () => {
    // Same cleaning as ui-server save_module_file — no client-side name blacklist.
    const safeName = cleanName
      .split("")
      .filter((c) => /[A-Za-z0-9_-]/.test(c))
      .join("");

    if (!safeName) {
      setError("Saisis un nom de modèle.");
      return;
    }

    setLoading(true);
    setError(null);

    const content = {
      description: description.trim() || undefined,
      params: {},
      components: [],
      instances: [],
      edges: [],
      connections: [],
      ports: {} as Record<string, string>,
    };

    const res = await saveModule(safeName, content);
    setLoading(false);

    if (!res.ok) {
      setError(res.error || "Impossible de créer le modèle.");
      return;
    }

    if (typeof window !== "undefined") {
      window.dispatchEvent(new Event("entropyk-modules-updated"));
    }
    onClassCreated(safeName);
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[100] flex items-center justify-center bg-[rgba(23,32,43,0.35)] p-4"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="new-model-title"
        className="relative w-full max-w-md rounded-lg border border-[var(--line)] bg-[var(--panel)] shadow-md"
        onMouseDown={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between border-b border-[var(--line)] bg-[var(--chrome)] px-4 py-3">
          <div className="flex items-center gap-2">
            <PackagePlus size={18} className="text-[var(--accent)]" />
            <div>
              <h3 id="new-model-title" className="text-[14px] font-semibold text-[var(--ink)]">
                Nouveau modèle
              </h3>
              <p className="text-[11px] text-[var(--ink-faint)]">
                Classe Modelica · fichier .ekmod
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded p-1 text-[var(--ink-faint)] hover:bg-[var(--chrome-2)] hover:text-[var(--ink)]"
            aria-label="Fermer"
          >
            <X size={16} />
          </button>
        </div>

        <div className="space-y-4 p-4">
          {error && (
            <div className="rounded border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700">
              {error}
            </div>
          )}

          <div>
            <label htmlFor="new-model-name" className="mb-1 block text-[12px] font-medium text-[var(--ink-dim)]">
              Nom du modèle
            </label>
            <input
              id="new-model-name"
              ref={inputRef}
              type="text"
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setError(null);
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  void handleValidate();
                }
              }}
              placeholder=""
              className="mono w-full rounded border border-[var(--line-strong)] bg-white px-3 py-2 text-[13px] text-[var(--ink)] outline-none focus:border-[var(--accent)]"
            />
            {cleanName.length > 0 && (
              <p className="mono mt-1 text-[11px] text-[var(--ink-faint)]">
                .entropyk/modules/{cleanName}.ekmod
              </p>
            )}
          </div>

          <div>
            <label htmlFor="new-model-desc" className="mb-1 block text-[12px] font-medium text-[var(--ink-dim)]">
              Description <span className="font-normal text-[var(--ink-faint)]">(optionnel)</span>
            </label>
            <input
              id="new-model-desc"
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Circuit chillé eau / eau"
              className="w-full rounded border border-[var(--line-strong)] bg-white px-3 py-2 text-[13px] text-[var(--ink)] outline-none focus:border-[var(--accent)]"
            />
          </div>
        </div>

        <div className="flex items-center justify-end gap-2 border-t border-[var(--line)] bg-[var(--chrome)] px-4 py-3">
          <button
            type="button"
            onClick={onClose}
            className="rounded-md border border-[var(--line)] bg-white px-4 py-2 text-[13px] font-medium text-[var(--ink)] hover:bg-[var(--chrome-2)]"
          >
            Annuler
          </button>
          <button
            type="button"
            onClick={() => void handleValidate()}
            disabled={loading}
            className="min-w-[100px] rounded-md bg-[var(--accent)] px-4 py-2 text-[13px] font-semibold text-white shadow-sm hover:brightness-110 disabled:cursor-wait"
          >
            {loading ? "…" : "Valider"}
          </button>
        </div>
      </div>
    </div>
  );
}
