"use client";

import { ensureBuiltinIndicatorsRegistered } from "@/lib/indicators/builtin";
import {
  addIndicatorInstance,
  createIndicatorInstance,
} from "@/lib/indicators/instances/manager";
import {
  loadIndicatorInstances,
  saveIndicatorInstances,
} from "@/lib/indicators/instances/storage";
import type { IndicatorInstanceScope } from "@/lib/indicators/instances/types";
import { listIndicators } from "@/lib/indicators/registry";
import type { IndicatorDefinition } from "@/lib/indicators/types";
import { useMemo, useState } from "react";
import { createPortal } from "react-dom";

ensureBuiltinIndicatorsRegistered();

const HIDDEN_IDS = new Set(["reference.annotation-fixture"]);

type IndicatorCatalogModalProps = {
  open: boolean;
  onClose: () => void;
  scope: IndicatorInstanceScope;
  onAdded?: () => void;
};

export function IndicatorCatalogModal({
  open,
  onClose,
  scope,
  onAdded,
}: IndicatorCatalogModalProps) {
  const catalog = useMemo(
    () =>
      listIndicators().filter((d) => !HIDDEN_IDS.has(d.id)) as IndicatorDefinition[],
    [],
  );
  const [message, setMessage] = useState<string | null>(null);

  if (!open) {
    return null;
  }

  const addToChart = (definitionId: string) => {
    const created = createIndicatorInstance(scope, definitionId);
    if ("error" in created) {
      setMessage(created.error);
      return;
    }
    const next = addIndicatorInstance(loadIndicatorInstances(scope), created);
    saveIndicatorInstances(scope, next);
    setMessage(`Added to ${scope.symbol} ${scope.timeframe}.`);
    onAdded?.();
  };

  if (typeof document === "undefined") {
    return null;
  }

  return createPortal(
    <>
      <div className="catalog-modal-backdrop" onClick={onClose} aria-hidden />
      <div className="catalog-modal" role="dialog" aria-labelledby="catalog-title">
        <header className="catalog-modal-head">
          <h2 id="catalog-title">Indicator catalog</h2>
          <button type="button" className="toolbar-btn toolbar-btn-sm" onClick={onClose}>
            Close
          </button>
        </header>
        <p className="catalog-modal-meta">
          Adds to current chart ({scope.symbol.replace("_", "/")} · {scope.timeframe}
          {scope.layoutId ? ` · ${scope.layoutId}` : ""}).
        </p>
        {message ? <p className="status">{message}</p> : null}
        <ul className="indicator-catalog">
          {catalog.map((def) => (
            <li key={def.id} className="indicator-catalog-item">
              <div>
                <strong>{def.name}</strong>
                <span className="chart-meta">
                  {def.id} · v{def.version} · {def.renderPlacement}
                </span>
                <p className="chart-meta">{def.description}</p>
              </div>
              <button
                type="button"
                className="toolbar-btn toolbar-btn-sm"
                onClick={() => addToChart(def.id)}
              >
                Add
              </button>
            </li>
          ))}
        </ul>
      </div>
    </>,
    document.body,
  );
}
