import { useState } from "react";
import { useParams } from "react-router";
import {
  Users, UserPlus, Shield, Trash2, Loader2, X, Check, Settings,
} from "lucide-react";
import { useTeamMembers, useUpdateMember, useRemoveMember, useAddMember } from "../../hooks/useTeam";
import { useProject, useUpdateProject } from "../../hooks/useProjects";
import {
  aspectRatioOptions,
  getAspectRatioLabel,
  getProjectStyleLabel,
  getResolutionLabel,
  projectStyleOptions,
  resolutionOptions,
} from "../../lib/projectStyles";

const ROLES = ["owner", "admin", "member"] as const;
type Role = typeof ROLES[number];

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

const rolePermissions: Record<string, string[]> = {
  owner: ["完全控制", "删除项目", "管理成员", "编辑内容", "查看内容"],
  admin: ["管理成员", "编辑内容", "审核分镜", "生成视频", "查看内容"],
  member: ["编辑内容", "创建分镜", "修改分镜", "查看内容"],
};

export function ProjectSettings() {
  const { projectId } = useParams();
  const numId = projectId ?? "";

  const { data: project, isLoading: loadingProject } = useProject(numId);
  const { data: members = [], isLoading: loadingMembers } = useTeamMembers();
  const updateMember = useUpdateMember();
  const removeMember = useRemoveMember();
  const addMember = useAddMember();
  const updateProject = useUpdateProject(numId);

  const [showInviteModal, setShowInviteModal] = useState(false);
  const [inviteForm, setInviteForm] = useState({ username: "", email: "", password: "", role: "member" });
  const [inviteError, setInviteError] = useState("");

  const [editingProject, setEditingProject] = useState(false);
  const [projectForm, setProjectForm] = useState({
    name: "",
    description: "",
    style: "",
    aspectRatio: "",
    resolution: "",
  });

  const openEditProject = () => {
    setProjectForm({
      name: project?.name ?? "",
      description: project?.description ?? "",
      style: project?.style ?? "",
      aspectRatio: project?.aspectRatio ?? "",
      resolution: project?.resolution ?? "",
    });
    setEditingProject(true);
  };

  const handleSaveProject = async () => {
    await updateProject.mutateAsync(projectForm);
    setEditingProject(false);
  };

  const handleRoleChange = async (userId: number, role: string) => {
    await updateMember.mutateAsync({ userId, patch: { role } });
  };

  const handleRemove = async (userId: number) => {
    if (!confirm("确定要移除该成员吗？")) return;
    await removeMember.mutateAsync(userId);
  };

  const handleInvite = async () => {
    setInviteError("");
    if (!inviteForm.username.trim() || !inviteForm.email.trim() || !inviteForm.password.trim()) {
      setInviteError("用户名、邮箱和密码不能为空");
      return;
    }
    try {
      await addMember.mutateAsync(inviteForm);
      setShowInviteModal(false);
      setInviteForm({ username: "", email: "", password: "", role: "member" });
    } catch {
      setInviteError("添加失败，该邮箱可能已存在");
    }
  };

  const roleCounts = (role: string) => members.filter((m) => m.role === role).length;

  if (loadingProject || loadingMembers) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-6 h-6 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="h-full overflow-auto bg-background p-6">
      <div className="max-w-6xl mx-auto">
        <div className="mb-6">
          <h1 className="text-2xl font-semibold text-foreground mb-1">项目设置</h1>
          <p className="text-sm text-muted-foreground">管理项目信息和团队成员权限</p>
        </div>

        {/* Project Info */}
        <div className="rounded-xl border border-border bg-card p-5 mb-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-foreground flex items-center gap-2">
              <Settings className="w-4 h-4" /> 项目信息
            </h2>
            {!editingProject && (
              <button
                onClick={openEditProject}
                className="px-3 py-1.5 rounded-lg border border-border text-sm text-foreground hover:bg-muted transition-colors"
              >
                编辑
              </button>
            )}
          </div>
          {editingProject ? (
            <div className="space-y-3">
              <div>
                <label className="block text-xs text-muted-foreground mb-1">项目名称</label>
                <input
                  type="text"
                  value={projectForm.name}
                  onChange={(e) => setProjectForm({ ...projectForm, name: 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"
                />
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">项目描述</label>
                <textarea
                  value={projectForm.description}
                  onChange={(e) => setProjectForm({ ...projectForm, description: e.target.value })}
                  rows={2}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground resize-none focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => setEditingProject(false)}
                  className="px-4 py-2 rounded-lg border border-border text-sm text-foreground hover:bg-muted transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleSaveProject}
                  disabled={updateProject.isPending}
                  className="px-4 py-2 rounded-lg bg-primary text-white text-sm hover:opacity-90 flex items-center gap-2 disabled:opacity-60"
                >
                  {updateProject.isPending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Check className="w-3.5 h-3.5" />}
                  保存
                </button>
              </div>
            </div>
          ) : (
            <div className="space-y-2 text-sm">
              <div>
                <span className="text-muted-foreground">名称：</span>
                <span className="text-foreground font-medium">{project?.name}</span>
              </div>
              <div>
                <span className="text-muted-foreground">描述：</span>
                <span className="text-foreground">{project?.description || "—"}</span>
              </div>
              <div>
                <span className="text-muted-foreground">状态：</span>
                <span className="text-foreground">{project?.status}</span>
              </div>
            </div>
          )}
        </div>

        {/* Team Overview */}
        <div className="grid grid-cols-4 gap-4 mb-6">
          <div className="rounded-xl border border-border bg-card p-4">
            <div className="w-10 h-10 rounded-lg bg-accent flex items-center justify-center mb-3">
              <Users className="w-5 h-5 text-primary" />
            </div>
            <div className="text-2xl font-semibold text-foreground mb-0.5">{members.length}</div>
            <div className="text-xs text-muted-foreground">团队成员</div>
          </div>
          {["owner", "admin", "member"].map((role) => (
            <div key={role} className="rounded-xl border border-border bg-card p-4">
              <div className="text-2xl font-semibold text-foreground mb-0.5">{roleCounts(role)}</div>
              <div className="text-xs text-muted-foreground">{roleLabels[role]}</div>
            </div>
          ))}
        </div>

        {/* Invite Button */}
        <div className="mb-6">
          <button
            onClick={() => setShowInviteModal(true)}
            className="px-5 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white flex items-center gap-2 hover:shadow-md transition-all text-sm"
          >
            <UserPlus className="w-4 h-4" />
            添加成员
          </button>
        </div>

        {/* Members List */}
        <div className="mb-8">
          <h2 className="text-lg font-semibold text-foreground mb-4">团队成员</h2>
          {members.length === 0 ? (
            <div className="rounded-xl border border-border bg-card p-8 text-center text-sm text-muted-foreground">
              暂无成员
            </div>
          ) : (
            <div className="space-y-3">
              {members.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-10 h-10 rounded-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center">
                      <span className="text-sm font-semibold text-primary">
                        {member.username?.[0]?.toUpperCase() ?? "U"}
                      </span>
                    </div>
                    <div>
                      <div className="text-sm font-medium text-foreground mb-0.5">{member.username}</div>
                      <div className="text-xs text-muted-foreground">{member.email}</div>
                    </div>
                  </div>

                  <div className="flex items-center gap-4">
                    <div className="text-xs text-muted-foreground">
                      加入于 {member.joinedAt?.slice(0, 10)}
                    </div>
                    <select
                      value={member.role}
                      onChange={(e) => handleRoleChange(member.userId, e.target.value)}
                      disabled={member.role === "owner" || updateMember.isPending}
                      className="px-3 py-1.5 rounded-lg border border-border bg-card text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                    >
                      {ROLES.map((r) => (
                        <option key={r} value={r}>{roleLabels[r]}</option>
                      ))}
                    </select>
                    {member.role !== "owner" && (
                      <button
                        onClick={() => handleRemove(member.userId)}
                        disabled={removeMember.isPending}
                        className="p-1.5 rounded-lg border border-border bg-card text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Role Permissions */}
        <div>
          <h2 className="text-lg font-semibold text-foreground mb-4">角色权限说明</h2>
          <div className="grid grid-cols-3 gap-4">
            {Object.entries(rolePermissions).map(([key, perms]) => (
              <div key={key} className="rounded-xl border border-border bg-card p-4">
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-8 h-8 rounded-lg bg-accent flex items-center justify-center">
                    <Shield className="w-4 h-4 text-primary" />
                  </div>
                  <h3 className="font-medium text-foreground">{roleLabels[key]}</h3>
                </div>
                <div className="space-y-2">
                  {perms.map((p, i) => (
                    <div key={i} className="flex items-center gap-2 text-sm text-muted-foreground">
                      <div className="w-1 h-1 rounded-full bg-primary" />
                      {p}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Invite Modal */}
        {showInviteModal && (
          <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">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-foreground">添加成员</h2>
                <button onClick={() => setShowInviteModal(false)} className="p-2 hover:bg-muted rounded-lg transition-colors">
                  <X className="w-5 h-5 text-muted-foreground" />
                </button>
              </div>

              <div className="space-y-4 mb-6">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">用户名</label>
                  <input
                    type="text"
                    value={inviteForm.username}
                    onChange={(e) => setInviteForm({ ...inviteForm, username: e.target.value })}
                    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
                    type="email"
                    value={inviteForm.email}
                    onChange={(e) => setInviteForm({ ...inviteForm, email: e.target.value })}
                    placeholder="member@example.com"
                    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
                    type="password"
                    value={inviteForm.password}
                    onChange={(e) => setInviteForm({ ...inviteForm, password: e.target.value })}
                    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>
                  <select
                    value={inviteForm.role}
                    onChange={(e) => setInviteForm({ ...inviteForm, role: 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 cursor-pointer"
                  >
                    <option value="admin">管理员</option>
                    <option value="member">成员</option>
                  </select>
                </div>
                {inviteError && <p className="text-sm text-destructive">{inviteError}</p>}
              </div>

              <div className="flex gap-3">
                <button
                  onClick={() => setShowInviteModal(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={handleInvite}
                  disabled={addMember.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"
                >
                  {addMember.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
                  添加
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
