"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 { deleteAlertRuleById, toggleAlertEnabled } from "@/lib/alerts/manager";
import { findLayoutIdForAlertId, loadAllAlertRules } from "@/lib/alerts/storage";
import { CHART_LAYOUTS } from "@/lib/chart/layout-profile";
import type { AlertRule } from "@/lib/alerts/types";
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";

const DEFAULT_SYMBOL = "EUR_USD" as CanonicalSymbol;
const DEFAULT_TF = "H1" as SupportedTimeframe;

export function AlertsPageClient() {
  const [rules, setRules] = useState<AlertRule[]>([]);
  const [priceModalOpen, setPriceModalOpen] = useState(false);
  const [editRule, setEditRule] = useState<AlertRule | null>(null);

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

  const layoutLabel = (alertId: string) => {
    const id = findLayoutIdForAlertId(alertId);
    return CHART_LAYOUTS.find((l) => l.id === id)?.label ?? id ?? "Layout";
  };

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

  return (
    <main>
      <header className="app-subheader">
        <Link href="/">← Chart</Link>
        <h1>Alerts</h1>
      </header>
      <section className="panel">
        <div className="alert-page-toolbar">
          <NotificationPermissionButton />
          <AlertSoundSettings />
          <button
            type="button"
            className="toolbar-btn"
            onClick={() => setPriceModalOpen(true)}
          >
            New price alert
          </button>
        </div>
        {rules.length === 0 ? (
          <p className="status">No alerts yet. Select a drawing on the chart or add a price alert.</p>
        ) : (
          <ul className="alert-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>
                    {layoutLabel(rule.id)} · {rule.symbol.replace("_", "/")} · {rule.timeframe}
                  </span>
                  <span>{describeAlertCondition(rule)}</span>
                  <span className="chart-meta">Target: {describeAlertTarget(rule)}</span>
                  <span className="chart-meta">
                    Created {new Date(rule.createdAt).toLocaleString()}
                    {rule.lastTriggeredAt
                      ? ` · Last triggered ${new Date(rule.lastTriggeredAt).toLocaleString()}`
                      : ""}
                  </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();
                      }}
                    />
                    Enabled
                  </label>
                  <button
                    type="button"
                    className="toolbar-btn"
                    onClick={() => setEditRule(rule)}
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    className="toolbar-btn"
                    onClick={() => {
                      deleteAlertRuleById(rule.id);
                      refresh();
                    }}
                  >
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
      <CreateAlertModal
        open={priceModalOpen}
        onClose={() => setPriceModalOpen(false)}
        layoutId="layout-a"
        symbol={DEFAULT_SYMBOL}
        timeframe={DEFAULT_TF}
      />
      <EditAlertModal rule={editRule} onClose={() => setEditRule(null)} />
    </main>
  );
}
