"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";

interface Role {
  id: number;
  name: string;
  description: string | null;
}

interface AdminUser {
  id: number;
  username: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  roles: Role[];
}

interface AllRole {
  id: number;
  name: string;
  description: string | null;
}

export default function UserDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [user, setUser] = useState<AdminUser | null>(null);
  const [allRoles, setAllRoles] = useState<AllRole[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  const [showEditRoles, setShowEditRoles] = useState(false);
  const [selectedRoles, setSelectedRoles] = useState<number[]>([]);
  const [newPassword, setNewPassword] = useState("");

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    fetch(`/api/users/${id}`)
      .then((r) => r.json())
      .then((data) => {
        if (data.error) { setError(data.error); return; }
        setUser(data);
        setSelectedRoles(data.roles.map((r: Role) => r.id));
      })
      .catch((e) => setError(String(e)))
      .finally(() => setLoading(false));
  }, [id]);

  useEffect(() => {
    fetch("/api/roles")
      .then((r) => r.json())
      .then((data) => setAllRoles(data.roles || []))
      .catch(console.error);
  }, []);

  async function handleSave() {
    setSaving(true);
    setError("");
    const body: Record<string, unknown> = {};
    if (newPassword) body.password = newPassword;
    if (showEditRoles) body.roleIds = selectedRoles;

    const res = await fetch(`/api/users/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok) { setError(data.error || "保存失败"); setSaving(false); return; }
    setNewPassword("");
    setShowEditRoles(false);
    // reload user
    const reloaded = await fetch(`/api/users/${id}`).then(r => r.json());
    setUser(reloaded);
    setSelectedRoles(reloaded.roles.map((r: Role) => r.id));
    setSaving(false);
  }

  if (loading) return <div className="admin-content"><div className="loading">加载中...</div></div>;
  if (error && !user) return <div className="admin-content"><div className="alert alert-error">{error}</div></div>;
  if (!user) return <div className="admin-content"><div className="alert alert-error">用户不存在</div></div>;

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

      <div className="page-header">
        <h1 className="page-title">{user.username}</h1>
        <p className="page-subtitle">
          <span className={`badge ${user.is_active ? "badge-success" : "badge-danger"}`}>
            {user.is_active ? "启用" : "禁用"}
          </span>
        </p>
      </div>

      {error && <div className="alert alert-error" style={{ marginBottom: "16px" }}>{error}</div>}

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
        {/* 基本信息 */}
        <div className="card">
          <div className="card-title">基本信息</div>
          <table className="info-table">
            <tbody>
              <tr><td className="info-label">ID</td><td>{user.id}</td></tr>
              <tr><td className="info-label">用户名</td><td>{user.username}</td></tr>
              <tr><td className="info-label">状态</td><td>
                <span className={`badge ${user.is_active ? "badge-success" : "badge-danger"}`}>
                  {user.is_active ? "启用" : "禁用"}
                </span>
              </td></tr>
              <tr><td className="info-label">创建时间</td><td>{new Date(user.created_at).toLocaleString()}</td></tr>
              <tr><td className="info-label">更新时间</td><td>{new Date(user.updated_at).toLocaleString()}</td></tr>
            </tbody>
          </table>
        </div>

        {/* 角色 */}
        <div className="card">
          <div className="card-title">角色分配</div>
          {user.roles.length === 0 ? (
            <p style={{ color: "#737373", fontSize: "14px" }}>暂无角色</p>
          ) : (
            <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", marginBottom: "12px" }}>
              {user.roles.map((r) => (
                <span key={r.id} className="badge badge-neutral">{r.name}</span>
              ))}
            </div>
          )}
          {showEditRoles ? (
            <div className="checkbox-group" style={{ marginBottom: "12px" }}>
              {allRoles.map((r) => (
                <label key={r.id} className="checkbox-item">
                  <input type="checkbox" checked={selectedRoles.includes(r.id)}
                    onChange={(e) => {
                      setSelectedRoles(e.target.checked
                        ? [...selectedRoles, r.id]
                        : selectedRoles.filter(x => x !== r.id));
                    }} />
                  {r.name}
                </label>
              ))}
            </div>
          ) : null}
          <div style={{ display: "flex", gap: "8px" }}>
            {!showEditRoles && (
              <button className="btn btn-secondary btn-sm" onClick={() => setShowEditRoles(true)}>修改角色</button>
            )}
            {showEditRoles && (
              <>
                <button className="btn btn-secondary btn-sm" onClick={() => { setShowEditRoles(false); setSelectedRoles(user.roles.map((r: Role) => r.id)); }}>取消</button>
                <button className="btn btn-primary btn-sm" disabled={saving} onClick={handleSave}>
                  {saving ? "保存中..." : "保存角色"}
                </button>
              </>
            )}
          </div>
        </div>

        {/* 重置密码 */}
        <div className="card">
          <div className="card-title">重置密码</div>
          <div className="form-group">
            <label className="form-label">新密码（留空则不修改）</label>
            <input type="password" className="form-input" value={newPassword}
              minLength={6} onChange={(e) => setNewPassword(e.target.value)}
              placeholder="至少6位" />
          </div>
          <button className="btn btn-primary btn-sm" disabled={!newPassword || saving}
            onClick={handleSave}>
            {saving ? "保存中..." : "保存密码"}
          </button>
        </div>

        {/* 快速操作 */}
        <div className="card">
          <div className="card-title">快速操作</div>
          <button
            className={`btn btn-sm ${user.is_active ? "btn-danger" : "btn-primary"}`}
            style={{ marginRight: "8px", marginBottom: "8px" }}
            onClick={async () => {
              const res = await fetch(`/api/users/${id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ isActive: !user!.is_active }),
              });
              if (res.ok) {
                setUser({ ...user, is_active: !user.is_active });
              }
            }}
          >
            {user.is_active ? "禁用账号" : "启用账号"}
          </button>
          {user.id !== -1 && (
            <button className="btn btn-danger btn-sm"
              onClick={async () => {
                if (!confirm(`确定删除用户 "${user.username}" 吗？`)) return;
                const res = await fetch(`/api/users/${id}`, { method: "DELETE" });
                if (res.ok) router.push("/admin/users");
              }}>
              删除用户
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
