import { useEffect, useState, useCallback } from 'react';
import {
  Table, Button, Modal, Form, Input, Select, Tag, Popconfirm, message, Space,
  Checkbox, Divider, Alert, Tooltip,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SafetyOutlined } from '@ant-design/icons';
import { userApi, type UserInfo } from '../api/modules';
import { usePermissions } from '../hooks/usePermissions';
import { getErrorMessage } from '../utils/error';

const ROLE_OPTIONS = [
  { value: 'super_admin', label: '超级管理员' },
  { value: 'operation', label: '运营' },
  { value: 'support', label: '客服' },
];

const ROLE_COLORS: Record<string, string> = {
  super_admin: 'red',
  operation: 'blue',
  support: 'green',
};

// 权限分组定义
const PERMISSION_GROUPS = [
  { label: '用户管理', prefix: 'user:' },
  { label: '账号管理', prefix: 'account:' },
  { label: '登录任务', prefix: 'login:' },
  { label: 'Cookie', prefix: 'cookie:' },
  { label: '代理 & 白名单', prefix: ['proxy:', 'whitelist:'] },
  { label: '系统', prefix: ['system:', 'audit:'] },
];

function isPrefixMatch(key: string, prefix: string | string[]): boolean {
  if (Array.isArray(prefix)) return prefix.some(p => key.startsWith(p));
  return key.startsWith(prefix);
}

export default function UsersPage() {
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<UserInfo | null>(null);
  const [form] = Form.useForm();
  const [pageSize, setPageSize] = useState(() => {
    const v = localStorage.getItem('user_page_size');
    return v ? Number(v) || 20 : 20;
  });
  const [currentPage, setCurrentPage] = useState(1);

  // 权限管理
  const [permModalOpen, setPermModalOpen] = useState(false);
  const [permUser, setPermUser] = useState<UserInfo | null>(null);
  const [permList, setPermList] = useState<Record<string, string>>({});
  const [rolePermMap, setRolePermMap] = useState<Record<string, string[]>>({});
  const [selectedPerms, setSelectedPerms] = useState<string[]>([]);
  const [useCustom, setUseCustom] = useState(false);
  const [permLoading, setPermLoading] = useState(false);
  const { can } = usePermissions();

  const canAssignPerm = can('user:assign_permissions');

  const loadUsers = useCallback(async () => {
    setLoading(true);
    try {
      const data = await userApi.list();
      setUsers(data);
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ role: 'support' });
    setModalOpen(true);
  };

  const handleEdit = (user: UserInfo) => {
    setEditing(user);
    form.setFieldsValue({
      username: user.username,
      role: user.role,
      remark: user.remark,
    });
    setModalOpen(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      if (editing) {
        const updateData: { role: string; remark: string; password?: string } = { role: values.role, remark: values.remark };
        if (values.password) updateData.password = values.password;
        await userApi.update(editing.id, updateData);
        message.success('已更新');
      } else {
        await userApi.create(values);
        message.success('已创建');
      }
      setModalOpen(false);
      loadUsers();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await userApi.delete(id);
      message.success('已删除');
      loadUsers();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    }
  };

  // ---- 权限管理 ----
  const handlePermClick = async (user: UserInfo) => {
    setPermUser(user);
    setPermModalOpen(true);
    setPermLoading(true);
    try {
      const data = await userApi.listPermissions();
      setPermList(data.permissions || {});
      setRolePermMap(data.role_permissions || {});
      // 初始化选中权限：如果用户有 custom_permissions 则使用，否则使用角色默认
      if (user.custom_permissions !== null && user.custom_permissions !== undefined) {
        setUseCustom(true);
        setSelectedPerms(user.custom_permissions);
      } else {
        setUseCustom(false);
        setSelectedPerms(data.role_permissions?.[user.role] || []);
      }
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    } finally {
      setPermLoading(false);
    }
  };

  const handlePermSave = async () => {
    if (!permUser) return;
    setPermLoading(true);
    try {
      await userApi.update(permUser.id, {
        custom_permissions: useCustom ? selectedPerms : null,
      });
      message.success('权限已更新');
      setPermModalOpen(false);
      loadUsers();
    } catch (e: unknown) {
      message.error(getErrorMessage(e));
    } finally {
      setPermLoading(false);
    }
  };

  const handleRoleChangeForPerm = (role: string) => {
    const rolePerms = rolePermMap[role] || [];
    setSelectedPerms(rolePerms);
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '用户名', dataIndex: 'username' },
    {
      title: '角色',
      dataIndex: 'role',
      render: (role: string) => {
        const label = ROLE_OPTIONS.find((r) => r.value === role)?.label || role;
        return <Tag color={ROLE_COLORS[role] || 'default'}>{label}</Tag>;
      },
    },
    {
      title: '权限模式',
      dataIndex: 'custom_permissions',
      width: 100,
      render: (_: unknown, record: UserInfo) =>
        record.custom_permissions !== null && record.custom_permissions !== undefined
          ? <Tag color="orange">自定义</Tag>
          : <Tag>角色默认</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 80,
      render: (active: boolean) => active ? <Tag color="green">启用</Tag> : <Tag>禁用</Tag>,
    },
    { title: '备注', dataIndex: 'remark', ellipsis: true },
    {
      title: '操作',
      width: 200,
      render: (_: unknown, record: UserInfo) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          {canAssignPerm && (
            <Tooltip title="权限管理">
              <Button size="small" icon={<SafetyOutlined />} onClick={() => handlePermClick(record)}>权限</Button>
            </Tooltip>
          )}
          {record.role !== 'super_admin' && (
            <Popconfirm title="确认删除？" onConfirm={() => handleDelete(record.id)}>
              <Button danger size="small" icon={<DeleteOutlined />}>删除</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h2>用户管理</h2>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>新建用户</Button>
      </div>
      <Table
        columns={columns}
        dataSource={users}
        rowKey="id"
        loading={loading}
        size="small"
        pagination={{
          current: currentPage,
          pageSize,
          showSizeChanger: true,
          showTotal: (t) => `共 ${t} 条`,
          onChange: (page, size) => {
            setCurrentPage(page);
            if (size !== pageSize) {
              setPageSize(size);
              localStorage.setItem('user_page_size', String(size));
              setCurrentPage(1); // 切换 pageSize 时重置到第1页
            }
          },
        }}
      />

      {/* 编辑/新建用户 Modal */}
      <Modal
        title={editing ? '编辑用户' : '新建用户'}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={handleSave}
        okText="保存"
      >
        <Form form={form} layout="vertical">
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input disabled={!!editing} />
          </Form.Item>
          <Form.Item
            name="password"
            label={editing ? '新密码（留空不修改）' : '密码'}
            rules={editing ? [] : [{ required: true, message: '请输入密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item name="role" label="角色" rules={[{ required: true }]}>
            <Select options={ROLE_OPTIONS} />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限管理 Modal */}
      <Modal
        title={permUser ? `权限管理 - ${permUser.username}` : '权限管理'}
        open={permModalOpen}
        onCancel={() => setPermModalOpen(false)}
        onOk={handlePermSave}
        okText="保存"
        width={640}
        confirmLoading={permLoading}
      >
        {permUser && (
          <>
            <Alert
              message={
                useCustom
                  ? '当前使用自定义权限，修改角色不会自动更新权限'
                  : '当前使用角色默认权限，修改角色后权限会自动跟随'
              }
              type={useCustom ? 'warning' : 'info'}
              showIcon
              style={{ marginBottom: 16 }}
            />
            <div style={{ marginBottom: 16 }}>
              <span>权限模式：</span>
              <Select
                value={useCustom ? 'custom' : 'role'}
                style={{ width: 140 }}
                onChange={(v) => {
                  if (v === 'role') {
                    setUseCustom(false);
                    setSelectedPerms(rolePermMap[permUser.role] || []);
                  } else {
                    setUseCustom(true);
                  }
                }}
                options={[
                  { value: 'role', label: '角色默认' },
                  { value: 'custom', label: '自定义' },
                ]}
              />
              {useCustom && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => handleRoleChangeForPerm(permUser.role)}
                >
                  重置为角色默认
                </Button>
              )}
            </div>
            <Checkbox.Group
              value={selectedPerms}
              onChange={(vals) => setSelectedPerms(vals as string[])}
              disabled={!useCustom}
            >
              {PERMISSION_GROUPS.map((group) => {
                const groupKeys = Object.keys(permList).filter(k => isPrefixMatch(k, group.prefix));
                if (groupKeys.length === 0) return null;
                return (
                  <div key={group.label} style={{ marginBottom: 12 }}>
                    <Divider style={{ margin: '8px 0 12px' }}>
                      {group.label}
                    </Divider>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 24px' }}>
                      {groupKeys.map(key => (
                        <Checkbox key={key} value={key}>
                          {permList[key]}
                        </Checkbox>
                      ))}
                    </div>
                  </div>
                );
              })}
            </Checkbox.Group>
          </>
        )}
      </Modal>
    </div>
  );
}
