"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type User = {
  id: number;
  email: string;
  name: string | null;
  role: string;
  isActive: boolean;
};

export default function AdminUsersClient({
  users,
  currentUserId,
  createAdminAction,
  updateAdminAction,
}: {
  users: User[];
  currentUserId: number;
  createAdminAction: (formData: FormData) => Promise<void>;
  updateAdminAction: (formData: FormData) => Promise<void>;
}) {
  const [showCreate, setShowCreate] = useState(false);
  const [editing, setEditing] = useState<User | null>(null);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold">管理员管理</h1>
        <Button onClick={() => setShowCreate(true)}>新建管理员</Button>
      </div>

      <div className="overflow-hidden rounded-md border">
        <div className="grid grid-cols-12 bg-gray-50 p-3 text-sm font-medium text-gray-600">
          <div className="col-span-1">ID</div>
          <div className="col-span-3">邮箱</div>
          <div className="col-span-3">姓名</div>
          <div className="col-span-2">角色</div>
          <div className="col-span-2">状态</div>
          <div className="col-span-1 text-right pr-2">操作</div>
        </div>
        <div className="divide-y">
          {users.map((u) => (
            <button
              key={u.id}
              className="grid w-full grid-cols-12 items-center gap-2 p-3 text-left hover:bg-gray-50"
              onClick={() => setEditing(u)}
            >
              <div className="col-span-1 text-sm text-gray-500">{u.id}</div>
              <div className="col-span-3 truncate text-sm">{u.email}</div>
              <div className="col-span-3 truncate text-sm">{u.name ?? ""}</div>
              <div className="col-span-2 text-sm">{u.role === 'super' ? '系统管理员' : '普通管理员'}</div>
              <div className="col-span-2 text-sm">{u.isActive ? '启用' : '停用'}</div>
              <div className="col-span-1 text-right text-sm text-blue-600">编辑</div>
            </button>
          ))}
          {users.length === 0 && (
            <div className="p-4 text-sm text-gray-500">暂无管理员</div>
          )}
        </div>
      </div>

      {showCreate && (
        <Modal onClose={() => setShowCreate(false)} title="新建管理员">
          <form action={createAdminAction} className="space-y-4" onSubmit={() => setShowCreate(false)}>
            <div className="space-y-2">
              <Label htmlFor="name">姓名</Label>
              <Input id="name" name="name" placeholder="李四" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">邮箱</Label>
              <Input id="email" name="email" type="email" placeholder="user@example.com" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">初始密码</Label>
              <Input id="password" name="password" type="password" required />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="role">角色</Label>
                <select id="role" name="role" className="h-9 w-full rounded-md border px-3 text-sm">
                  <option value="admin">普通管理员</option>
                  <option value="super">系统管理员</option>
                </select>
              </div>
              <div className="flex items-end gap-2 pt-6">
                <input id="isActive" name="isActive" type="checkbox" defaultChecked className="h-4 w-4" />
                <Label htmlFor="isActive">启用账号</Label>
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => setShowCreate(false)}>取消</Button>
              <Button type="submit">创建</Button>
            </div>
          </form>
        </Modal>
      )}

      {editing && (
        <Modal onClose={() => setEditing(null)} title="编辑管理员">
          <form action={updateAdminAction} className="space-y-4" onSubmit={() => setEditing(null)}>
            <input type="hidden" name="id" value={editing.id} />
            <div className="space-y-2">
              <Label>邮箱</Label>
              <Input defaultValue={editing.email} disabled />
            </div>
            <div className="space-y-2">
              <Label htmlFor="name">姓名</Label>
              <Input id="name" name="name" defaultValue={editing.name ?? ''} />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="role">角色</Label>
                <select
                  id="role"
                  name="role"
                  defaultValue={editing.role}
                  className="h-9 w-full rounded-md border px-3 text-sm"
                  disabled={editing.id === currentUserId}
                >
                  <option value="admin">普通管理员</option>
                  <option value="super">系统管理员</option>
                </select>
                {editing.id === currentUserId && (
                  <p className="mt-1 text-xs text-gray-500">不能修改自己的角色</p>
                )}
              </div>
              <div className="flex items-end gap-2 pt-6">
                <input
                  id="isActiveEdit"
                  name="isActive"
                  type="checkbox"
                  defaultChecked={editing.isActive}
                  className="h-4 w-4"
                  disabled={editing.id === currentUserId}
                />
                <Label htmlFor="isActiveEdit">启用账号</Label>
              </div>
            </div>
            {editing.id === currentUserId && (
              <p className="text-xs text-gray-500">不能修改自己的状态</p>
            )}
            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => setEditing(null)}>取消</Button>
              <Button type="submit">保存</Button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  );
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/30" onClick={onClose} />
      <div className="relative z-10 w-full max-w-lg rounded-lg bg-white p-6 shadow-lg">
        <div className="mb-4 text-lg font-semibold">{title}</div>
        {children}
      </div>
    </div>
  );
}

