"use client";

import { updateAlertRule } from "@/lib/alerts/manager";
import { findLayoutIdForAlertId } from "@/lib/alerts/storage";
import type { AlertRule } from "@/lib/alerts/types";
import { useEffect, useState } from "react";

type EditAlertModalProps = {
  open?: boolean;
  rule: AlertRule | null;
  onClose: () => void;
  onSaved?: () => void;
};

export function EditAlertModal({ open = true, rule, onClose, onSaved }: EditAlertModalProps) {
  const [label, setLabel] = useState("");
  const [oneShot, setOneShot] = useState(false);

  useEffect(() => {
    if (!rule) {
      return;
    }
    setLabel(rule.conditions[0]?.label ?? "");
    setOneShot(rule.oneShot ?? false);
  }, [rule]);

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

  const save = () => {
    const conditions = [...rule.conditions];
    conditions[0] = { ...conditions[0]!, label: label.trim() || undefined };
    const layoutId = findLayoutIdForAlertId(rule.id);
    if (!layoutId) {
      return;
    }
    updateAlertRule(layoutId, { ...rule, conditions, oneShot });
    onSaved?.();
    onClose();
  };

  return (
    <div className="alert-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="alert-modal"
        role="dialog"
        aria-labelledby="edit-alert-title"
        onClick={(e) => e.stopPropagation()}
      >
        <h2 id="edit-alert-title">Edit alert</h2>
        <p className="alert-modal-meta">
          {rule.symbol.replace("_", "/")} · {rule.timeframe}
        </p>
        <label>
          Name
          <input
            type="text"
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            className="toolbar-input"
          />
        </label>
        <label className="toolbar-check-row">
          <input
            type="checkbox"
            checked={oneShot}
            onChange={(e) => setOneShot(e.target.checked)}
          />
          One shot (disable after first trigger)
        </label>
        <div className="alert-modal-actions">
          <button type="button" className="toolbar-btn" onClick={onClose}>
            Cancel
          </button>
          <button type="button" className="toolbar-btn toolbar-btn-primary" onClick={save}>
            Save
          </button>
        </div>
      </div>
    </div>
  );
}
