"use client";

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

interface Project {
  id: string;
  name: string;
  display_name: string;
  description: string | null;
  is_public: boolean;
  workspace_id: string | null;
  workspace_name: string | null;
  workspace_slug: string | null;
  workspace_plan: string | null;
  created_by: string;
  created_at: string;
  updated_at: string;
  balance: string;
  currency: string;
}

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

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

const ROLE_LABELS: Record<string, string> = {
  owner: "所有者", admin: "管理员", member: "成员",
};

export default function ProjectDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [project, setProject] = useState<Project | null>(null);
  const [members, setMembers] = useState<Member[]>([]);
  const [billing, setBilling] = useState<{ balance: string; currency: string } | null>(null);
  const [billingHistory, setBillingHistory] = useState<BillingEntry[]>([]);
  const [tab, setTab] = useState<"members" | "billing">("members");
  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 [addScope, setAddScope] = 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);

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    fetch(`/api/admin/projects/${id}`)
      .then(r => r.json())
      .then(data => {
        if (data.error) { setError(data.error); return; }
        setProject(data.project);
        setMembers(data.members || []);
        setBilling(data.billing || null);
        setBillingHistory(data.billingHistory || []);
      })
      .catch(e => setError(String(e)))
      .finally(() => setLoading(false));
  }, [id]);

  function reloadBilling() {
    if (!id) return;
    fetch(`/api/admin/projects/${id}/billing`)
      .then(r => r.json())
      .then(data => {
        if (data.billing) setBilling(data.billing);
        if (data.history) setBillingHistory(data.history);
      })
      .catch(console.error);
  }

  function reload() {
    if (!id) return;
    setLoading(true);
    fetch(`/api/admin/projects/${id}`)
      .then(r => r.json())
      .then(data => {
        if (data.error) { setError(data.error); return; }
        setProject(data.project);
        setMembers(data.members || []);
        setBilling(data.billing || null);
        setBillingHistory(data.billingHistory || []);
      })
      .catch(e => setError(String(e)))
      .finally(() => setLoading(false));
  }

  async function handleUserSearch(q: string) {
    setAddUserId(q); // 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) {
        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("");
    } catch {
      setSearchUsers([]);
      setAddMemberError("搜索失败，请检查网络连接");
    }
    finally { setSearchLoading(false); }
  }

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

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

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

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

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

  return (
    <div className="admin-content">
      <div style={{ marginBottom: "16px" }}>
        <Link href="/admin/projects" className="btn btn-secondary btn-sm">← 返回列表</Link>
      </div>

      <div className="page-header">
        <h1 className="page-title">{project.display_name || project.name}</h1>
        <p className="page-subtitle">
          {project.workspace_name && (
            <Link href={`/admin/workspaces/${project.workspace_id}`} style={{ marginRight: "8px" }}>
              <span className="badge badge-neutral">{project.workspace_name}</span>
            </Link>
          )}
          <span className={`badge ${project.is_public ? "badge-success" : "badge-neutral"}`}>
            {project.is_public ? "公开" : "私有"}
          </span>
          {project.description && (
            <span style={{ marginLeft: "8px", fontSize: "13px", color: "#737373" }}>{project.description}</span>
          )}
        </p>
      </div>

      <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">
            {billing
              ? `${parseFloat(billing.balance).toFixed(4)} ${billing.currency}`
              : "—"}
          </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" style={{ fontSize: "18px" }}>{project.created_by}</div>
          <div className="stat-label">创建者 UID</div>
        </div>
        <div className="stat-card">
          <div className="stat-value" style={{ fontSize: "16px" }}>{format(new Date(project.created_at), "yyyy-MM-dd")}</div>
          <div className="stat-label">创建时间</div>
        </div>
      </div>

      <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 === "billing" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("billing")}>
          账单历史
        </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></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 && handleUpdateScope(m.id, e.target.value)}
                          >
                            <option value="admin">管理员</option>
                            <option value="member">成员</option>
                          </select>
                        )}
                      </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={5} 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(6)}
                    </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>
        )}
      </div>

      {showCredit && (
        <div className="modal-overlay" onClick={() => setShowCredit(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: "420px" }}>
            <h2 className="modal-title">为项目充值</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="例如：10.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={addScope} onChange={e => setAddScope(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>
  );
}
