import React, { useState, useMemo, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Plus, Search, Edit, Trash2, Filter, X } from 'lucide-react';
import { userClient } from '@/client/api';
import type { InferRequestType, InferResponseType } from 'hono/client';
import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Badge } from '@/client/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import AvatarSelector from '@/client/admin/components/AvatarSelector';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { Skeleton } from '@/client/components/ui/skeleton';
import { Switch } from '@/client/components/ui/switch';
import { DisabledStatus } from '@/share/types';
import { CreateUserDto, UpdateUserDto } from '@d8d/user-module/schemas';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/client/components/ui/popover';
import { Calendar } from '@/client/components/ui/calendar';
import { cn } from '@/client/lib/utils';

// 使用RPC方式提取类型
type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];
type UserResponse = InferResponseType<typeof userClient.$get, 200>['data'][0];

// 直接使用后端定义的 schema
const createUserFormSchema = CreateUserDto;
const updateUserFormSchema = UpdateUserDto;

type CreateUserFormData = CreateUserRequest;
type UpdateUserFormData = UpdateUserRequest;

export const UsersPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    keyword: ''
  });
  const [filters, setFilters] = useState({
    isDisabled: undefined as number | undefined,
    roleIds: [] as number[],
    createdAt: undefined as { gte?: string; lte?: string } | undefined
  });
  const [showFilters, setShowFilters] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserResponse | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<number | null>(null);
  // Avatar selector is now integrated, no separate state needed

  const [isCreateForm, setIsCreateForm] = useState(true);
  
  const createForm = useForm<CreateUserFormData>({
    resolver: zodResolver(createUserFormSchema),
    defaultValues: {
      username: '',
      nickname: undefined,
      email: null,
      phone: null,
      name: null,
      password: '',
      isDisabled: DisabledStatus.ENABLED,
    },
  });

  const updateForm = useForm<UpdateUserFormData>({
    resolver: zodResolver(updateUserFormSchema),
    defaultValues: {
      username: undefined,
      nickname: undefined,
      email: null,
      phone: null,
      name: null,
      password: undefined,
      isDisabled: undefined,
    },
  });

  const { data: usersData, isLoading, refetch } = useQuery({
    queryKey: ['users', searchParams, filters],
    queryFn: async () => {
      const filterParams: Record<string, unknown> = {};

      if (filters.isDisabled !== undefined) {
        filterParams.isDisabled = filters.isDisabled;
      }

      if (filters.roleIds.length > 0) {
        filterParams['roles.id'] = filters.roleIds;
      }

      if (filters.createdAt) {
        filterParams.createdAt = filters.createdAt;
      }

      const res = await userClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.keyword,
          filters: Object.keys(filterParams).length > 0 ? JSON.stringify(filterParams) : undefined
        }
      });
      if (res.status !== 200) {
        throw new Error('获取用户列表失败');
      }
      return await res.json();
    }
  });

  const users = usersData?.data || [];
  const totalCount = usersData?.pagination?.total || 0;

  // 防抖搜索函数
  const debounce = (func: Function, delay: number) => {
    let timeoutId: NodeJS.Timeout;
    return (...args: any[]) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func(...args), delay);
    };
  };

  // 使用useCallback包装防抖搜索
  const debouncedSearch = useCallback(
    debounce((keyword: string) => {
      setSearchParams(prev => ({ ...prev, keyword, page: 1 }));
    }, 300),
    []
  );

  // 处理搜索输入变化
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const keyword = e.target.value;
    setSearchParams(prev => ({ ...prev, keyword }));
    debouncedSearch(keyword);
  };

  // 处理搜索表单提交
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 处理分页
  const handlePageChange = (page: number, limit: number) => {
    setSearchParams(prev => ({ ...prev, page, limit }));
  };

  // 处理过滤条件变化
  const handleFilterChange = (newFilters: Partial<typeof filters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 重置所有过滤条件
  const resetFilters = () => {
    setFilters({
      isDisabled: undefined,
      roleIds: [],
      createdAt: undefined
    });
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 检查是否有活跃的过滤条件
  const hasActiveFilters = useMemo(() => {
    return filters.isDisabled !== undefined ||
           filters.roleIds.length > 0 ||
           filters.createdAt !== undefined;
  }, [filters]);


  // 打开创建用户对话框
  const handleCreateUser = () => {
    setEditingUser(null);
    setIsCreateForm(true);
    createForm.reset({
      username: '',
      nickname: null,
      email: null,
      phone: null,
      name: null,
      password: '',
      isDisabled: DisabledStatus.ENABLED,
    });
    setIsModalOpen(true);
  };

  // 打开编辑用户对话框
  const handleEditUser = (user: UserResponse) => {
    setEditingUser(user);
    setIsCreateForm(false);
    updateForm.reset({
      username: user.username,
      nickname: user.nickname,
      email: user.email,
      phone: user.phone,
      name: user.name,
      avatarFileId: user.avatarFileId,
      isDisabled: user.isDisabled,
    });
    setIsModalOpen(true);
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: CreateUserFormData) => {
    try {
      const res = await userClient.$post({
        json: data
      });
      if (res.status !== 201) {
        throw new Error('创建用户失败');
      }
      toast.success('用户创建成功');
      setIsModalOpen(false);
      refetch();
    } catch {
      toast.error('创建失败，请重试');
    }
  };

  // 处理更新表单提交
  const handleUpdateSubmit = async (data: UpdateUserFormData) => {
    if (!editingUser) return;
    
    try {
      const res = await userClient[':id']['$put']({
        param: { id: editingUser.id },
        json: data
      });
      if (res.status !== 200) {
        throw new Error('更新用户失败');
      }
      toast.success('用户更新成功');
      setIsModalOpen(false);
      refetch();
    } catch {
      toast.error('更新失败，请重试');
    }
  };

  // 处理删除用户
  const handleDeleteUser = (id: number) => {
    setUserToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!userToDelete) return;
    
    try {
      const res = await userClient[':id']['$delete']({
        param: { id: userToDelete }
      });
      if (res.status !== 204) {
        throw new Error('删除用户失败');
      }
      toast.success('用户删除成功');
      refetch();
    } catch {
      toast.error('删除失败，请重试');
    } finally {
      setDeleteDialogOpen(false);
      setUserToDelete(null);
    }
  };

  // 渲染表格部分的骨架屏
  const renderTableSkeleton = () => (
    <div className="space-y-2">
      {Array.from({ length: 5 }).map((_, index) => (
        <div key={index} className="flex space-x-4">
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 w-16" />
        </div>
      ))}
    </div>
  );

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">用户管理</h1>
        <Button onClick={handleCreateUser}>
          <Plus className="mr-2 h-4 w-4" />
          创建用户
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>用户列表</CardTitle>
          <CardDescription>
            管理系统中的所有用户，共 {totalCount} 位用户
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4 space-y-4">
            <form onSubmit={handleSearch} className="flex gap-2">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索用户名、昵称或邮箱..."
                  value={searchParams.keyword}
                  onChange={handleSearchChange}
                  className="pl-8"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center gap-2"
              >
                <Filter className="h-4 w-4" />
                高级筛选
                {hasActiveFilters && (
                  <Badge variant="secondary" className="ml-1">
                    {Object.values(filters).filter(v =>
                      v !== undefined &&
                      (!Array.isArray(v) || v.length > 0)
                    ).length}
                  </Badge>
                )}
              </Button>
              {hasActiveFilters && (
                <Button
                  type="button"
                  variant="ghost"
                  onClick={resetFilters}
                  className="flex items-center gap-2"
                >
                  <X className="h-4 w-4" />
                  重置
                </Button>
              )}
            </form>

            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 border rounded-lg bg-muted/50">
                {/* 状态筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">用户状态</label>
                  <Select
                    value={filters.isDisabled === undefined ? 'all' : filters.isDisabled.toString()}
                    onValueChange={(value) =>
                      handleFilterChange({
                        isDisabled: value === 'all' ? undefined : parseInt(value)
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部状态</SelectItem>
                      <SelectItem value="0">启用</SelectItem>
                      <SelectItem value="1">禁用</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 角色筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">用户角色</label>
                  <Select
                    value=""
                    onValueChange={(value) => {
                      const roleId = parseInt(value);
                      if (!filters.roleIds.includes(roleId)) {
                        handleFilterChange({
                          roleIds: [...filters.roleIds, roleId]
                        });
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择角色" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">管理员</SelectItem>
                      <SelectItem value="2">普通用户</SelectItem>
                    </SelectContent>
                  </Select>
                  {filters.roleIds.length > 0 && (
                    <div className="flex flex-wrap gap-2 mt-2">
                      {filters.roleIds.map(roleId => (
                        <Badge
                          key={roleId}
                          variant="secondary"
                          className="flex items-center gap-1"
                        >
                          {roleId === 1 ? '管理员' : '普通用户'}
                          <X
                            className="h-3 w-3 cursor-pointer"
                            onClick={() => handleFilterChange({
                              roleIds: filters.roleIds.filter(id => id !== roleId)
                            })}
                          />
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>

                {/* 创建时间筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">创建时间</label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        className={cn(
                          "w-full justify-start text-left font-normal",
                          !filters.createdAt && "text-muted-foreground"
                        )}
                      >
                        {filters.createdAt ?
                          `${filters.createdAt.gte || ''} 至 ${filters.createdAt.lte || ''}` :
                          '选择日期范围'
                        }
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <Calendar
                        mode="range"
                        selected={{
                          from: filters.createdAt?.gte ? new Date(filters.createdAt.gte) : undefined,
                          to: filters.createdAt?.lte ? new Date(filters.createdAt.lte) : undefined
                        }}
                        onSelect={(range) => {
                          handleFilterChange({
                            createdAt: range?.from && range?.to ? {
                              gte: format(range.from, 'yyyy-MM-dd'),
                              lte: format(range.to, 'yyyy-MM-dd')
                            } : undefined
                          });
                        }}
                        initialFocus
                      />
                    </PopoverContent>
                  </Popover>
                </div>
              </div>
            )}

            {/* 过滤条件标签 */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2">
                {filters.isDisabled !== undefined && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    状态: {filters.isDisabled === 0 ? '启用' : '禁用'}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ isDisabled: undefined })}
                    />
                  </Badge>
                )}
                {filters.roleIds.map(roleId => (
                  <Badge key={roleId} variant="secondary" className="flex items-center gap-1">
                    角色: {roleId === 1 ? '管理员' : '普通用户'}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({
                        roleIds: filters.roleIds.filter(id => id !== roleId)
                      })}
                    />
                  </Badge>
                ))}
                {filters.createdAt && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    创建时间: {filters.createdAt.gte || ''} 至 {filters.createdAt.lte || ''}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ createdAt: undefined })}
                    />
                  </Badge>
                )}
              </div>
            )}
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>头像</TableHead>
                  <TableHead>用户名</TableHead>
                  <TableHead>昵称</TableHead>
                  <TableHead>邮箱</TableHead>
                  <TableHead>真实姓名</TableHead>
                  <TableHead>角色</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  // 显示表格骨架屏
                  <TableRow>
                    <TableCell colSpan={8} className="p-4">
                      {renderTableSkeleton()}
                    </TableCell>
                  </TableRow>
                ) : (
                  // 显示实际用户数据
                  users.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>
                      <div className="w-10 h-10">
                        {user.avatarFile?.fullUrl ? (
                          <img
                            src={user.avatarFile.fullUrl}
                            alt={user.username}
                            className="w-10 h-10 rounded-full object-cover"
                          />
                        ) : (
                          <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                            <span className="text-sm font-medium text-gray-500">
                              {user.username?.charAt(0)?.toUpperCase() || 'U'}
                            </span>
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="font-medium">{user.username}</TableCell>
                      <TableCell>{user.nickname || '-'}</TableCell>
                      <TableCell>{user.email || '-'}</TableCell>
                      <TableCell>{user.name || '-'}</TableCell>
                      <TableCell>
                        <Badge
                          variant={user.roles?.some((role) => role.name === 'admin') ? 'destructive' : 'default'}
                          className="capitalize"
                        >
                          {user.roles?.some((role) => role.name === 'admin') ? '管理员' : '普通用户'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={user.isDisabled === 1 ? 'secondary' : 'default'}
                        >
                          {user.isDisabled === 1 ? '禁用' : '启用'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm')}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleEditUser(user)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleDeleteUser(user.id)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          <DataTablePagination
            currentPage={searchParams.page}
            totalCount={totalCount}
            pageSize={searchParams.limit}
            onPageChange={handlePageChange}
          />
        </CardContent>
      </Card>

      {/* 创建/编辑用户对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingUser ? '编辑用户' : '创建用户'}
            </DialogTitle>
            <DialogDescription>
              {editingUser ? '编辑现有用户信息' : '创建一个新的用户账户'}
            </DialogDescription>
          </DialogHeader>
          
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="username"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        用户名
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入用户名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="nickname"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>昵称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入昵称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>邮箱</FormLabel>
                      <FormControl>
                        <Input type="email" placeholder="请输入邮箱" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入手机号" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>真实姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入真实姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        密码
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input type="password" placeholder="请输入密码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="avatarFileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>头像</FormLabel>
                      <FormControl>
                        <AvatarSelector
                          value={field.value || undefined}
                          onChange={(value) => field.onChange(value)}
                          maxSize={2}
                          uploadPath="/avatars"
                          uploadButtonText="上传头像"
                          previewSize="medium"
                          placeholder="选择头像"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="isDisabled"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">用户状态</FormLabel>
                        <FormDescription>
                          禁用后用户将无法登录系统
                        </FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">
                    创建用户
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="username"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        用户名
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入用户名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="nickname"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>昵称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入昵称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>邮箱</FormLabel>
                      <FormControl>
                        <Input type="email" placeholder="请输入邮箱" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入手机号" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>真实姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入真实姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>新密码</FormLabel>
                      <FormControl>
                        <Input type="password" placeholder="留空则不修改密码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="avatarFileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>头像</FormLabel>
                      <FormControl>
                        <AvatarSelector
                          value={field.value || undefined}
                          onChange={(value) => field.onChange(value)}
                          maxSize={2}
                          uploadPath="/avatars"
                          uploadButtonText="上传头像"
                          previewSize="medium"
                          placeholder="选择头像"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="isDisabled"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">用户状态</FormLabel>
                        <FormDescription>
                          禁用后用户将无法登录系统
                        </FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 0)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">
                    更新用户
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* Avatar selector is now integrated within the form */}

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个用户吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};