"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { readBackendUnavailableMessage, useResolvedApiBase } from "../lib/api-base";
import { DetailKeyGrid, DetailSection } from "./admin-detail";
import { EmptyPanel, ErrorBanner, NoticeBanner, PageStatus } from "./admin-feedback";
import { AdminFrame } from "./admin-frame";
import { ResourceToolbar } from "./admin-resource";
import styles from "./platform-shell.module.css";

type AlertSeverity = "info" | "warning" | "major" | "critical";
type AlertStatus = "open" | "acknowledged" | "resolved";

type MonitorAlert = {
  id: string;
  targetId: string;
  runId: string | null;
  serviceKey: string;
  title: string;
  category: string;
  severity: AlertSeverity;
  status: AlertStatus;
  sourceType: "run-status" | "log-analysis";
  summary: string;
  occurrenceCount: number;
  firstDetectedAt: string;
  lastDetectedAt: string;
  notifiedAt: string | null;
  notificationStatus: string | null;
  notificationMessage: string | null;
  target?: {
    id: string;
    name: string;
    type: string;
    endpoint: string;
  };
};

type MonitorAlertDetail = {
  alert: MonitorAlert & {
    target: {
      id: string;
      name: string;
      type: string;
      endpoint: string;
    };
    run: {
      id: string;
      traceId: string;
      status: string;
      errorTag: string | null;
      startedAt: string;
      endedAt: string | null;
    } | null;
  };
  detail: {
    details: Record<string, unknown>;
  };
};

function formatTime(value?: string | null) {
  return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "暂无";
}

function severityLabel(value: AlertSeverity) {
  return ({ info: "信息", warning: "预警", major: "严重", critical: "紧急" } as const)[value];
}

function alertStatusLabel(value: AlertStatus) {
  return ({ open: "处理中", acknowledged: "已确认", resolved: "已关闭" } as const)[value];
}

function readErrorMessage(error: unknown, apiBase?: string) {
  if (error instanceof TypeError) return readBackendUnavailableMessage(apiBase);
  if (error instanceof Error) return error.message;
  if (error && typeof error === "object" && "message" in error) {
    const message = (error as { message?: string | string[] }).message;
    return Array.isArray(message) ? message.join("；") : (message ?? "请求失败，请稍后重试。");
  }
  return "请求失败，请稍后重试。";
}

export function MonitoringAlertsConsole() {
  const apiBase = useResolvedApiBase();
  const [alerts, setAlerts] = useState<MonitorAlert[]>([]);
  const [selectedAlertId, setSelectedAlertId] = useState<string | null>(null);
  const [selectedAlertDetail, setSelectedAlertDetail] = useState<MonitorAlertDetail | null>(null);
  const [statusFilter, setStatusFilter] = useState<"" | AlertStatus>("open");
  const [severityFilter, setSeverityFilter] = useState<"" | AlertSeverity>("");
  const [keyword, setKeyword] = useState("");
  const [refreshing, setRefreshing] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [infoMessage, setInfoMessage] = useState("");
  const [updatingStatus, setUpdatingStatus] = useState<string | null>(null);

  async function request<T>(path: string, init?: RequestInit) {
    try {
      const response = await fetch(`${apiBase}${path}`, {
        ...init,
        headers: {
          "Content-Type": "application/json",
          ...(init?.headers ?? {}),
        },
        cache: "no-store",
      });
      if (!response.ok) {
        let payload: unknown = null;
        try { payload = await response.json(); } catch { payload = null; }
        throw new Error(readErrorMessage(payload, apiBase));
      }
      return await response.json() as T;
    } catch (error) {
      throw new Error(readErrorMessage(error, apiBase));
    }
  }

  async function loadAlertDetail(alertId: string) {
    const detail = await request<MonitorAlertDetail>(`/api/monitoring/alerts/${alertId}`);
    setSelectedAlertId(alertId);
    setSelectedAlertDetail(detail);
  }

  async function refreshData(preferredAlertId?: string) {
    setRefreshing(true);
    setErrorMessage("");
    try {
      const params = new URLSearchParams();
      if (statusFilter) params.set("status", statusFilter);
      if (severityFilter) params.set("severity", severityFilter);
      params.set("limit", "200");
      const payload = await request<{ list: MonitorAlert[] }>(`/api/monitoring/alerts?${params.toString()}`);
      setAlerts(payload.list);
      const nextAlertId = preferredAlertId ?? (selectedAlertId && payload.list.some((item) => item.id === selectedAlertId) ? selectedAlertId : payload.list[0]?.id ?? null);
      if (nextAlertId) await loadAlertDetail(nextAlertId);
      else {
        setSelectedAlertId(null);
        setSelectedAlertDetail(null);
      }
    } catch (error) {
      setErrorMessage(readErrorMessage(error, apiBase));
    } finally {
      setRefreshing(false);
    }
  }

  useEffect(() => {
    void refreshData();
  }, [apiBase, statusFilter, severityFilter]);

  useEffect(() => {
    if (!infoMessage) return;
    const timer = window.setTimeout(() => setInfoMessage(""), 4000);
    return () => window.clearTimeout(timer);
  }, [infoMessage]);

  const visibleAlerts = useMemo(() => {
    const q = keyword.trim();
    return alerts.filter((item) => !q || item.title.includes(q) || item.serviceKey.includes(q) || item.category.includes(q));
  }, [alerts, keyword]);

  const stats = useMemo(() => ({
    total: alerts.length,
    open: alerts.filter((item) => item.status === "open").length,
    critical: alerts.filter((item) => item.severity === "critical").length,
    notified: alerts.filter((item) => item.notificationStatus === "sent").length,
  }), [alerts]);

  async function handleUpdateStatus(alertId: string, status: AlertStatus) {
    setUpdatingStatus(`${alertId}:${status}`);
    try {
      await request(`/api/monitoring/alerts/${alertId}/status`, {
        method: "PATCH",
        body: JSON.stringify({ status }),
      });
      setInfoMessage(status === "acknowledged" ? "告警已确认。" : status === "resolved" ? "告警已关闭。" : "告警已重新打开。");
      await refreshData(alertId);
    } catch (error) {
      setErrorMessage(readErrorMessage(error, apiBase));
    } finally {
      setUpdatingStatus(null);
    }
  }

  return (
    <AdminFrame
      section="alerts"
      title="告警事件"
      description="监测失败、访问异常和日志分析命中的问题会汇总到这里，并同步通知状态。"
      actions={<PageStatus busy={refreshing} busyLabel="同步中" idleLabel="已就绪" />}
    >
      <NoticeBanner message={infoMessage} />
      <ErrorBanner message={errorMessage} />
      <section className={styles.mainContent}>
        <section className={styles.panel}>
          <div className={styles.pageHeader}>
            <div>
              <p className={styles.pageKicker}>事件总览</p>
              <h2>当前告警池</h2>
            </div>
            <div className={styles.buttonRow}>
              <button className={styles.secondaryButton} onClick={() => void refreshData()} type="button">刷新数据</button>
            </div>
          </div>
          <div className={styles.statsGrid}>
            <article className={styles.statCard}><span>告警总数</span><strong>{stats.total}</strong></article>
            <article className={styles.statCard} data-tone="danger"><span>处理中</span><strong>{stats.open}</strong></article>
            <article className={styles.statCard} data-tone="danger"><span>紧急级别</span><strong>{stats.critical}</strong></article>
            <article className={styles.statCard} data-tone="success"><span>已通知</span><strong>{stats.notified}</strong></article>
          </div>
        </section>

        <section className={styles.runWorkspace}>
          <section className={styles.runListPanel}>
            <ResourceToolbar title="告警列表" description="按状态和级别收敛问题，再看单条事件详情。">
              <label className={styles.inlineField}>
                <span>关键词</span>
                <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="按标题、service_key、分类筛选" />
              </label>
              <label className={styles.inlineField}>
                <span>状态</span>
                <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as "" | AlertStatus)}>
                  <option value="">全部状态</option>
                  <option value="open">处理中</option>
                  <option value="acknowledged">已确认</option>
                  <option value="resolved">已关闭</option>
                </select>
              </label>
              <label className={styles.inlineField}>
                <span>级别</span>
                <select value={severityFilter} onChange={(event) => setSeverityFilter(event.target.value as "" | AlertSeverity)}>
                  <option value="">全部级别</option>
                  <option value="critical">紧急</option>
                  <option value="major">严重</option>
                  <option value="warning">预警</option>
                  <option value="info">信息</option>
                </select>
              </label>
            </ResourceToolbar>

            <div className={styles.runList}>
              {visibleAlerts.length ? visibleAlerts.map((alert) => (
                <article className={styles.runRow} data-active={selectedAlertId === alert.id} key={alert.id}>
                  <button className={styles.runRowButton} onClick={() => void loadAlertDetail(alert.id)} type="button">
                    <div className={styles.runRowMain}>
                      <div className={styles.runRowHeader}>
                        <strong>{alert.title}</strong>
                        <span className={styles.badge} data-status={alert.severity === "critical" || alert.severity === "major" ? "failed" : alert.severity === "warning" ? "partial" : "success"}>{severityLabel(alert.severity)}</span>
                      </div>
                      <span className={styles.runMetaLine}>
                        <span>{alertStatusLabel(alert.status)}</span>
                        <span>{alert.serviceKey}</span>
                        <span>{formatTime(alert.lastDetectedAt)}</span>
                      </span>
                      <span>{alert.summary}</span>
                    </div>
                    <div className={styles.runRowSide}>
                      <span>{alert.category}</span>
                      <span>{alert.occurrenceCount} 次</span>
                    </div>
                  </button>
                </article>
              )) : <EmptyPanel message="当前筛选条件下没有告警事件。" />}
            </div>
          </section>

          <aside className={styles.runDetailPanel}>
            {selectedAlertDetail ? (
              <div className={styles.detailStack}>
                <div className={styles.detailHeader}>
                  <div>
                    <p className={styles.pageKicker}>告警详情</p>
                    <h3>{selectedAlertDetail.alert.title}</h3>
                  </div>
                  <span className={styles.badge} data-status={selectedAlertDetail.alert.severity === "critical" || selectedAlertDetail.alert.severity === "major" ? "failed" : selectedAlertDetail.alert.severity === "warning" ? "partial" : "success"}>
                    {severityLabel(selectedAlertDetail.alert.severity)}
                  </span>
                </div>

                <DetailKeyGrid
                  items={[
                    { label: "状态", value: alertStatusLabel(selectedAlertDetail.alert.status) },
                    { label: "service_key", value: selectedAlertDetail.alert.serviceKey },
                    { label: "分类", value: selectedAlertDetail.alert.category },
                    { label: "来源", value: selectedAlertDetail.alert.sourceType },
                    { label: "首次发现", value: formatTime(selectedAlertDetail.alert.firstDetectedAt) },
                    { label: "最近发现", value: formatTime(selectedAlertDetail.alert.lastDetectedAt) },
                    { label: "通知结果", value: selectedAlertDetail.alert.notificationStatus ?? "未通知" },
                    { label: "触发次数", value: String(selectedAlertDetail.alert.occurrenceCount) },
                  ]}
                />

                <DetailSection title="摘要区" description="先看当前事件结论与通知反馈。">
                  <div className={styles.metaList}>
                    <span>摘要：{selectedAlertDetail.alert.summary}</span>
                    <span>通知说明：{selectedAlertDetail.alert.notificationMessage ?? "暂无"}</span>
                  </div>
                </DetailSection>

                <DetailSection title="关联对象" description="把告警与监测目标、运行记录串起来。">
                  <div className={styles.metaList}>
                    <span>目标：{selectedAlertDetail.alert.target.name}</span>
                    <span>地址：{selectedAlertDetail.alert.target.endpoint}</span>
                    <span>run_id：{selectedAlertDetail.alert.runId ?? "暂无"}</span>
                    <span>trace_id：{selectedAlertDetail.alert.run?.traceId ?? "暂无"}</span>
                  </div>
                  <div className={styles.buttonRow}>
                    <Link className={styles.linkButton} href={`/monitors?targetId=${selectedAlertDetail.alert.target.id}`}>
                      查看目标
                    </Link>
                    {selectedAlertDetail.alert.runId ? (
                      <Link
                        className={styles.secondaryButton}
                        href={`/monitors?targetId=${selectedAlertDetail.alert.target.id}&runId=${selectedAlertDetail.alert.runId}`}
                      >
                        查看监测记录
                      </Link>
                    ) : null}
                    <Link className={styles.secondaryButton} href={`/monitors/${selectedAlertDetail.alert.target.id}/edit`}>
                      编辑目标
                    </Link>
                  </div>
                </DetailSection>

                <DetailSection title="原始详情" description="这里保留触发告警时的结构化内容。">
                  <pre className={styles.codeBlock}>{JSON.stringify(selectedAlertDetail.detail.details, null, 2)}</pre>
                </DetailSection>

                <DetailSection title="操作区" description="支持确认、关闭和重新打开告警。">
                  <div className={styles.buttonRow}>
                    <button className={styles.secondaryButton} disabled={updatingStatus === `${selectedAlertDetail.alert.id}:acknowledged`} onClick={() => void handleUpdateStatus(selectedAlertDetail.alert.id, "acknowledged")} type="button">
                      {updatingStatus === `${selectedAlertDetail.alert.id}:acknowledged` ? "确认中..." : "标记已确认"}
                    </button>
                    <button className={styles.secondaryButton} disabled={updatingStatus === `${selectedAlertDetail.alert.id}:resolved`} onClick={() => void handleUpdateStatus(selectedAlertDetail.alert.id, "resolved")} type="button">
                      {updatingStatus === `${selectedAlertDetail.alert.id}:resolved` ? "关闭中..." : "关闭告警"}
                    </button>
                    <button className={styles.secondaryButton} disabled={updatingStatus === `${selectedAlertDetail.alert.id}:open`} onClick={() => void handleUpdateStatus(selectedAlertDetail.alert.id, "open")} type="button">
                      {updatingStatus === `${selectedAlertDetail.alert.id}:open` ? "打开中..." : "重新打开"}
                    </button>
                  </div>
                </DetailSection>
              </div>
            ) : <EmptyPanel message="从左侧选择一条告警事件后，这里会展示详情和通知状态。" />}
          </aside>
        </section>
      </section>
    </AdminFrame>
  );
}
