import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import {
  Plus, 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/List/service';
import type { UserResponse, UserQuery, Role } from './types';
import type { DepartmentResponse } from '../../Department/List/types';
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 tableRef = useRef<PaginatedTableRef<UserResponse>>(null);
  const [stats, setStats] = useState({ total: 0, enabledCount: 0, disabledCount: 0 });
  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);

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: UserQuery) => {
    const result = await getUsers(query);
    const all = result.content || [];
    setStats({
      total: result.totalElements || 0,
      enabledCount: all.filter(d => d.enabled).length,
      disabledCount: all.filter(d => !d.enabled).length,
    });
    return result;
  };

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

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

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

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

  const handleSuccess = () => {
    setEditModalOpen(false);
    setEditRecord(undefined);
    tableRef.current?.refresh();
  };

  // 重置密码
  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}" 分配角色`,
      });
      tableRef.current?.refresh();
      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}" 已删除`,
      });
      tableRef.current?.refresh();
      setDeleteDialogOpen(false);
      setDeleteRecord(null);
    } catch (error) {
      console.error('删除失败:', error);
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'username', type: 'input', placeholder: '搜索用户名', width: 'w-[180px]' },
    { key: 'email', type: 'input', placeholder: '搜索邮箱', width: 'w-[180px]' },
    {
      key: 'enabled',
      type: 'select',
      placeholder: '状态',
      width: 'w-[120px]',
      options: [
        { label: '启用', value: 'true' },
        { label: '禁用', value: 'false' },
      ],
    },
  ], []);

  // 列定义
  const columns: ColumnDef<UserResponse>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'username', title: '用户名', dataIndex: 'username', width: '120px' },
    { key: 'nickname', title: '昵称', dataIndex: 'nickname', width: '120px' },
    { key: 'email', title: '邮箱', dataIndex: 'email', width: '200px' },
    { key: 'phone', title: '手机号', dataIndex: 'phone', width: '120px' },
    { key: 'departmentName', title: '部门', dataIndex: 'departmentName', width: '120px' },
    {
      key: 'roles',
      title: '角色',
      width: '150px',
      render: (_, record) => (
        <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>
      ),
    },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, record) => record.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>
      ),
    },
    {
      key: 'createTime',
      title: '创建时间',
      width: '180px',
      render: (_, record) => record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      key: 'actions',
      title: '操作',
      width: '200px',
      sticky: true,
      render: (_, record) => {
        const isAdmin = record.username === 'admin';
        return (
          <div className="flex 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>
        );
      },
    },
  ], []);

  // 工具栏
  const toolbar = (
    <Button onClick={handleCreate}>
      <Plus className="h-4 w-4 mr-2" />
      新增用户
    </Button>
  );

  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>
          <CardTitle>用户列表</CardTitle>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<UserResponse, UserQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1340px"
          />
        </CardContent>
      </Card>

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

      {/* 重置密码对话框 */}
      <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;
