"use client";

import { CreateAlertModal } from "@/components/alerts/CreateAlertModal";
import { EditAlertModal } from "@/components/alerts/EditAlertModal";
import { AlertSoundSettings } from "@/components/alerts/AlertSoundSettings";
import { NotificationPermissionButton } from "@/components/alerts/NotificationPermissionButton";
import {
  describeAlertCondition,
  describeAlertTarget,
} from "@/lib/alerts/condition-labels";
import { ALERTS_CHANGED_EVENT } from "@/lib/alerts/events";
import { deleteAlertRule, toggleAlertEnabled } from "@/lib/alerts/manager";
import { loadAlertRules } from "@/lib/alerts/storage";
import type { AlertRule } from "@/lib/alerts/types";
import type { ChartLayoutId } from "@/lib/chart/layout-profile";
import type { CanonicalSymbol } from "@/lib/market/instruments";
import type { SupportedTimeframe } from "@/lib/market/timeframes";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";

type AlertDrawerProps = {
  open: boolean;
  onClose: () => void;
  layoutId: ChartLayoutId;
  defaultSymbol: CanonicalSymbol;
  defaultTimeframe: SupportedTimeframe;
};

export function AlertDrawer({
  open,
  onClose,
  layoutId,
  defaultSymbol,
  defaultTimeframe,
}: AlertDrawerProps) {
  const [rules, setRules] = useState<AlertRule[]>([]);
  const [priceModalOpen, setPriceModalOpen] = useState(false);
  const [editRule, setEditRule] = useState<AlertRule | null>(null);

  const refresh = useCallback(() => {
    setRules(loadAlertRules(layoutId));
  }, [layoutId]);

  useEffect(() => {
    refresh();
    const onChange = () => refresh();
    window.addEventListener(ALERTS_CHANGED_EVENT, onChange);
    return () => window.removeEventListener(ALERTS_CHANGED_EVENT, onChange);
  }, [refresh]);

  useEffect(() => {
    if (!open) {
      return;
    }
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) {
    return null;
  }

  return (
    <>
      <div className="alert-drawer-backdrop" onClick={onClose} aria-hidden />
      <aside className="alert-drawer" aria-label="Alerts">
        <header className="alert-drawer-head">
          <h2>Alerts</h2>
          <button type="button" className="toolbar-btn toolbar-btn-sm" onClick={onClose}>
            Close
          </button>
        </header>
        <div className="alert-drawer-toolbar">
          <NotificationPermissionButton />
          <button
            type="button"
            className="toolbar-btn toolbar-btn-sm"
            onClick={() => setPriceModalOpen(true)}
          >
            New price alert
          </button>
          <Link className="toolbar-btn toolbar-btn-sm toolbar-link" href="/alerts">
            Full page
          </Link>
        </div>
        <AlertSoundSettings />
        {rules.length === 0 ? (
          <p className="chart-indicator-empty">
            No alerts yet. Select a drawing on the chart or add a price alert.
          </p>
        ) : (
          <ul className="alert-list alert-drawer-list">
            {rules.map((rule) => (
              <li key={rule.id} className="alert-list-item">
                <div className="alert-list-main">
                  <strong>{rule.conditions[0]?.label ?? rule.id.slice(0, 8)}</strong>
                  <span>
                    {rule.symbol.replace("_", "/")} · {rule.timeframe}
                    {!rule.enabled ? " · disabled" : ""}
                  </span>
                  <span>{describeAlertCondition(rule)}</span>
                  <span className="chart-meta">Target: {describeAlertTarget(rule)}</span>
                </div>
                <div className="alert-list-actions">
                  <label className="toolbar-check-row">
                    <input
                      type="checkbox"
                      checked={rule.enabled}
                      onChange={(e) => {
                        toggleAlertEnabled(rule.id, e.target.checked);
                        refresh();
                      }}
                    />
                    <span>On</span>
                  </label>
                  <button
                    type="button"
                    className="toolbar-btn toolbar-btn-sm"
                    onClick={() => setEditRule(rule)}
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    className="toolbar-btn toolbar-btn-sm"
                    onClick={() => {
                      if (window.confirm("Delete this alert?")) {
                        deleteAlertRule(layoutId, rule.id);
                        refresh();
                      }
                    }}
                  >
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </aside>
      <CreateAlertModal
        open={priceModalOpen}
        onClose={() => setPriceModalOpen(false)}
        layoutId={layoutId}
        symbol={defaultSymbol}
        timeframe={defaultTimeframe}
      />
      <EditAlertModal
        open={editRule !== null}
        rule={editRule}
        onClose={() => setEditRule(null)}
        onSaved={refresh}
      />
    </>
  );
}
