import { useState } from "react";
import {
  Users,
  UserPlus,
  Search,
  Edit2,
  Trash2,
  Shield,
  Check,
  Loader2,
  X,
  UserMinus,
} from "lucide-react";
import {
  useTeamMembers,
  useAddMember,
  useUpdateMember,
  useRemoveMember,
  useTeamGroups,
  useCreateGroup,
  useUpdateGroup,
  useDeleteGroup,
  useAddGroupMember,
  useRemoveGroupMember,
} from "../../hooks/useTeam";
import type { TeamMember, TeamGroup } from "../../lib/api/team";

type TabType = "employees" | "groups" | "permissions";

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

export function TeamManagement() {
  const [activeTab, setActiveTab] = useState<TabType>("employees");
  const [searchTerm, setSearchTerm] = useState("");

  // ---- add member modal ----
  const [showAddMemberModal, setShowAddMemberModal] = useState(false);
  const [formUsername, setFormUsername] = useState("");
  const [formEmail, setFormEmail] = useState("");
  const [formPassword, setFormPassword] = useState("");
  const [formRole, setFormRole] = useState("member");
  const [formPosition, setFormPosition] = useState("");

  // ---- edit member modal ----
  const [editingMember, setEditingMember] = useState<TeamMember | null>(null);
  const [editRole, setEditRole] = useState("");
  const [editPosition, setEditPosition] = useState("");

  // ---- add group modal ----
  const [showAddGroupModal, setShowAddGroupModal] = useState(false);
  const [formGroupName, setFormGroupName] = useState("");
  const [formGroupDesc, setFormGroupDesc] = useState("");

  // ---- edit group modal ----
  const [editingGroup, setEditingGroup] = useState<TeamGroup | null>(null);
  const [editGroupName, setEditGroupName] = useState("");
  const [editGroupDesc, setEditGroupDesc] = useState("");

  // ---- manage group members modal ----
  const [managingGroupId, setManagingGroupId] = useState<number | null>(null);

  const { data: members = [], isLoading: loadingMembers } = useTeamMembers();
  const { data: groups = [], isLoading: loadingGroups } = useTeamGroups();
  const addMember = useAddMember();
  const updateMember = useUpdateMember();
  const removeMember = useRemoveMember();
  const createGroup = useCreateGroup();
  const updateGroup = useUpdateGroup();
  const deleteGroup = useDeleteGroup();
  const addGroupMember = useAddGroupMember();
  const removeGroupMember = useRemoveGroupMember();

  const tabs = [
    { id: "employees" as TabType, label: "员工管理", icon: Users },
    { id: "groups" as TabType, label: "小组管理", icon: Users },
    { id: "permissions" as TabType, label: "权限说明", icon: Shield },
  ];

  const filteredMembers = members.filter(
    (m) =>
      m.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
      m.email.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const filteredGroups = groups.filter((g) =>
    g.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const memberById = Object.fromEntries(members.map((m) => [m.userId, m]));
  const managingGroup = managingGroupId !== null ? groups.find((g) => g.id === managingGroupId) ?? null : null;

  // handlers
  const handleAddMember = async () => {
    await addMember.mutateAsync({ username: formUsername, email: formEmail, password: formPassword, role: formRole, position: formPosition });
    setFormUsername(""); setFormEmail(""); setFormPassword(""); setFormRole("member"); setFormPosition("");
    setShowAddMemberModal(false);
  };

  const openEditMember = (m: TeamMember) => {
    setEditingMember(m);
    setEditRole(m.role);
    setEditPosition(m.position ?? "");
  };

  const handleEditMember = async () => {
    if (!editingMember) return;
    await updateMember.mutateAsync({ userId: editingMember.userId, patch: { role: editRole, position: editPosition } });
    setEditingMember(null);
  };

  const handleAddGroup = async () => {
    await createGroup.mutateAsync({ name: formGroupName, description: formGroupDesc });
    setFormGroupName(""); setFormGroupDesc("");
    setShowAddGroupModal(false);
  };

  const openEditGroup = (g: TeamGroup) => {
    setEditingGroup(g);
    setEditGroupName(g.name);
    setEditGroupDesc(g.description ?? "");
  };

  const handleEditGroup = async () => {
    if (!editingGroup) return;
    await updateGroup.mutateAsync({ groupId: editingGroup.id, patch: { name: editGroupName, description: editGroupDesc } });
    setEditingGroup(null);
  };

  const addBtnLabel = activeTab === "employees" ? "添加成员" : activeTab === "groups" ? "创建小组" : "";

  return (
    <div className="h-full flex flex-col bg-background">
      {/* Header */}
      <div className="border-b border-border bg-card px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h1 className="text-2xl font-semibold text-foreground mb-1">团队管理</h1>
            <p className="text-sm text-muted-foreground">管理团队成员、小组和权限</p>
          </div>
          {addBtnLabel && (
            <button
              onClick={() => activeTab === "employees" ? setShowAddMemberModal(true) : setShowAddGroupModal(true)}
              className="px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all text-sm flex items-center gap-2"
            >
              <UserPlus className="w-4 h-4" />
              {addBtnLabel}
            </button>
          )}
        </div>

        <div className="flex gap-1">
          {tabs.map((tab) => (
            <button key={tab.id} onClick={() => setActiveTab(tab.id)}
              className={`px-4 py-2 rounded-lg text-sm flex items-center gap-2 transition-all ${
                activeTab === tab.id ? "bg-accent text-accent-foreground font-medium" : "text-muted-foreground hover:text-foreground hover:bg-muted"
              }`}>
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-7xl mx-auto">
          <div className="mb-6">
            <div className="relative max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <input type="text" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="搜索..."
                className="w-full pl-9 pr-4 py-2 rounded-lg border border-border bg-card text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
            </div>
          </div>

          {/* Employees Tab */}
          {activeTab === "employees" && (
            <div className="space-y-3">
              {loadingMembers && <div className="text-center py-8"><Loader2 className="w-6 h-6 animate-spin mx-auto text-muted-foreground" /></div>}
              {filteredMembers.map((member) => (
                <div key={member.userId} className="rounded-xl border border-border bg-card p-4 flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-full bg-accent flex items-center justify-center text-primary font-semibold text-lg">
                      {member.username.charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <div className="flex items-center gap-3 mb-1">
                        <span className="font-medium text-foreground">{member.username}</span>
                        {member.position && <span className="text-xs text-muted-foreground">{member.position}</span>}
                        <span className="px-2 py-0.5 rounded bg-accent text-primary text-xs">{roleLabels[member.role] ?? member.role}</span>
                        {member.status === 1
                          ? <span className="px-2 py-0.5 rounded bg-green-100 text-green-700 text-xs">已启用</span>
                          : <span className="px-2 py-0.5 rounded bg-gray-100 text-gray-700 text-xs">已禁用</span>}
                      </div>
                      <div className="text-sm text-muted-foreground">{member.email}</div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {member.role !== "owner" && (
                      <>
                        <button onClick={() => openEditMember(member)}
                          className="px-3 py-1.5 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors text-xs flex items-center gap-1">
                          <Edit2 className="w-3 h-3" />编辑
                        </button>
                        <button onClick={() => removeMember.mutate(member.userId)}
                          className="p-1.5 rounded-lg border border-border bg-card text-destructive hover:bg-destructive/10 transition-colors">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </>
                    )}
                  </div>
                </div>
              ))}
              {!loadingMembers && filteredMembers.length === 0 && (
                <div className="text-center py-16 text-muted-foreground">暂无成员</div>
              )}
            </div>
          )}

          {/* Groups Tab */}
          {activeTab === "groups" && (
            <div className="grid grid-cols-2 gap-4">
              {loadingGroups && <div className="col-span-2 text-center py-8"><Loader2 className="w-6 h-6 animate-spin mx-auto text-muted-foreground" /></div>}
              {filteredGroups.map((group) => (
                <div key={group.id} className="rounded-xl border border-border bg-card p-5">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h3 className="font-medium text-foreground mb-1">{group.name}</h3>
                      {group.description && <p className="text-sm text-muted-foreground">{group.description}</p>}
                    </div>
                    <div className="flex items-center gap-1">
                      <button onClick={() => openEditGroup(group)}
                        className="p-1.5 rounded-lg hover:bg-muted transition-colors text-muted-foreground hover:text-foreground">
                        <Edit2 className="w-4 h-4" />
                      </button>
                      <button onClick={() => deleteGroup.mutate(group.id)}
                        className="p-1.5 rounded-lg hover:bg-destructive/10 text-destructive transition-colors">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  <div className="mb-4">
                    <div className="flex items-center justify-between mb-2">
                      <div className="text-xs text-muted-foreground">成员 ({group.memberIds.length})</div>
                      <button onClick={() => setManagingGroupId(group.id)}
                        className="text-xs text-primary hover:underline flex items-center gap-1">
                        <UserPlus className="w-3 h-3" />管理成员
                      </button>
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                      {group.memberIds.map((uid) => {
                        const m = memberById[uid];
                        return (
                          <span key={uid} className="px-2.5 py-1 rounded-lg bg-muted text-foreground text-xs flex items-center gap-1">
                            {m ? m.username : `#${uid}`}
                            <button onClick={() => removeGroupMember.mutate({ groupId: group.id, userId: uid })}
                              className="text-muted-foreground hover:text-destructive transition-colors">
                              <X className="w-3 h-3" />
                            </button>
                          </span>
                        );
                      })}
                      {group.memberIds.length === 0 && (
                        <span className="text-xs text-muted-foreground">暂无成员</span>
                      )}
                    </div>
                  </div>
                </div>
              ))}
              {!loadingGroups && filteredGroups.length === 0 && (
                <div className="col-span-2 text-center py-16 text-muted-foreground">暂无小组</div>
              )}
            </div>
          )}

          {/* Permissions Tab */}
          {activeTab === "permissions" && (
            <div className="grid grid-cols-2 gap-4">
              {[
                { name: "owner（所有者）", description: "最高权限，可管理成员、计费、所有功能", includes: ["成员管理", "计费管理", "项目管理", "资产库", "全部操作"] },
                { name: "admin（管理员）", description: "可管理成员和项目，但不能操作计费", includes: ["成员管理", "项目管理", "资产库", "生成操作"] },
                { name: "member（成员）", description: "可操作已授权的项目功能", includes: ["项目查看", "分镜编辑", "视频生成", "资产库查看"] },
              ].map((role, idx) => (
                <div key={idx} className="rounded-xl border border-border bg-card p-5">
                  <div className="flex items-start gap-3 mb-4">
                    <div className="w-10 h-10 rounded-lg bg-accent flex items-center justify-center flex-shrink-0">
                      <Shield className="w-5 h-5 text-primary" />
                    </div>
                    <div>
                      <h3 className="font-medium text-foreground mb-1">{role.name}</h3>
                      <p className="text-sm text-muted-foreground">{role.description}</p>
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground mb-2">包含权限</div>
                    <div className="space-y-2">
                      {role.includes.map((item) => (
                        <div key={item} className="flex items-center gap-2 text-sm text-foreground">
                          <Check className="w-4 h-4 text-green-500" />{item}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* ---- Add Member Modal ---- */}
      {showAddMemberModal && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-lg w-full">
            <h2 className="text-xl font-semibold text-foreground mb-6">添加团队成员</h2>
            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">用户名</label>
                <input value={formUsername} onChange={(e) => setFormUsername(e.target.value)} type="text" placeholder="输入用户名"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">邮箱</label>
                <input value={formEmail} onChange={(e) => setFormEmail(e.target.value)} type="email" placeholder="输入邮箱"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">初始密码</label>
                <input value={formPassword} onChange={(e) => setFormPassword(e.target.value)} type="password" placeholder="设置初始密码"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">角色</label>
                  <select value={formRole} onChange={(e) => setFormRole(e.target.value)}
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20">
                    <option value="member">成员</option>
                    <option value="admin">管理员</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">职位</label>
                  <input value={formPosition} onChange={(e) => setFormPosition(e.target.value)} type="text" placeholder="如：分镜师"
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
                </div>
              </div>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setShowAddMemberModal(false)}
                className="flex-1 px-4 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">取消</button>
              <button onClick={handleAddMember} disabled={addMember.isPending || !formUsername || !formEmail || !formPassword}
                className="flex-1 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all disabled:opacity-50 flex items-center justify-center gap-2">
                {addMember.isPending && <Loader2 className="w-4 h-4 animate-spin" />}确定
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ---- Edit Member Modal ---- */}
      {editingMember && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-md w-full">
            <h2 className="text-xl font-semibold text-foreground mb-2">编辑成员</h2>
            <p className="text-sm text-muted-foreground mb-6">{editingMember.username} · {editingMember.email}</p>
            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">角色</label>
                <select value={editRole} onChange={(e) => setEditRole(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20">
                  <option value="member">成员</option>
                  <option value="admin">管理员</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">职位</label>
                <input value={editPosition} onChange={(e) => setEditPosition(e.target.value)} type="text" placeholder="如：分镜师"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setEditingMember(null)}
                className="flex-1 px-4 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">取消</button>
              <button onClick={handleEditMember} disabled={updateMember.isPending}
                className="flex-1 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all disabled:opacity-50 flex items-center justify-center gap-2">
                {updateMember.isPending && <Loader2 className="w-4 h-4 animate-spin" />}保存
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ---- Add Group Modal ---- */}
      {showAddGroupModal && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-md w-full">
            <h2 className="text-xl font-semibold text-foreground mb-6">创建小组</h2>
            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">小组名称</label>
                <input value={formGroupName} onChange={(e) => setFormGroupName(e.target.value)} type="text" placeholder="输入小组名称"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">描述</label>
                <textarea value={formGroupDesc} onChange={(e) => setFormGroupDesc(e.target.value)} rows={3} placeholder="输入小组描述"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none" />
              </div>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setShowAddGroupModal(false)}
                className="flex-1 px-4 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">取消</button>
              <button onClick={handleAddGroup} disabled={createGroup.isPending || !formGroupName.trim()}
                className="flex-1 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all disabled:opacity-50 flex items-center justify-center gap-2">
                {createGroup.isPending && <Loader2 className="w-4 h-4 animate-spin" />}创建
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ---- Edit Group Modal ---- */}
      {editingGroup && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-md w-full">
            <h2 className="text-xl font-semibold text-foreground mb-6">编辑小组</h2>
            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">小组名称</label>
                <input value={editGroupName} onChange={(e) => setEditGroupName(e.target.value)} type="text"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20" />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">描述</label>
                <textarea value={editGroupDesc} onChange={(e) => setEditGroupDesc(e.target.value)} rows={3}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 resize-none" />
              </div>
            </div>
            <div className="flex gap-3">
              <button onClick={() => setEditingGroup(null)}
                className="flex-1 px-4 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors">取消</button>
              <button onClick={handleEditGroup} disabled={updateGroup.isPending || !editGroupName.trim()}
                className="flex-1 px-4 py-2 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all disabled:opacity-50 flex items-center justify-center gap-2">
                {updateGroup.isPending && <Loader2 className="w-4 h-4 animate-spin" />}保存
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ---- Manage Group Members Modal ---- */}
      {managingGroup && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-lg w-full">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-semibold text-foreground">管理小组成员 · {managingGroup.name}</h2>
              <button onClick={() => setManagingGroupId(null)} className="p-1.5 rounded-lg hover:bg-muted transition-colors">
                <X className="w-5 h-5 text-muted-foreground" />
              </button>
            </div>

            <div className="mb-4">
              <div className="text-sm font-medium text-foreground mb-3">当前成员</div>
              {managingGroup.memberIds.length === 0
                ? <p className="text-sm text-muted-foreground">暂无成员</p>
                : (
                  <div className="space-y-2">
                    {managingGroup.memberIds.map((uid) => {
                      const m = memberById[uid];
                      return (
                        <div key={uid} className="flex items-center justify-between rounded-lg bg-muted px-3 py-2">
                          <span className="text-sm text-foreground">{m ? `${m.username} (${m.email})` : `#${uid}`}</span>
                          <button onClick={() => removeGroupMember.mutate({ groupId: managingGroup.id, userId: uid })}
                            className="p-1 rounded hover:bg-destructive/10 text-destructive transition-colors">
                            <UserMinus className="w-4 h-4" />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                )}
            </div>

            <div>
              <div className="text-sm font-medium text-foreground mb-3">添加成员</div>
              <div className="space-y-2">
                {members
                  .filter((m) => !managingGroup.memberIds.includes(m.userId))
                  .map((m) => (
                    <div key={m.userId} className="flex items-center justify-between rounded-lg border border-border px-3 py-2">
                      <span className="text-sm text-foreground">{m.username} <span className="text-muted-foreground">({m.email})</span></span>
                      <button onClick={() => addGroupMember.mutate({ groupId: managingGroup.id, userId: m.userId })}
                        className="px-3 py-1 rounded-lg bg-primary/10 text-primary hover:bg-primary/20 transition-colors text-xs">
                        添加
                      </button>
                    </div>
                  ))}
                {members.filter((m) => !managingGroup.memberIds.includes(m.userId)).length === 0 && (
                  <p className="text-sm text-muted-foreground">所有成员均已在小组中</p>
                )}
              </div>
            </div>

            <div className="mt-6 flex justify-end">
              <button onClick={() => setManagingGroupId(null)}
                className="px-6 py-2 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors text-sm">
                完成
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
