import React, { useState, useEffect, useMemo } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DataTablePagination } from '@/components/ui/pagination';
import {
  Loader2, Plus, Search, Edit, Trash2, KeyRound, Users as UsersIcon,
  UserCheck, UserX, Activity
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { getUsers, deleteUser, resetPassword, assignRoles, getAllRoles } from './service';
import { getDepartmentTree } from '../Department/service';
import type { UserResponse, UserQuery, Role } from './types';
import type { DepartmentResponse } from '../Department/types';
import type { Page } from '@/types/base';
import { DEFAULT_PAGE_SIZE, DEFAULT_CURRENT } from '@/utils/page';
import EditModal from './components/EditModal';
import ResetPasswordDialog from './components/ResetPasswordDialog';
import AssignRolesDialog from './components/AssignRolesDialog';
import DeleteDialog from './components/DeleteDialog';
import dayjs from 'dayjs';

/**
 * 用户管理页面
 */
const UserPage: React.FC = () => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Page<UserResponse> | null>(null);
  const [departments, setDepartments] = useState<DepartmentResponse[]>([]);
  const [allRoles, setAllRoles] = useState<Role[]>([]);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<UserResponse>();
  const [resetPasswordDialogOpen, setResetPasswordDialogOpen] = useState(false);
  const [resetPasswordRecord, setResetPasswordRecord] = useState<UserResponse | null>(null);
  const [assignRolesDialogOpen, setAssignRolesDialogOpen] = useState(false);
  const [assignRolesRecord, setAssignRolesRecord] = useState<UserResponse | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteRecord, setDeleteRecord] = useState<UserResponse | null>(null);
  const [query, setQuery] = useState<UserQuery>({
    pageNum: DEFAULT_CURRENT - 1,
    pageSize: DEFAULT_PAGE_SIZE,
    username: '',
    email: '',
    enabled: undefined,
  });

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const result = await getUsers(query);
      setData(result);
    } catch (error) {
      console.error('加载用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 加载部门和角色
  const loadDepartmentsAndRoles = async () => {
    try {
      const [deptData, roleData] = await Promise.all([
        getDepartmentTree(),
        getAllRoles()
      ]);
      setDepartments(deptData);
      setAllRoles(roleData);
    } catch (error) {
      console.error('加载部门和角色失败:', error);
    }
  };

  useEffect(() => {
    loadDepartmentsAndRoles();
  }, []);

  useEffect(() => {
    loadData();
  }, [query]);

  // 搜索
  const handleSearch = () => {
    setQuery(prev => ({ ...prev, pageNum: 0 }));
  };

  // 重置
  const handleReset = () => {
    setQuery({
      pageNum: 0,
      pageSize: DEFAULT_PAGE_SIZE,
      username: '',
      email: '',
      enabled: undefined,
    });
  };

  // 新建
  const handleCreate = () => {
    setEditRecord(undefined);
    setEditModalOpen(true);
  };

  // 编辑
  const handleEdit = (record: UserResponse) => {
    setEditRecord(record);
    setEditModalOpen(true);
  };

  // 重置密码
  const handleResetPassword = (record: UserResponse) => {
    setResetPasswordRecord(record);
    setResetPasswordDialogOpen(true);
  };

  const confirmResetPassword = async (password: string) => {
    if (!resetPasswordRecord) return;
    try {
      await resetPassword(resetPasswordRecord.id, password);
      toast({
        title: '重置成功',
        description: `用户 "${resetPasswordRecord.username}" 的密码已重置`,
      });
      setResetPasswordDialogOpen(false);
      setResetPasswordRecord(null);
    } catch (error) {
      console.error('重置密码失败:', error);
      toast({
        title: '重置失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 分配角色
  const handleAssignRoles = (record: UserResponse) => {
    setAssignRolesRecord(record);
    setAssignRolesDialogOpen(true);
  };

  const confirmAssignRoles = async (roleIds: number[]) => {
    if (!assignRolesRecord) return;
    try {
      await assignRoles(assignRolesRecord.id, roleIds);
      toast({
        title: '分配成功',
        description: `已为用户 "${assignRolesRecord.username}" 分配角色`,
      });
      loadData();
      setAssignRolesDialogOpen(false);
      setAssignRolesRecord(null);
    } catch (error) {
      console.error('分配角色失败:', error);
      toast({
        title: '分配失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 删除
  const handleDelete = (record: UserResponse) => {
    setDeleteRecord(record);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!deleteRecord) return;
    try {
      await deleteUser(deleteRecord.id);
      toast({
        title: '删除成功',
        description: `用户 "${deleteRecord.username}" 已删除`,
      });
      loadData();
      setDeleteDialogOpen(false);
      setDeleteRecord(null);
    } catch (error) {
      console.error('删除失败:', error);
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 状态徽章
  const getStatusBadge = (enabled: boolean) => {
    return enabled ? (
      <Badge variant="success" className="inline-flex items-center gap-1">
        <UserCheck className="h-3 w-3" />
        启用
      </Badge>
    ) : (
      <Badge variant="secondary" className="inline-flex items-center gap-1">
        <UserX className="h-3 w-3" />
        禁用
      </Badge>
    );
  };

  // 统计数据
  const stats = useMemo(() => {
    const total = data?.totalElements || 0;
    const enabledCount = data?.content?.filter(d => d.enabled).length || 0;
    const disabledCount = data?.content?.filter(d => !d.enabled).length || 0;
    return { total, enabledCount, disabledCount };
  }, [data]);

  const pageCount = data?.totalElements ? Math.ceil(data.totalElements / (query.pageSize || DEFAULT_PAGE_SIZE)) : 0;

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-foreground">用户管理</h1>
        <p className="text-muted-foreground mt-2">
          管理系统用户账号，设置权限和角色。
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        <Card className="bg-gradient-to-br from-blue-500/10 to-blue-500/5 border-blue-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-blue-700">总用户数</CardTitle>
            <Activity className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground mt-1">所有系统用户</p>
          </CardContent>
        </Card>
        <Card className="bg-gradient-to-br from-green-500/10 to-green-500/5 border-green-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-green-700">启用用户</CardTitle>
            <UserCheck className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.enabledCount}</div>
            <p className="text-xs text-muted-foreground mt-1">可正常登录的用户</p>
          </CardContent>
        </Card>
        <Card className="bg-gradient-to-br from-gray-500/10 to-gray-500/5 border-gray-500/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-gray-700">禁用用户</CardTitle>
            <UserX className="h-4 w-4 text-gray-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.disabledCount}</div>
            <p className="text-xs text-muted-foreground mt-1">已停用的用户</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>用户列表</CardTitle>
          <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            新增用户
          </Button>
        </CardHeader>
        <CardContent>
          {/* 搜索栏 */}
          <div className="flex flex-wrap items-center gap-4 mb-4">
            <div className="flex-1 max-w-xs">
              <Input
                placeholder="搜索用户名"
                value={query.username}
                onChange={(e) => setQuery(prev => ({ ...prev, username: e.target.value }))}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-9"
              />
            </div>
            <div className="flex-1 max-w-xs">
              <Input
                placeholder="搜索邮箱"
                value={query.email}
                onChange={(e) => setQuery(prev => ({ ...prev, email: e.target.value }))}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-9"
              />
            </div>
            <Select
              value={query.enabled === undefined ? 'all' : query.enabled ? 'true' : 'false'}
              onValueChange={(value) => setQuery(prev => ({
                ...prev,
                enabled: value === 'all' ? undefined : value === 'true'
              }))}
            >
              <SelectTrigger className="w-[130px] h-9">
                <SelectValue placeholder="全部状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="true">启用</SelectItem>
                <SelectItem value="false">禁用</SelectItem>
              </SelectContent>
            </Select>
            <Button onClick={handleSearch} className="h-9">
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
            <Button variant="outline" onClick={handleReset} className="h-9">
              重置
            </Button>
          </div>

          {/* 表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[120px]">用户名</TableHead>
                  <TableHead className="w-[150px]">昵称</TableHead>
                  <TableHead className="w-[200px]">邮箱</TableHead>
                  <TableHead className="w-[120px]">手机号</TableHead>
                  <TableHead className="w-[120px]">部门</TableHead>
                  <TableHead className="w-[150px]">角色</TableHead>
                  <TableHead className="w-[100px]">状态</TableHead>
                  <TableHead className="w-[180px]">创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={9} className="h-24 text-center">
                      <div className="flex items-center justify-center">
                        <Loader2 className="h-6 w-6 animate-spin mr-2" />
                        <span className="text-sm text-muted-foreground">加载中...</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : data?.content && data.content.length > 0 ? (
                  data.content.map((record) => {
                    const isAdmin = record.username === 'admin';
                    return (
                      <TableRow key={record.id} className="hover:bg-muted/50">
                        <TableCell className="font-medium">
                          {record.username}
                        </TableCell>
                        <TableCell>{record.nickname || '-'}</TableCell>
                        <TableCell className="text-sm">{record.email || '-'}</TableCell>
                        <TableCell className="text-sm">{record.phone || '-'}</TableCell>
                        <TableCell>{record.departmentName || '-'}</TableCell>
                        <TableCell>
                          <div className="flex flex-wrap gap-1">
                            {record.roles && record.roles.length > 0 ? (
                              record.roles.map(role => (
                                <Badge key={role.id} variant="outline" className="text-xs">
                                  {role.name}
                                </Badge>
                              ))
                            ) : (
                              <span className="text-muted-foreground">-</span>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>{getStatusBadge(record.enabled)}</TableCell>
                        <TableCell className="text-sm">
                          {record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm') : '-'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(record)}
                              title="编辑"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleResetPassword(record)}
                              title="重置密码"
                              className="text-orange-600 hover:text-orange-700 hover:bg-orange-50"
                            >
                              <KeyRound className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleAssignRoles(record)}
                              title="分配角色"
                              className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                              disabled={isAdmin}
                            >
                              <UsersIcon className="h-4 w-4" />
                            </Button>
                            {!isAdmin && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleDelete(record)}
                                className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                title="删除"
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                ) : (
                  <TableRow>
                    <TableCell colSpan={9} className="h-24 text-center">
                      <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                        <UsersIcon className="w-16 h-16 mb-4 text-muted-foreground/50" />
                        <div className="text-lg font-semibold mb-2">暂无用户数据</div>
                        <div className="text-sm">点击右上角"新增用户"开始创建用户。</div>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          {/* 分页 */}
          {pageCount > 1 && (
            <DataTablePagination
              pageIndex={(query.pageNum || 0) + 1}
              pageSize={query.pageSize || DEFAULT_PAGE_SIZE}
              pageCount={pageCount}
              onPageChange={(page) => setQuery(prev => ({
                ...prev,
                pageNum: page - 1
              }))}
            />
          )}
        </CardContent>
      </Card>

      {/* 编辑弹窗 */}
      <EditModal
        open={editModalOpen}
        record={editRecord}
        departments={departments}
        onOpenChange={setEditModalOpen}
        onSuccess={loadData}
      />

      {/* 重置密码对话框 */}
      <ResetPasswordDialog
        open={resetPasswordDialogOpen}
        record={resetPasswordRecord}
        onOpenChange={setResetPasswordDialogOpen}
        onConfirm={confirmResetPassword}
      />

      {/* 分配角色对话框 */}
      <AssignRolesDialog
        open={assignRolesDialogOpen}
        record={assignRolesRecord}
        allRoles={allRoles}
        onOpenChange={setAssignRolesDialogOpen}
        onConfirm={confirmAssignRoles}
      />

      {/* 删除确认对话框 */}
      <DeleteDialog
        open={deleteDialogOpen}
        record={deleteRecord}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={confirmDelete}
      />
    </div>
  );
};

export default UserPage;
