"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { format } from "date-fns";

interface Workspace {
  id: string; slug: string; name: string; plan: string;
  description: string | null; billing_email: string | null;
  balance: string | null; currency: string | null;
  monthly_quota: string | null; total_spent: string | null;
  created_at: string;
}

interface Member {
  id?: number;
  uid: string; username: string; display_name: string | null;
  avatar_url: string | null; role: string; joined_at: string;
  status?: string;
}

interface Project {
  id: string; name: string;
  is_public: boolean; member_count: number; created_at: string;
}

interface BillingEntry {
  reason: string; amount: string; description: string | null; created_at: string;
}

const ROLE_LABELS: Record<string, string> = {
  owner: "所有者", admin: "管理员", member: "成员", viewer: "查看者",
};
const PLAN_LABELS: Record<string, string> = {
  free: "免费", starter: "入门", pro: "专业", enterprise: "企业",
};

type Tab = "members" | "projects" | "billing" | "alerts";

interface AlertConfig {
  id: number;
  alert_type: string;
  threshold: string;
  email_enabled: boolean;
  enabled: boolean;
}

const ALERT_TYPE_LABELS: Record<string, { label: string; unit: string; placeholder: string }> = {
  low_balance: { label: "余额不足告警", unit: "USD", placeholder: "10.00" },
  monthly_quota: { label: "月度配额告警", unit: "%", placeholder: "80" },
  usage_surge: { label: "使用量激增", unit: "%", placeholder: "200" },
};

export default function WorkspaceDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [workspace, setWorkspace] = useState<Workspace | null>(null);
  const [members, setMembers] = useState<Member[]>([]);
  const [projects, setProjects] = useState<Project[]>([]);
  const [billingHistory, setBillingHistory] = useState<BillingEntry[]>([]);
  const [tab, setTab] = useState<Tab>("members");
  const [alertConfigs, setAlertConfigs] = useState<AlertConfig[]>([]);
  const [alertSaving, setAlertSaving] = useState(false);
  const [alertCheckMsg, setAlertCheckMsg] = useState<string | null>(null);
  const [alertChecking, setAlertChecking] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showCredit, setShowCredit] = useState(false);
  const [creditAmount, setCreditAmount] = useState("");
  const [creditDesc, setCreditDesc] = useState("");
  const [creditLoading, setCreditLoading] = useState(false);
  const [creditError, setCreditError] = useState("");

  // Member management
  const [showAddMember, setShowAddMember] = useState(false);
  const [addUserId, setAddUserId] = useState("");
  const [addUserDisplay, setAddUserDisplay] = useState(""); // shown in the input field
  const [addRole, setAddRole] = useState("member");
  const [addMemberLoading, setAddMemberLoading] = useState(false);
  const [addMemberError, setAddMemberError] = useState("");
  const [searchUsers, setSearchUsers] = useState<{ uid: string; username: string; display_name: string | null }[]>([]);
  const [searchLoading, setSearchLoading] = useState(false);

  function reload() {
    if (!id) return;
    setLoading(true);
    Promise.all([
      fetch(`/api/platform/workspaces/${id}`).then((r) => r.json()),
      fetch(`/api/platform/workspaces/${id}/alert-config`).then((r) => r.json()),
    ]).then(([wsData, alertData]) => {
      if (wsData.error) { setError(wsData.error); return; }
      setWorkspace(wsData.workspace);
      setMembers(wsData.members || []);
      setProjects(wsData.projects || []);
      setBillingHistory(wsData.billingHistory || []);
      setAlertConfigs(alertData.configs || []);
    }).catch((e) => setError(String(e))).finally(() => setLoading(false));
  }

  useEffect(() => {
    if (!id) return;
    reload();
  }, [id]);

  async function handleSaveAlerts() {
    setAlertSaving(true);
    try {
      const res = await fetch(`/api/platform/workspaces/${id}/alert-config`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ configs: alertConfigs }),
      });
      const data = await res.json();
      if (!res.ok) { window.alert(data.error || "保存失败"); return; }
      window.alert("告警配置已保存");
    } catch { window.alert("保存失败"); }
    finally { setAlertSaving(false); }
  }

  function updateAlert(type: string, field: keyof AlertConfig, value: string | boolean) {
    setAlertConfigs((prev) => {
      const existing = prev.find((c) => c.alert_type === type);
      if (existing) {
        return prev.map((c) => c.alert_type === type ? { ...c, [field]: value } : c);
      } else {
        return [...prev, {
          id: 0,
          alert_type: type,
          threshold: "0",
          email_enabled: true,
          enabled: true,
          [field]: value,
        } as AlertConfig];
      }
    });
  }

  function getAlert(type: string): AlertConfig | undefined {
    return alertConfigs.find((c) => c.alert_type === type);
  }

  async function handleAddCredit() {
    const amount = parseFloat(creditAmount);
    if (!amount || amount <= 0) { setCreditError("请输入有效金额"); return; }
    setCreditLoading(true);
    setCreditError("");
    try {
      const res = await fetch(`/api/platform/workspaces/${id}/add-credit`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ amount, description: creditDesc }),
      });
      const data = await res.json();
      if (!res.ok) { setCreditError(data.error || "充值失败"); return; }
      setShowCredit(false);
      setCreditAmount("");
      setCreditDesc("");
      reload();
    } catch {
      setCreditError("充值失败，请重试");
    } finally {
      setCreditLoading(false);
    }
  }

  // Search users for adding member
  async function handleUserSearch(q: string) {
    setAddUserId(q); // keep the raw typed text for form submission
    if (q.length < 2) { setSearchUsers([]); return; }
    setSearchLoading(true);
    try {
      const res = await fetch(`/api/platform/users?search=${encodeURIComponent(q)}&pageSize=10`);
      const data = await res.json();
      if (!res.ok) {
        // Show error from API
        setSearchUsers([]);
        setAddMemberError(data.error || "搜索失败，请重试");
        return;
      }
      const existingIds = new Set(members.map(m => m.uid));
      setSearchUsers((data.users || []).filter((u: { uid: string }) => !existingIds.has(u.uid)));
      setAddMemberError(""); // clear previous errors
    } catch {
      setSearchUsers([]);
      setAddMemberError("搜索失败，请检查网络连接");
    }
    finally { setSearchLoading(false); }
  }

  async function handleAddMember() {
    if (!addUserId) { setAddMemberError("请选择用户"); return; }
    setAddMemberLoading(true);
    setAddMemberError("");
    try {
      const res = await fetch(`/api/platform/workspaces/${id}/members`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: addUserId, role: addRole }),
      });
      const data = await res.json();
      if (!res.ok) { setAddMemberError(data.error || "添加失败"); return; }
      setShowAddMember(false);
      setAddUserId("");
      setAddUserDisplay("");
      setAddRole("member");
      setSearchUsers([]);
      reload();
    } catch { setAddMemberError("添加失败"); }
    finally { setAddMemberLoading(false); }
  }

  async function handleRemoveMember(memberId: number) {
    if (!confirm("确定移除该成员？")) return;
    try {
      await fetch(`/api/platform/workspaces/${id}/members/${memberId}`, { method: "DELETE" });
      reload();
    } catch { window.alert("移除失败"); }
  }

  async function handleUpdateRole(memberId: number, role: string) {
    try {
      await fetch(`/api/platform/workspaces/${id}/members/${memberId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ role }),
      });
      reload();
    } catch { window.alert("更新失败"); }
  }

  if (loading) return <div className="admin-content"><div className="loading">加载中...</div></div>;
  if (error || !workspace) return <div className="admin-content"><div className="alert alert-error">{error || "未找到"}</div></div>;

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">{workspace.name}</h1>
        <p className="page-subtitle">
          <code>{workspace.slug}</code>
          <span className="badge badge-neutral" style={{ marginLeft: "8px" }}>{PLAN_LABELS[workspace.plan] || workspace.plan}</span>
          {workspace.billing_email && <span style={{ marginLeft: "8px", fontSize: "13px", color: "#737373" }}>{workspace.billing_email}</span>}
        </p>
      </div>

      {/* Stats row */}
      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-value">{members.length}</div>
          <div className="stat-label">成员</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">{projects.length}</div>
          <div className="stat-label">项目</div>
        </div>
        <div className="stat-card">
          <div className="stat-value">
            {workspace.balance ? `${parseFloat(workspace.balance).toFixed(2)}` : "0.00"} {workspace.currency || "USD"}
          </div>
          <div className="stat-label">
            当前余额
            <button className="btn btn-secondary btn-sm" style={{ marginLeft: "8px" }} onClick={() => setShowCredit(true)}>+ 充值</button>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-value">
            {workspace.total_spent ? `${parseFloat(workspace.total_spent).toFixed(2)}` : "0.00"}
          </div>
          <div className="stat-label">累计消费</div>
        </div>
      </div>

      {workspace.description && (
        <div className="card" style={{ marginBottom: "16px" }}>
          <p style={{ margin: 0, color: "#737373", fontSize: "14px" }}>{workspace.description}</p>
        </div>
      )}

      {/* Tabs */}
      <div className="toolbar" style={{ marginBottom: "0" }}>
        <button className={`btn btn-sm ${tab === "members" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("members")}>成员 ({members.length})</button>
        <button className={`btn btn-sm ${tab === "projects" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("projects")}>项目 ({projects.length})</button>
        <button className={`btn btn-sm ${tab === "billing" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("billing")}>账单历史</button>
        <button className={`btn btn-sm ${tab === "alerts" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("alerts")}>告警配置</button>
      </div>

      <div className="card">
        {tab === "members" && (
          <>
            <div style={{ padding: "12px", borderBottom: "1px solid #e5e5e5", display: "flex", justifyContent: "flex-end" }}>
              <button className="btn btn-sm btn-primary" onClick={() => setShowAddMember(true)}>+ 添加成员</button>
            </div>
            <div className="table-container">
              <table className="data-table">
                <thead><tr><th>用户名</th><th>显示名</th><th>角色</th><th>状态</th><th>加入时间</th><th>操作</th></tr></thead>
                <tbody>
                  {members.map((m) => (
                    <tr key={m.id ?? m.uid}>
                      <td>{m.username}</td>
                      <td>{m.display_name || "-"}</td>
                      <td>
                        {m.role === "owner" ? (
                          <span className="badge badge-success">{ROLE_LABELS[m.role] || m.role}</span>
                        ) : (
                          <select
                            className="form-input"
                            style={{ padding: "2px 6px", fontSize: "12px", width: "auto" }}
                            value={m.role}
                            onChange={(e) => m.id && handleUpdateRole(m.id, e.target.value)}
                          >
                            <option value="admin">管理员</option>
                            <option value="member">成员</option>
                          </select>
                        )}
                      </td>
                      <td>
                        {m.status && m.status !== "active" ? (
                          <span className="badge badge-neutral">{m.status}</span>
                        ) : (
                          <span className="badge badge-success">正常</span>
                        )}
                      </td>
                      <td>{format(new Date(m.joined_at), "yyyy-MM-dd")}</td>
                      <td>
                        {m.role !== "owner" && (
                          <button className="btn btn-danger btn-sm" onClick={() => m.id && handleRemoveMember(m.id)}>移除</button>
                        )}
                      </td>
                    </tr>
                  ))}
                  {members.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无成员</td></tr>}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "projects" && (
          <div className="table-container">
            <table className="data-table">
              <thead><tr><th>名称</th><th>可见性</th><th>成员</th><th>创建时间</th></tr></thead>
              <tbody>
                {projects.map((p) => (
                  <tr key={p.id}>
                    <td>{p.name}</td>
                    <td><span className={`badge ${p.is_public ? "badge-success" : "badge-neutral"}`}>{p.is_public ? "公开" : "私有"}</span></td>
                    <td>{p.member_count}</td>
                    <td>{format(new Date(p.created_at), "yyyy-MM-dd")}</td>
                  </tr>
                ))}
                {projects.length === 0 && <tr><td colSpan={4} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无项目</td></tr>}
              </tbody>
            </table>
          </div>
        )}

        {tab === "billing" && (
          <div className="table-container">
            <table className="data-table">
              <thead><tr><th>时间</th><th>类型</th><th>金额</th><th>描述</th></tr></thead>
              <tbody>
                {billingHistory.map((b, i) => (
                  <tr key={i}>
                    <td>{format(new Date(b.created_at), "yyyy-MM-dd HH:mm")}</td>
                    <td><span className="badge badge-neutral">{b.reason}</span></td>
                    <td style={{ color: parseFloat(b.amount) >= 0 ? "#16a34a" : "#dc2626" }}>
                      {parseFloat(b.amount) >= 0 ? "+" : ""}{parseFloat(b.amount).toFixed(4)}
                    </td>
                    <td style={{ fontSize: "12px", color: "#737373" }}>{b.description || "-"}</td>
                  </tr>
                ))}
                {billingHistory.length === 0 && <tr><td colSpan={4} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无账单记录</td></tr>}
              </tbody>
            </table>
          </div>
        )}

        {tab === "alerts" && (
          <div>
            <p style={{ fontSize: "13px", color: "#737373", marginBottom: "16px" }}>
              配置 Workspace 的告警规则。当触发条件满足时，将发送邮件通知 Workspace 管理员。
            </p>
            <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              {Object.entries(ALERT_TYPE_LABELS).map(([type, meta]) => {
                const cfg = getAlert(type);
                const enabled = cfg?.enabled ?? false;
                const threshold = cfg?.threshold ?? "";
                const emailEnabled = cfg?.email_enabled ?? true;
                return (
                  <div key={type} style={{ border: "1px solid #e5e5e5", borderRadius: "8px", padding: "16px" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "12px" }}>
                      <div>
                        <div style={{ fontWeight: 500 }}>{meta.label}</div>
                        <div style={{ fontSize: "12px", color: "#737373", marginTop: "2px" }}>
                          当阈值低于 {meta.unit} 时触发
                        </div>
                      </div>
                      <label style={{ display: "flex", alignItems: "center", gap: "8px", cursor: "pointer" }}>
                        <input
                          type="checkbox"
                          checked={enabled}
                          onChange={(e) => updateAlert(type, "enabled", e.target.checked)}
                        />
                        <span style={{ fontSize: "13px" }}>启用告警</span>
                      </label>
                    </div>
                    {enabled && (
                      <div style={{ display: "flex", gap: "12px", alignItems: "center" }}>
                        <div style={{ flex: 1 }}>
                          <input
                            type="number"
                            className="form-input"
                            placeholder={meta.placeholder}
                            value={threshold}
                            min="0"
                            step={meta.unit === "%" ? "1" : "0.01"}
                            onChange={(e) => updateAlert(type, "threshold", e.target.value)}
                            style={{ maxWidth: "200px" }}
                          />
                          <span style={{ marginLeft: "8px", fontSize: "13px", color: "#737373" }}>{meta.unit}</span>
                        </div>
                        <label style={{ display: "flex", alignItems: "center", gap: "6px", cursor: "pointer", fontSize: "13px" }}>
                          <input
                            type="checkbox"
                            checked={emailEnabled}
                            onChange={(e) => updateAlert(type, "email_enabled", e.target.checked)}
                          />
                          邮件通知
                        </label>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: "16px" }}>
              <button className="btn btn-primary" disabled={alertSaving} onClick={handleSaveAlerts}>
                {alertSaving ? "保存中..." : "保存配置"}
              </button>
              <button
                className="btn btn-secondary"
                style={{ marginLeft: "8px" }}
                disabled={alertChecking}
                onClick={async () => {
                  setAlertChecking(true);
                  setAlertCheckMsg(null);
                  try {
                    const res = await fetch("/api/platform/alerts/check", { method: "POST" });
                    const data = await res.json();
                    if (res.ok && data.data) {
                      const d = data.data;
                      setAlertCheckMsg(
                        `检查完成：扫描 ${d.workspaces_checked} 个 Workspace，发送 ${d.alerts_sent} 封告警邮件`
                      );
                    } else {
                      setAlertCheckMsg(`检查失败: ${data.error || res.status}`);
                    }
                  } catch (e) {
                    setAlertCheckMsg(`检查失败: ${e instanceof Error ? e.message : String(e)}`);
                  } finally {
                    setAlertChecking(false);
                  }
                }}
              >
                {alertChecking ? "检查中..." : "立即检查告警"}
              </button>
            </div>
            {alertCheckMsg && (
              <div className={`alert ${alertCheckMsg.includes("失败") ? "alert-error" : "alert-success"}`} style={{ marginTop: "12px" }}>
                {alertCheckMsg}
              </div>
            )}
          </div>
        )}
      </div>

      {showCredit && (
        <div className="modal-overlay" onClick={() => setShowCredit(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "420px" }}>
            <h2 className="modal-title">为 Workspace 充值</h2>
            {creditError && <div className="alert alert-error">{creditError}</div>}
            <div className="form-group">
              <label className="form-label">充值金额（USD）</label>
              <input type="number" className="form-input" min="0.01" step="0.01"
                value={creditAmount} onChange={(e) => setCreditAmount(e.target.value)}
                placeholder="例如：100.00" autoFocus />
            </div>
            <div className="form-group">
              <label className="form-label">备注（可选）</label>
              <input type="text" className="form-input"
                value={creditDesc} onChange={(e) => setCreditDesc(e.target.value)}
                placeholder="充值原因或备注" />
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => setShowCredit(false)}>取消</button>
              <button className="btn btn-primary" disabled={creditLoading} onClick={handleAddCredit}>
                {creditLoading ? "充值中..." : "确认充值"}
              </button>
            </div>
          </div>
        </div>
      )}

      {showAddMember && (
        <div className="modal-overlay" onClick={() => setShowAddMember(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: "440px" }}>
            <h2 className="modal-title">添加成员</h2>
            {addMemberError && <div className="alert alert-error">{addMemberError}</div>}
            <div className="form-group">
              <label className="form-label">搜索用户</label>
              <input
                className="form-input"
                value={addUserDisplay || addUserId}
                onChange={(e) => { setAddUserDisplay(e.target.value); handleUserSearch(e.target.value); }}
                placeholder="输入用户名搜索..."
                autoFocus
              />
              {searchUsers.length > 0 && (
                <div style={{ border: "1px solid #e5e5e5", borderRadius: "6px", marginTop: "4px", maxHeight: "200px", overflowY: "auto", background: "#fff" }}>
                  {searchUsers.map((u) => (
                    <div
                      key={u.uid}
                      style={{ padding: "8px 12px", cursor: "pointer", borderBottom: "1px solid #f0f0f0" }}
                      onClick={() => {
                        setAddUserId(u.uid);
                        setAddUserDisplay(u.username);
                        setSearchUsers([]);
                      }}
                    >
                      <div style={{ fontWeight: 500, fontSize: "14px" }}>{u.username}</div>
                      <div style={{ fontSize: "12px", color: "#737373" }}>{u.display_name || ""}</div>
                    </div>
                  ))}
                </div>
              )}
              {searchLoading && <div style={{ fontSize: "12px", color: "#737373", marginTop: "4px" }}>搜索中...</div>}
            </div>
            <div className="form-group">
              <label className="form-label">角色</label>
              <select className="form-input" value={addRole} onChange={(e) => setAddRole(e.target.value)}>
                <option value="admin">管理员</option>
                <option value="member">成员</option>
              </select>
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => { setShowAddMember(false); setSearchUsers([]); setAddUserDisplay(""); }}>取消</button>
              <button className="btn btn-primary" disabled={addMemberLoading || !addUserId} onClick={handleAddMember}>
                {addMemberLoading ? "添加中..." : "添加"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
