"use client";

import {
  createDrawingAlertRule,
  createPriceAlertRule,
  upsertAlertRule,
} from "@/lib/alerts/manager";
import type { ChartDrawing } from "@/lib/chart/drawings/types";
import type { ChartLayoutId } from "@/lib/chart/layout-profile";
import type { CanonicalSymbol } from "@/lib/market/instruments";
import type { SupportedTimeframe } from "@/lib/market/timeframes";
import { useEffect, useMemo, useState } from "react";

type CreateAlertModalProps = {
  open: boolean;
  onClose: () => void;
  layoutId: ChartLayoutId;
  symbol: CanonicalSymbol;
  timeframe: SupportedTimeframe;
  drawing?: ChartDrawing | null;
};

type DrawingConditionOption = { value: string; label: string };

function drawingConditionOptions(drawing: ChartDrawing): DrawingConditionOption[] {
  switch (drawing.type) {
    case "horizontal":
    case "horizontal_ray":
      return [
        { value: "PRICE_CROSSES_ABOVE", label: "Cross above" },
        { value: "PRICE_CROSSES_BELOW", label: "Cross below" },
        { value: "PRICE_CROSSES_HORIZONTAL", label: "Cross either direction" },
        { value: "PRICE_TOUCHES", label: "Touch / reaches" },
      ];
    case "trend":
    case "ray":
    case "arrow":
      return [
        { value: "PRICE_CROSSES_TRENDLINE", label: "Cross line" },
        { value: "PRICE_TOUCHES", label: "Touch / reaches" },
      ];
    case "rectangle":
      return [
        { value: "PRICE_ENTERS_RECTANGLE", label: "Price enters zone" },
        { value: "PRICE_EXITS_RECTANGLE", label: "Price exits zone" },
      ];
    default:
      return [];
  }
}

export function CreateAlertModal({
  open,
  onClose,
  layoutId,
  symbol,
  timeframe,
  drawing,
}: CreateAlertModalProps) {
  const isPriceOnly = !drawing;
  const options = useMemo(
    () => (drawing ? drawingConditionOptions(drawing) : []),
    [drawing],
  );
  const [label, setLabel] = useState("");
  const [drawingCondition, setDrawingCondition] = useState(options[0]?.value ?? "");
  const [price, setPrice] = useState(1.1);
  const [priceCondition, setPriceCondition] = useState<
    "CROSS_ABOVE" | "CROSS_BELOW" | "CROSSES" | "REACHES"
  >("CROSS_ABOVE");
  const [oneShot, setOneShot] = useState(false);

  useEffect(() => {
    if (!open) {
      return;
    }
    setDrawingCondition(options[0]?.value ?? "");
  }, [open, drawing?.id, options]);

  if (!open) {
    return null;
  }

  const save = () => {
    const name = label.trim() || undefined;
    const condition = drawingCondition || options[0]?.value;
    if (drawing && condition) {
      upsertAlertRule(
        layoutId,
        createDrawingAlertRule({
          symbol,
          timeframe,
          drawingId: drawing.id,
          drawingAlertKey: drawing.alertKey,
          condition,
          label: name,
          oneShot,
        }),
      );
    } else {
      upsertAlertRule(
        layoutId,
        createPriceAlertRule({
          symbol,
          timeframe,
          price,
          condition: priceCondition,
          label: name,
          oneShot,
        }),
      );
    }
    onClose();
  };

  const unsupported = drawing && options.length === 0;

  return (
    <div className="alert-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="alert-modal"
        role="dialog"
        aria-labelledby="create-alert-title"
        onClick={(e) => e.stopPropagation()}
      >
        <h2 id="create-alert-title">Create alert</h2>
        <p className="alert-modal-meta">
          {symbol.replace("_", "/")} · {timeframe}
        </p>
        {unsupported ? (
          <p className="indicator-error">This drawing type does not support alerts yet.</p>
        ) : null}
        <label className="toolbar-field">
          <span className="toolbar-label">Name (optional)</span>
          <input
            className="toolbar-number"
            style={{ width: "100%" }}
            value={label}
            onChange={(e) => setLabel(e.target.value)}
          />
        </label>
        {isPriceOnly ? (
          <>
            <label className="toolbar-field">
              <span className="toolbar-label">Price level</span>
              <input
                type="number"
                step="any"
                className="toolbar-number"
                style={{ width: "100%" }}
                value={price}
                onChange={(e) => setPrice(Number(e.target.value))}
              />
            </label>
            <label className="toolbar-field">
              <span className="toolbar-label">Condition</span>
              <select
                value={priceCondition}
                onChange={(e) =>
                  setPriceCondition(e.target.value as typeof priceCondition)
                }
              >
                <option value="CROSS_ABOVE">Cross above</option>
                <option value="CROSS_BELOW">Cross below</option>
                <option value="CROSSES">Crosses (either)</option>
                <option value="REACHES">Reaches / touch</option>
              </select>
            </label>
          </>
        ) : (
          <label className="toolbar-field">
            <span className="toolbar-label">Condition</span>
            <select
              value={drawingCondition}
              onChange={(e) => setDrawingCondition(e.target.value)}
            >
              {options.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </label>
        )}
        <label className="toolbar-field toolbar-inline">
          <span className="toolbar-check-row">
            <input
              type="checkbox"
              checked={oneShot}
              onChange={(e) => setOneShot(e.target.checked)}
            />
            <span className="toolbar-label">One shot (disable after first trigger)</span>
          </span>
        </label>
        <div className="alert-modal-actions">
          <button type="button" className="toolbar-btn" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="toolbar-btn"
            disabled={Boolean(unsupported)}
            onClick={save}
          >
            Save alert
          </button>
        </div>
      </div>
    </div>
  );
}
