"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

// ─── Types ───────────────────────────────────────────────────────────────────

interface Recipient {
  id: number;
  email: string;
  name: string;
  is_active: boolean;
  created_at: string;
  created_by: number;
}

interface AiConfig {
  ai_model?: string;
  ai_api_key?: string;
  ai_enabled?: string;
  basic_api_url?: string;
  smtp_host?: string;
  smtp_port?: string;
  smtp_username?: string;
  smtp_password?: string;
  smtp_from?: string;
  smtp_tls?: string;
  report_enabled?: string;
}

// ─── Page ────────────────────────────────────────────────────────────────────

export default function DailyReportPage() {
  const [tab, setTab] = useState<"recipients" | "ai-config">("recipients");
  const [loading, setLoading] = useState(true);
  const [msg, setMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Recipients state
  const [recipients, setRecipients] = useState<Recipient[]>([]);
  const [showAdd, setShowAdd] = useState(false);
  const [addEmail, setAddEmail] = useState("");
  const [addName, setAddName] = useState("");
  const [addLoading, setAddLoading] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [editName, setEditName] = useState("");
  const [editActive, setEditActive] = useState(true);

  // AI Config state
  const [config, setConfig] = useState<AiConfig>({});
  const [savingAi, setSavingAi] = useState(false);
  const [aiForm, setAiForm] = useState<AiConfig>({});
  const [testLoading, setTestLoading] = useState(false);

  // Generate state
  const [generating, setGenerating] = useState(false);
  const [generateResult, setGenerateResult] = useState<Record<string, unknown> | null>(null);

  useEffect(() => { loadRecipients(); loadConfig(); }, []);

  async function loadRecipients() {
    try {
      const res = await fetch("/api/admin/daily-report/recipients");
      const data = await res.json();
      setRecipients(data.recipients || []);
    } catch { setMsg({ type: "error", text: "加载收件人失败" }); }
    finally { setLoading(false); }
  }

  async function loadConfig() {
    try {
      const res = await fetch("/api/admin/daily-report/ai-config");
      const data = await res.json();
      setConfig(data.config || {});
      setAiForm(data.config || {});
    } catch { setMsg({ type: "error", text: "加载配置失败" }); }
  }

  // ── Recipients ───────────────────────────────────────────────────────────────

  async function handleAddRecipient() {
    if (!addEmail) return;
    setAddLoading(true);
    try {
      const res = await fetch("/api/admin/daily-report/recipients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: addEmail, name: addName }),
      });
      const data = await res.json();
      if (!res.ok) { setMsg({ type: "error", text: data.error || "添加失败" }); return; }
      setMsg({ type: "success", text: "收件人已添加" });
      setShowAdd(false); setAddEmail(""); setAddName("");
      loadRecipients();
    } catch { setMsg({ type: "error", text: "添加失败" }); }
    finally { setAddLoading(false); }
  }

  async function handleUpdateRecipient(id: number) {
    const res = await fetch(`/api/admin/daily-report/recipients/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: editName, is_active: editActive }),
    });
    const data = await res.json();
    if (!res.ok) { setMsg({ type: "error", text: data.error || "更新失败" }); return; }
    setMsg({ type: "success", text: "已更新" });
    setEditId(null);
    loadRecipients();
  }

  async function handleDeleteRecipient(id: number) {
    if (!confirm("确定删除该收件人？")) return;
    const res = await fetch(`/api/admin/daily-report/recipients/${id}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) { setMsg({ type: "error", text: data.error || "删除失败" }); return; }
    setMsg({ type: "success", text: "已删除" });
    loadRecipients();
  }

  // ── AI Config ──────────────────────────────────────────────────────────────

  async function handleSaveAiConfig() {
    setSavingAi(true);
    try {
      const res = await fetch("/api/admin/daily-report/ai-config", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(aiForm),
      });
      const data = await res.json();
      if (!res.ok) { setMsg({ type: "error", text: data.error || "保存失败" }); return; }
      setMsg({ type: "success", text: "配置已保存" });
      loadConfig();
    } catch { setMsg({ type: "error", text: "保存失败" }); }
    finally { setSavingAi(false); }
  }

  async function handleTriggerReport() {
    if (!confirm("立即触发每日报告生成？")) return;
    setGenerating(true);
    setGenerateResult(null);
    try {
      const res = await fetch("/api/admin/daily-report/generate", { method: "POST" });
      const data = await res.json();
      if (!res.ok) { setMsg({ type: "error", text: data.error || "生成失败" }); return; }
      setGenerateResult(data);
      setMsg({ type: "success", text: `报告已发送至 ${data.sent || 0} 个收件人` });
    } catch { setMsg({ type: "error", text: "触发失败" }); }
    finally { setGenerating(false); }
  }

  const isReportEnabled = aiForm.report_enabled === "true";

  return (
    <div className="admin-content">
      <div className="page-header">
        <div>
          <h1 className="page-title">每日平台报告</h1>
          <p className="page-subtitle">配置 AI 分析并发送给内部员工邮箱，每日零点自动运行</p>
        </div>
        <div style={{ display: "flex", gap: "8px" }}>
          <button
            className="btn btn-secondary"
            onClick={handleTriggerReport}
            disabled={generating || !isReportEnabled}
          >
            {generating ? "生成中..." : "🔄 立即触发"}
          </button>
        </div>
      </div>

      {msg && (
        <div className={`alert ${msg.type === "error" ? "alert-error" : "alert-success"}`} style={{ marginBottom: "16px" }}>
          {msg.text}
          <button onClick={() => setMsg(null)} style={{ float: "right", background: "none", border: "none", cursor: "pointer" }}>×</button>
        </div>
      )}

      {generateResult && (
        <div className="card" style={{ marginBottom: "16px", background: "#f0fdf4" }}>
          <h3 style={{ margin: "0 0 12px 0", fontSize: "14px" }}>📊 上次报告结果</h3>
          <div style={{ fontSize: "13px", color: "#166534", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "8px" }}>
            <div>📧 已发送: <strong>{`${(generateResult.sent as number) ?? 0}`}</strong></div>
            <div>👥 收件人: <strong>{`${(generateResult.recipients as number) ?? 0}`}</strong></div>
            <div>🤖 AI分析: <strong>{`${(generateResult.aiSummaryUsed as boolean) ? "已启用" : "未启用"}`}</strong></div>
            {!!generateResult.stats && (
              <>
                <div>👥 新增用户: <strong>{`${(generateResult.stats as Record<string, unknown>).newUsers ?? 0}`}</strong></div>
                <div>💬 新增消息: <strong>{`${(generateResult.stats as Record<string, unknown>).newMessages ?? 0}`}</strong></div>
                <div>🔧 新增提交: <strong>{`${(generateResult.stats as Record<string, unknown>).newCommits ?? 0}`}</strong></div>
              </>
            )}
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="toolbar" style={{ marginBottom: "0" }}>
        <button className={`btn btn-sm ${tab === "recipients" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("recipients")}>
          📧 收件人管理
        </button>
        <button className={`btn btn-sm ${tab === "ai-config" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("ai-config")}>
          🤖 AI & SMTP 设置
        </button>
      </div>

      <div className="card">
        {tab === "recipients" && (
          <>
            <div style={{ padding: "12px", borderBottom: "1px solid #e5e7eb", display: "flex", justifyContent: "flex-end" }}>
              <button className="btn btn-sm btn-primary" onClick={() => setShowAdd(true)}>+ 添加收件人</button>
            </div>

            {showAdd && (
              <div style={{ padding: "16px", background: "#f9fafb", borderBottom: "1px solid #e5e7eb" }}>
                <div style={{ display: "flex", gap: "8px", alignItems: "flex-end" }}>
                  <div className="form-group" style={{ flex: 1, margin: 0 }}>
                    <label className="form-label">邮箱</label>
                    <input className="form-input" type="email" value={addEmail} onChange={e => setAddEmail(e.target.value)} placeholder="employee@company.com" />
                  </div>
                  <div className="form-group" style={{ flex: 1, margin: 0 }}>
                    <label className="form-label">姓名（可选）</label>
                    <input className="form-input" value={addName} onChange={e => setAddName(e.target.value)} placeholder="张三" />
                  </div>
                  <button className="btn btn-primary btn-sm" disabled={addLoading || !addEmail} onClick={handleAddRecipient}>
                    {addLoading ? "添加中..." : "添加"}
                  </button>
                  <button className="btn btn-secondary btn-sm" onClick={() => { setShowAdd(false); setAddEmail(""); setAddName(""); }}>取消</button>
                </div>
              </div>
            )}

            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>邮箱</th><th>姓名</th><th>状态</th><th>添加时间</th><th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {recipients.map(r => (
                    <tr key={r.id}>
                      <td>{r.email}</td>
                      <td>{editId === r.id ? (
                        <input className="form-input" style={{ padding: "2px 8px", fontSize: "13px", width: "120px" }}
                          value={editName} onChange={e => setEditName(e.target.value)} />
                      ) : r.name || "—"}</td>
                      <td>{editId === r.id ? (
                        <label style={{ display: "flex", alignItems: "center", gap: "4px", fontSize: "13px" }}>
                          <input type="checkbox" checked={editActive} onChange={e => setEditActive(e.target.checked)} />
                          启用
                        </label>
                      ) : (
                        <span className={`badge ${r.is_active ? "badge-success" : "badge-neutral"}`}>
                          {r.is_active ? "启用" : "禁用"}
                        </span>
                      )}</td>
                      <td style={{ fontSize: "13px", color: "#737373" }}>{r.created_at ? format(new Date(r.created_at), "yyyy-MM-dd HH:mm") : "—"}</td>
                      <td>
                        {editId === r.id ? (
                          <>
                            <button className="btn btn-primary btn-sm" style={{ marginRight: "4px" }} onClick={() => handleUpdateRecipient(r.id)}>保存</button>
                            <button className="btn btn-secondary btn-sm" onClick={() => setEditId(null)}>取消</button>
                          </>
                        ) : (
                          <>
                            <button className="btn btn-secondary btn-sm" style={{ marginRight: "4px" }}
                              onClick={() => { setEditId(r.id); setEditName(r.name); setEditActive(r.is_active); }}>编辑</button>
                            <button className="btn btn-danger btn-sm" onClick={() => handleDeleteRecipient(r.id)}>删除</button>
                          </>
                        )}
                      </td>
                    </tr>
                  ))}
                  {recipients.length === 0 && (
                    <tr><td colSpan={5} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>
                      暂无收件人，点击上方「添加收件人」开始配置
                    </td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "ai-config" && (
          <div style={{ padding: "24px" }}>
            {/* Report enable */}
            <div className="form-group">
              <label style={{ display: "flex", alignItems: "center", gap: "8px", cursor: "pointer", fontWeight: 600 }}>
                <input type="checkbox" checked={aiForm.report_enabled === "true"}
                  onChange={e => setAiForm(f => ({ ...f, report_enabled: e.target.checked ? "true" : "false" }))} />
                启用每日报告（每日零点自动生成并发送）
              </label>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
              {/* AI Settings */}
              <div>
                <h3 style={{ fontSize: "14px", fontWeight: 600, margin: "16px 0 12px", color: "#374151" }}>🤖 AI 分析设置</h3>
                <div className="form-group">
                  <label className="form-label">启用 AI 分析</label>
                  <label style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <input type="checkbox" checked={aiForm.ai_enabled === "true"}
                      onChange={e => setAiForm(f => ({ ...f, ai_enabled: e.target.checked ? "true" : "false" }))} />
                    启用（不启用则只发送原始数据）
                  </label>
                </div>
                <div className="form-group">
                  <label className="form-label">AI 模型</label>
                  <input className="form-input" value={aiForm.ai_model || ""}
                    onChange={e => setAiForm(f => ({ ...f, ai_model: e.target.value }))}
                    placeholder="gpt-4o-mini" />
                  <span style={{ fontSize: "12px", color: "#737373" }}>OpenAI 模型，支持 gpt-4o, gpt-4o-mini 等</span>
                </div>
                <div className="form-group">
                  <label className="form-label">OpenAI API Key</label>
                  <input className="form-input" type="password" value={aiForm.ai_api_key || ""}
                    onChange={e => setAiForm(f => ({ ...f, ai_api_key: e.target.value }))}
                    placeholder="sk-..." />
                </div>
                <div className="form-group">
                  <label className="form-label">自定义 API 地址（可选）</label>
                  <input className="form-input" value={aiForm.basic_api_url || ""}
                    onChange={e => setAiForm(f => ({ ...f, basic_api_url: e.target.value }))}
                    placeholder="https://api.openai.com（留空使用默认地址）" />
                  <span style={{ fontSize: "12px", color: "#737373" }}>
                    支持 OpenAI 兼容接口，如 Cloudflare AI Gateway、OneAPI 等
                  </span>
                </div>
              </div>

              {/* SMTP Settings */}
              <div>
                <h3 style={{ fontSize: "14px", fontWeight: 600, margin: "16px 0 12px", color: "#374151" }}>📧 SMTP 设置</h3>
                <div className="form-group">
                  <label className="form-label">SMTP 主机</label>
                  <input className="form-input" value={aiForm.smtp_host || ""}
                    onChange={e => setAiForm(f => ({ ...f, smtp_host: e.target.value }))}
                    placeholder="smtp.example.com" />
                </div>
                <div className="form-group">
                  <label className="form-label">SMTP 端口</label>
                  <input className="form-input" type="number" value={aiForm.smtp_port || "587"}
                    onChange={e => setAiForm(f => ({ ...f, smtp_port: e.target.value }))}
                    placeholder="587" />
                </div>
                <div className="form-group">
                  <label className="form-label">用户名</label>
                  <input className="form-input" value={aiForm.smtp_username || ""}
                    onChange={e => setAiForm(f => ({ ...f, smtp_username: e.target.value }))}
                    placeholder="notifications@example.com" />
                </div>
                <div className="form-group">
                  <label className="form-label">密码 / API Key</label>
                  <input className="form-input" type="password" value={aiForm.smtp_password || ""}
                    onChange={e => setAiForm(f => ({ ...f, smtp_password: e.target.value }))}
                    placeholder="••••••••" />
                </div>
                <div className="form-group">
                  <label className="form-label">发件人地址</label>
                  <input className="form-input" type="email" value={aiForm.smtp_from || ""}
                    onChange={e => setAiForm(f => ({ ...f, smtp_from: e.target.value }))}
                    placeholder="no-reply@example.com" />
                </div>
                <div className="form-group">
                  <label style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                    <input type="checkbox" checked={aiForm.smtp_tls === "true"}
                      onChange={e => setAiForm(f => ({ ...f, smtp_tls: e.target.checked ? "true" : "false" }))} />
                    使用 TLS（推荐，端口 587 默认启用）
                  </label>
                </div>
              </div>
            </div>

            <div style={{ marginTop: "20px", paddingTop: "16px", borderTop: "1px solid #e5e7eb" }}>
              <button className="btn btn-primary" disabled={savingAi} onClick={handleSaveAiConfig}>
                {savingAi ? "保存中..." : "💾 保存配置"}
              </button>
              <span style={{ marginLeft: "12px", fontSize: "13px", color: "#737373" }}>
                配置保存在数据库中，不会泄露到前端
              </span>
            </div>
          </div>
        )}
      </div>

      {/* Cron 说明 */}
      <div className="card" style={{ marginTop: "16px" }}>
        <h3 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: 600 }}>⏰ 自动运行配置</h3>
        <p style={{ margin: "0 0 8px 0", fontSize: "13px", color: "#737373" }}>
          使用 <code>npm start</code> 启动服务时，定时调度自动启用（每日零点 UTC）。
          生产环境（多实例）推荐使用 K8s CronJob：
        </p>
        <pre style={{ background: "#1e1e1e", color: "#d4d4d4", padding: "16px", borderRadius: "8px", fontSize: "12px", overflow: "auto" }}>
{`# admin-daily-report-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: daily-report
  namespace: admin
spec:
  schedule: "0 0 * * *"  # 每日零点 (UTC)
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: curl
            image: curlimages/curl:latest
            command: ["curl", "-X", "POST",
              "-H", "x-cron-secret: $DAILY_REPORT_CRON_SECRET",
              "http://admin-admin.$NAMESPACE.svc.cluster.local:3000/api/admin/daily-report/generate"]
          restartPolicy: OnFailure`}
        </pre>
        <p style={{ margin: "8px 0 0 0", fontSize: "12px", color: "#9ca3af" }}>
          <strong>生产提示：</strong>多实例部署时，K8s CronJob 可确保只触发一次；单实例部署时使用内置调度器即可。
          可通过设置 <code>DAILY_REPORT_CRON_SECRET</code> 环境变量保护 CronJob 调用。
        </p>
      </div>
    </div>
  );
}
