import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Plus, Search, Edit, Trash2, Eye, Calendar, UserCheck, UserX } from 'lucide-react';

import { userClient } from '@/client/api';
import type { InferResponseType, InferRequestType } from 'hono/client';
import { UserType } from '@/server/modules/users/user.enum';
import { CreateUserDto, UpdateUserDto } from '@/server/modules/users/user.schema';

import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Badge } from '@/client/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { Skeleton } from '@/client/components/ui/skeleton';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';

import { DataTablePagination } from '@/client/admin/components/DataTablePagination';

type UserListResponse = InferResponseType<typeof userClient.$get, 200>;
type UserDetailResponse = InferResponseType<typeof userClient[':id']['$get'], 200>;
type CreateUserRequest = InferRequestType<typeof userClient.$post>['json'];
type UpdateUserRequest = InferRequestType<typeof userClient[':id']['$put']>['json'];

// 创建表单schema
const createFormSchema = CreateUserDto;
const updateFormSchema = UpdateUserDto;

// 用户管理页面
export const UsersPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: ''
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [editingUser, setEditingUser] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<number | null>(null);
  const [traineeDialogOpen, setTraineeDialogOpen] = useState(false);
  const [selectedUser, setSelectedUser] = useState<any>(null);
  const [traineeValidFrom, setTraineeValidFrom] = useState<string>('');
  const [traineeValidTo, setTraineeValidTo] = useState<string>('');

  // 创建表单
  const createForm = useForm<CreateUserRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      username: '',
      password: '',
      email: null,
      phone: null,
      nickname: null,
      name: null,
      userType: UserType.STUDENT,
      isDisabled: 0
    }
  });

  // 更新表单
  const updateForm = useForm<UpdateUserRequest>({
    resolver: zodResolver(updateFormSchema),
    defaultValues: {
      username: '',
      email: null,
      phone: null,
      nickname: null,
      name: null,
      userType: UserType.STUDENT,
      isDisabled: 0
    }
  });

  // 获取用户列表
  const { data: usersData, isLoading, refetch } = useQuery({
    queryKey: ['users', searchParams],
    queryFn: async () => {
      const res = await userClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search
        }
      });
      if (res.status !== 200) {
        throw new Error('获取用户列表失败');
      }
      return await res.json();
    }
  });

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

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

  // 打开创建用户对话框
  const showCreateModal = () => {
    setIsCreateForm(true);
    setEditingUser(null);
    createForm.reset();
    setIsModalOpen(true);
  };

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

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

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

  // 打开删除确认对话框
  const showDeleteDialog = (userId: number) => {
    setUserToDelete(userId);
    setDeleteDialogOpen(true);
  };

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

  // 打开设置学员对话框
  const showSetTraineeDialog = (user: any) => {
    setSelectedUser(user);
    setTraineeValidFrom(user.traineeValidFrom ? new Date(user.traineeValidFrom).toISOString().split('T')[0] : '');
    setTraineeValidTo(user.traineeValidTo ? new Date(user.traineeValidTo).toISOString().split('T')[0] : '');
    setTraineeDialogOpen(true);
  };

  // 打开撤销学员对话框
  const showRemoveTraineeDialog = (user: any) => {
    setSelectedUser(user);
    setTraineeDialogOpen(true);
  };

  // 处理设置学员
  const handleSetTrainee = async () => {
    if (!selectedUser || !traineeValidFrom || !traineeValidTo) return;
    
    try {
      const validFrom = new Date(traineeValidFrom);
      const validTo = new Date(traineeValidTo);
      
      if (validFrom >= validTo) {
        toast.error('有效期结束时间必须晚于开始时间');
        return;
      }

      const res = await userClient[':id']['$put']({
        param: { id: selectedUser.id.toString() },
        json: {
          userType: UserType.TRAINEE,
          traineeValidFrom: validFrom.toISOString(),
          traineeValidTo: validTo.toISOString()
        }
      });
      
      if (res.status !== 200) {
        throw new Error('设置学员失败');
      }
      
      toast.success('设置学员成功');
      setTraineeDialogOpen(false);
      setSelectedUser(null);
      setTraineeValidFrom('');
      setTraineeValidTo('');
      refetch();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '设置失败，请重试');
    }
  };

  // 处理撤销学员
  const handleRemoveTrainee = async () => {
    if (!selectedUser) return;
    
    try {
      const res = await userClient[':id']['$put']({
        param: { id: selectedUser.id.toString() },
        json: {
          userType: UserType.STUDENT,
          traineeValidFrom: null,
          traineeValidTo: null
        }
      });
      
      if (res.status !== 200) {
        throw new Error('撤销学员失败');
      }
      
      toast.success('撤销学员成功');
      setTraineeDialogOpen(false);
      setSelectedUser(null);
      refetch();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '撤销失败，请重试');
    }
  };


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

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>用户列表</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="flex gap-2 mb-4">
            <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.search}
                onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                className="pl-8"
              />
            </div>
            <Button type="submit" variant="outline">
              搜索
            </Button>
          </form>

          {/* 用户表格 */}
          <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>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  // 加载状态 - 表格骨架屏
                  [...Array(5)].map((_, index) => (
                    <TableRow key={index}>
                      <TableCell><Skeleton className="w-8 h-8 rounded-full" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-16" /></TableCell>
                      <TableCell><Skeleton className="h-6 w-12" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell><Skeleton className="h-6 w-10" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Skeleton className="h-8 w-8 rounded-md" />
                          <Skeleton className="h-8 w-8 rounded-md" />
                          <Skeleton className="h-8 w-8 rounded-md" />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : users.length > 0 ? (
                  // 正常数据展示
                  users.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>
                        {user.avatarFile?.fullUrl ? (
                          <img
                            src={user.avatarFile.fullUrl}
                            alt={user.nickname || user.username}
                            className="w-8 h-8 rounded-full object-cover"
                          />
                        ) : (
                          <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-xs text-gray-500">
                            {user.nickname ? user.nickname.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase()}
                          </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.userType === UserType.TEACHER ? 'default' :
                            user.userType === UserType.STUDENT ? 'secondary' : 'outline'
                          }
                          className={
                            user.userType === UserType.TEACHER ? 'bg-blue-100 text-blue-800' :
                            user.userType === UserType.STUDENT ? 'bg-green-100 text-green-800' :
                            'bg-purple-100 text-purple-800'
                          }
                        >
                          {user.userType === UserType.TEACHER ? '老师' :
                           user.userType === UserType.STUDENT ? '学生' : '学员'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {user.userType === 'trainee' && user.traineeValidFrom && user.traineeValidTo ? (
                          <div className="text-sm">
                            <div>{format(new Date(user.traineeValidFrom), 'yyyy-MM-dd')}</div>
                            <div>至</div>
                            <div>{format(new Date(user.traineeValidTo), 'yyyy-MM-dd')}</div>
                          </div>
                        ) : '-'}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={user.isDisabled === 0 ? 'default' : 'destructive'}
                          className={user.isDisabled === 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
                        >
                          {user.isDisabled === 0 ? '启用' : '禁用'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {user.createdAt ? format(new Date(user.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN }) : '-'}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          {user.userType === 'trainee' ? (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => showRemoveTraineeDialog(user)}
                              className="text-purple-600 hover:text-purple-800"
                              title="撤销学员身份"
                            >
                              <UserX className="h-4 w-4" />
                            </Button>
                          ) : (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => showSetTraineeDialog(user)}
                              className="text-purple-600 hover:text-purple-800"
                              title="设置为学员"
                            >
                              <UserCheck className="h-4 w-4" />
                            </Button>
                          )}
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => showEditModal(user)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => showDeleteDialog(user.id)}
                            className="text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  // 空数据状态
                  <TableRow>
                    <TableCell colSpan={10} className="h-24 text-center">
                      <p className="text-muted-foreground">暂无数据</p>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页 */}
          <DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={totalCount}
            onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
          />
        </CardContent>
      </Card>

      {/* 创建/编辑用户对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isCreateForm ? '创建用户' : '编辑用户'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的用户账户' : '编辑现有用户信息'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="username"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>用户名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入用户名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>密码</FormLabel>
                      <FormControl>
                        <Input type="password" 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 type="tel" 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="userType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>用户类型</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择用户类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={UserType.TEACHER}>老师</SelectItem>
                          <SelectItem value={UserType.STUDENT}>学生</SelectItem>
                          <SelectItem value={UserType.TRAINEE}>学员</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="isDisabled"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <Select onValueChange={(value) => field.onChange(parseInt(value))} defaultValue={field.value?.toString()}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择状态" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="0">启用</SelectItem>
                          <SelectItem value="1">禁用</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </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>用户名</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 type="tel" 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="userType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>用户类型</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择用户类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={UserType.TEACHER}>老师</SelectItem>
                          <SelectItem value={UserType.STUDENT}>学生</SelectItem>
                          <SelectItem value={UserType.TRAINEE}>学员</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="isDisabled"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <Select onValueChange={(value) => field.onChange(parseInt(value))} defaultValue={field.value?.toString()}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择状态" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="0">启用</SelectItem>
                          <SelectItem value="1">禁用</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这个用户吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 学员设置对话框 */}
      <Dialog open={traineeDialogOpen} onOpenChange={setTraineeDialogOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>
              {selectedUser?.userType === 'trainee' ? '撤销学员身份' : '设置为学员'}
            </DialogTitle>
            <DialogDescription>
              {selectedUser?.userType === 'trainee'
                ? '确定要撤销该用户的学员身份吗？'
                : '请设置学员的有效期'}
            </DialogDescription>
          </DialogHeader>

          {selectedUser?.userType !== 'trainee' && (
            <div className="space-y-4">
              <div>
                <label className="text-sm font-medium">有效期开始时间</label>
                <Input
                  type="date"
                  value={traineeValidFrom}
                  onChange={(e) => setTraineeValidFrom(e.target.value)}
                  className="mt-1"
                />
              </div>
              <div>
                <label className="text-sm font-medium">有效期结束时间</label>
                <Input
                  type="date"
                  value={traineeValidTo}
                  onChange={(e) => setTraineeValidTo(e.target.value)}
                  className="mt-1"
                />
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setTraineeDialogOpen(false)}>
              取消
            </Button>
            <Button
              onClick={selectedUser?.userType === 'trainee' ? handleRemoveTrainee : handleSetTrainee}
              className={selectedUser?.userType === 'trainee' ? 'bg-red-600 hover:bg-red-700' : ''}
            >
              {selectedUser?.userType === 'trainee' ? '撤销学员' : '设置为学员'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};