import { useDomainflare } from "../context/DomainflareContext";
import type { DnsRecord } from "../types";
import { RECORD_TYPES } from "../constants";
import {
  dnsRecordTypeClass,
  proxiedBadgeClass,
  proxiedLabel,
  recordContentPreview,
  recordContentToneClass,
  ttlTagClass,
} from "../utils/dns";
import { DnsRecordDrawer } from "./DnsRecordDrawer";
import { useState } from "react";

/** 主区：解析记录表与分页 */
export function RecordsSection() {
  const {
    activeZone,
    activeZoneId,
    records,
    recordsStatus,
    fltType,
    setFltType,
    fltName,
    setFltName,
    fltContent,
    setFltContent,
    searchRecords,
    recordsPageInfo,
    goRecordsPrev,
    goRecordsNext,
    recordsPage,
    recordsTotalPages,
    toast,
    cf,
  } = useDomainflare();

  const [drawerOpen, setDrawerOpen] = useState(false);
  const [drawerMode, setDrawerMode] = useState<"create" | "edit">("create");
  const [editRecord, setEditRecord] = useState<DnsRecord | null>(null);

  function openCreate() {
    if (!activeZoneId) {
      toast("请先选择域名", true);
      return;
    }
    setDrawerMode("create");
    setEditRecord(null);
    setDrawerOpen(true);
  }

  function openEdit(r: DnsRecord) {
    setDrawerMode("edit");
    setEditRecord(r);
    setDrawerOpen(true);
  }

  async function onDelete(r: DnsRecord) {
    if (!activeZoneId) return;
    if (!confirm(`删除 ${r.type} ${r.name}？`)) return;
    try {
      await cf(`/zones/${activeZoneId}/dns_records/${r.id}`, { method: "DELETE" });
      toast("已删除");
      await searchRecords();
    } catch (e) {
      toast(e instanceof Error ? e.message : String(e), true);
    }
  }

  return (
    <>
      <section id="zone-banner" className={`banner${activeZone ? "" : " hidden"}`}>
        <div>
          <h2 id="zone-title">{activeZone?.name ?? "—"}</h2>
          <p className="muted small" id="zone-meta">
            {activeZone
              ? `Zone ID: ${activeZone.id} · ${activeZone.status} · ${activeZone.plan?.name || "plan"}`
              : ""}
          </p>
        </div>
        <div className="banner-actions">
          <button
            type="button"
            id="btn-zone-settings"
            className="btn ghost small"
            onClick={() => void dnssecAlert(cf, activeZoneId, toast)}
          >
            DNS 设置
          </button>
          <button
            type="button"
            id="btn-export"
            className="btn ghost small"
            onClick={() => void exportRecords(cf, activeZoneId, toast)}
          >
            导出记录
          </button>
        </div>
      </section>

      <section className="panel flat records-section">
        <div className="records-toolbar">
          <div className="toolbar-filters">
            <label className="field tight inline">
              <span className="sr-only">类型</span>
              <select
                id="flt-type"
                className="input-compact flt-select"
                value={fltType}
                onChange={(e) => setFltType(e.target.value)}
              >
                <option value="">全部类型</option>
                {RECORD_TYPES.map((t) => (
                  <option key={t} value={t}>
                    {t}
                  </option>
                ))}
              </select>
            </label>
            <label className="field tight inline flex-grow">
              <span className="sr-only">名称</span>
              <input
                id="flt-name"
                type="text"
                className="input-compact"
                placeholder="名称包含…"
                value={fltName}
                onChange={(e) => setFltName(e.target.value)}
              />
            </label>
            <label className="field tight inline flex-grow">
              <span className="sr-only">内容</span>
              <input
                id="flt-content"
                type="text"
                className="input-compact"
                placeholder="内容…"
                value={fltContent}
                onChange={(e) => setFltContent(e.target.value)}
              />
            </label>
            <button
              type="button"
              id="records-search"
              className="btn secondary small btn-compact"
              onClick={() => void searchRecords()}
            >
              查询
            </button>
          </div>
          <div className="toolbar-actions">
            <button
              type="button"
              id="record-new"
              className="btn primary small btn-compact"
              onClick={openCreate}
            >
              新建解析
            </button>
          </div>
        </div>
        <div id="records-status" className="records-meta muted small">
          {recordsStatus}
        </div>
        <div className="table-wrap">
          <table className="table table-record" id="records-table">
            <thead>
              <tr>
                <th className="col-type">类型</th>
                <th className="col-name">名称</th>
                <th className="col-content">内容</th>
                <th className="col-narrow">TTL</th>
                <th className="col-narrow">代理</th>
                <th className="col-actions">操作</th>
              </tr>
            </thead>
            <tbody id="records-body">
              {records.map((r) => (
                <tr key={r.id} className="record-row">
                  <td data-label="类型" className="td-type">
                    <span className={`pill ${dnsRecordTypeClass(r.type)}`}>{r.type}</span>
                  </td>
                  <td data-label="名称" className="cell-mono td-name td-name-rec">
                    {r.name}
                  </td>
                  <td data-label="内容" className="cell-mono td-content">
                    <span className={`record-content ${recordContentToneClass(r)}`}>
                      {recordContentPreview(r)}
                    </span>
                  </td>
                  <td data-label="TTL" className="td-ttl">
                    <span className={ttlTagClass(r)}>{r.ttl === 1 ? "自动" : String(r.ttl)}</span>
                  </td>
                  <td data-label="代理" className="td-proxy">
                    <span className={proxiedBadgeClass(r)}>{proxiedLabel(r)}</span>
                  </td>
                  <td data-label="操作" className="td-actions">
                    <div className="record-actions">
                      <button
                        type="button"
                        className="btn secondary tiny btn-action btn-action-edit"
                        onClick={() => openEdit(r)}
                      >
                        编辑
                      </button>
                      <button
                        type="button"
                        className="btn ghost tiny danger btn-action"
                        onClick={() => void onDelete(r)}
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="pager pager-tight">
          <button
            type="button"
            id="page-prev"
            className="btn ghost small"
            disabled={recordsPage <= 1}
            onClick={goRecordsPrev}
          >
            上一页
          </button>
          <span id="page-info" className="muted small">
            {recordsPageInfo}
          </span>
          <button
            type="button"
            id="page-next"
            className="btn ghost small"
            disabled={recordsPage >= recordsTotalPages}
            onClick={goRecordsNext}
          >
            下一页
          </button>
        </div>
      </section>

      <DnsRecordDrawer
        open={drawerOpen}
        mode={drawerMode}
        record={editRecord}
        zoneId={activeZoneId}
        onClose={() => setDrawerOpen(false)}
        onSaved={async () => {
          await searchRecords();
        }}
      />
    </>
  );
}

async function dnssecAlert(
  cf: (path: string, init?: RequestInit) => Promise<unknown>,
  zoneId: string | null,
  toast: (m: string, e?: boolean) => void,
) {
  if (!zoneId) return;
  try {
    const json = (await cf(`/zones/${zoneId}/dnssec`)) as { result?: unknown };
    const pretty = JSON.stringify(json.result ?? json, null, 2);
    alert(`DNSSEC（Cloudflare API /zones/:id/dnssec）：\n\n${pretty}`);
  } catch (e) {
    toast(e instanceof Error ? e.message : String(e), true);
  }
}

async function exportRecords(
  cf: (path: string, init?: RequestInit) => Promise<unknown>,
  zoneId: string | null,
  toast: (m: string, e?: boolean) => void,
) {
  if (!zoneId) return;
  try {
    const json = (await cf(`/zones/${zoneId}/dns_records?per_page=5000`)) as {
      result?: unknown;
    };
    const blob = new Blob([JSON.stringify(json.result, null, 2)], {
      type: "application/json",
    });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `dns-export-${zoneId}.json`;
    a.click();
    URL.revokeObjectURL(a.href);
    toast("已导出 JSON");
  } catch (e) {
    toast(e instanceof Error ? e.message : String(e), true);
  }
}
