"use client";

import { createIndicatorAlertRule, upsertAlertRule } from "@/lib/alerts/manager";
import { getIndicator } from "@/lib/indicators/registry";
import type { IndicatorInstance } from "@/lib/indicators/instances/types";
import type { ChartLayoutId } from "@/lib/chart/layout-profile";
import type { CanonicalSymbol } from "@/lib/market/instruments";
import type { SupportedTimeframe } from "@/lib/market/timeframes";
import { useMemo, useState } from "react";

type CreateIndicatorAlertModalProps = {
  open: boolean;
  onClose: () => void;
  layoutId: ChartLayoutId;
  symbol: CanonicalSymbol;
  timeframe: SupportedTimeframe;
  instance: IndicatorInstance;
};

export function CreateIndicatorAlertModal({
  open,
  onClose,
  layoutId,
  symbol,
  timeframe,
  instance,
}: CreateIndicatorAlertModalProps) {
  const def = getIndicator(instance.definitionId);
  const conditions = useMemo(() => def?.alertConditions ?? [], [def]);
  const [conditionId, setConditionId] = useState(conditions[0]?.conditionId ?? "");
  const [label, setLabel] = useState("");
  const [oneShot, setOneShot] = useState(false);

  if (!open || !def) {
    return null;
  }

  return (
    <div className="alert-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="alert-modal"
        role="dialog"
        aria-labelledby="indicator-alert-title"
        onClick={(e) => e.stopPropagation()}
      >
        <h2 id="indicator-alert-title">Indicator alert — {def.name}</h2>
        <p className="alert-modal-meta">
          Alerts run in the background while this app is open. You will get a sound (if enabled on
          Alerts) and a browser notification when permission is granted. The rule is tied to this
          chart symbol, timeframe, and indicator instance.
        </p>
        {conditions.length === 0 ? (
          <p className="indicator-error">
            This indicator has no alert conditions. For Supply Demand UHV, enable &quot;Enable UHV
            alert conditions&quot; in indicator settings so events are emitted.
          </p>
        ) : (
          <>
            <label className="toolbar-field">
              <span className="toolbar-label">When</span>
              <select value={conditionId} onChange={(e) => setConditionId(e.target.value)}>
                {conditions.map((c) => (
                  <option key={c.conditionId} value={c.conditionId}>
                    {c.label}
                  </option>
                ))}
              </select>
            </label>
            <label className="toolbar-field">
              <span className="toolbar-label">Name (optional)</span>
              <input
                type="text"
                value={label}
                onChange={(e) => setLabel(e.target.value)}
                placeholder={conditions.find((c) => c.conditionId === conditionId)?.label}
              />
            </label>
            <label className="toolbar-check-row">
              <input
                type="checkbox"
                checked={oneShot}
                onChange={(e) => setOneShot(e.target.checked)}
              />
              <span>One-shot (disable after first trigger)</span>
            </label>
          </>
        )}
        <div className="alert-modal-actions">
          <button type="button" className="toolbar-btn" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="toolbar-btn"
            disabled={conditions.length === 0 || !conditionId}
            onClick={() => {
              const picked = conditions.find((c) => c.conditionId === conditionId);
              if (!picked) {
                return;
              }
              upsertAlertRule(
                layoutId,
                createIndicatorAlertRule({
                  symbol,
                  timeframe,
                  indicatorId: instance.definitionId,
                  instanceId: instance.instanceId,
                  conditionId: picked.conditionId,
                  label: label.trim() || picked.label,
                  oneShot,
                }),
              );
              onClose();
            }}
          >
            Create alert
          </button>
        </div>
      </div>
    </div>
  );
}
