import { PlusOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import {
  App,
  Avatar,
  Button,
  Checkbox,
  Col,
  Form,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useMemo, useState } from 'react';

import { initialUsers, roleOptions, type UserItem, type UserRole } from './mock';

interface UserFormValues {
  username: string;
  nickname: string;
  email: string;
  phone: string;
  roles: UserRole[];
  password?: string;
  enabled: boolean;
  remark?: string;
}

interface PasswordFormValues {
  password: string;
  confirmPassword: string;
  forceChange: boolean;
}

const roleColors: Record<UserRole, string> = {
  超级管理员: 'blue',
  运营: 'cyan',
  只读: 'default',
};

const maskPhone = (phone: string) => phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');

export default function UserManagement() {
  const { message } = App.useApp();
  const [userForm] = Form.useForm<UserFormValues>();
  const [passwordForm] = Form.useForm<PasswordFormValues>();
  const [users, setUsers] = useState(initialUsers);
  const [keyword, setKeyword] = useState('');
  const [role, setRole] = useState<UserRole>();
  const [enabled, setEnabled] = useState<boolean>();
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [editingUser, setEditingUser] = useState<UserItem>();
  const [formOpen, setFormOpen] = useState(false);
  const [resetUser, setResetUser] = useState<UserItem>();

  const filteredUsers = useMemo(() => {
    const normalizedKeyword = keyword.trim().toLowerCase();
    return users.filter(user => {
      const matchesKeyword =
        !normalizedKeyword ||
        user.username.toLowerCase().includes(normalizedKeyword) ||
        user.nickname.toLowerCase().includes(normalizedKeyword) ||
        user.email.toLowerCase().includes(normalizedKeyword) ||
        user.phone.includes(normalizedKeyword);

      return (
        matchesKeyword && (!role || user.roles.includes(role)) && (enabled === undefined || user.enabled === enabled)
      );
    });
  }, [enabled, keyword, role, users]);

  const closeUserForm = () => {
    setFormOpen(false);
    setEditingUser(undefined);
    userForm.resetFields();
  };

  const openCreate = () => {
    setEditingUser(undefined);
    userForm.setFieldsValue({
      username: '',
      nickname: '',
      email: '',
      phone: '',
      roles: ['只读'],
      password: '',
      enabled: true,
      remark: '',
    });
    setFormOpen(true);
  };

  const openEdit = (user: UserItem) => {
    setEditingUser(user);
    userForm.setFieldsValue({ ...user, password: '' });
    setFormOpen(true);
  };

  const saveUser = async () => {
    const values = await userForm.validateFields();

    if (editingUser) {
      setUsers(current =>
        current.map(user =>
          user.id === editingUser.id
            ? {
                ...user,
                nickname: values.nickname,
                email: values.email,
                phone: values.phone,
                roles: values.roles,
                enabled: values.enabled,
                remark: values.remark,
              }
            : user,
        ),
      );
      message.success('用户已更新');
    } else {
      setUsers(current => [
        ...current,
        {
          id: `user-${Date.now()}`,
          username: values.username,
          nickname: values.nickname,
          email: values.email,
          phone: values.phone,
          roles: values.roles,
          enabled: values.enabled,
          remark: values.remark,
          lastLoginAt: '从未登录',
          createdAt: '2026-07-26',
        },
      ]);
      message.success('用户已添加');
    }

    closeUserForm();
  };

  const deleteUser = (user: UserItem) => {
    setUsers(current => current.filter(item => item.id !== user.id));
    setSelectedKeys(current => current.filter(key => key !== user.id));
    message.success('用户已删除');
  };

  const batchDisable = () => {
    setUsers(current => current.map(user => (selectedKeys.includes(user.id) ? { ...user, enabled: false } : user)));
    message.success(`已禁用 ${selectedKeys.length} 个用户`);
    setSelectedKeys([]);
  };

  const openResetPassword = (user: UserItem) => {
    setResetUser(user);
    passwordForm.setFieldsValue({ password: '', confirmPassword: '', forceChange: true });
  };

  const resetPassword = async () => {
    await passwordForm.validateFields();
    message.success('密码已重置');
    setResetUser(undefined);
    passwordForm.resetFields();
  };

  const columns: ColumnsType<UserItem> = [
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      render: (value: string) => (
        <Space>
          <Avatar size="small" icon={<UserOutlined />} />
          <Typography.Text strong style={{ whiteSpace: 'nowrap' }}>
            {value}
          </Typography.Text>
        </Space>
      ),
    },
    { title: '昵称', dataIndex: 'nickname', width: 70, ellipsis: true },
    { title: '邮箱', dataIndex: 'email', width: 150, ellipsis: true },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 110,
      render: (value: string) => <span style={{ whiteSpace: 'nowrap' }}>{maskPhone(value)}</span>,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      width: 100,
      render: (roles: UserRole[]) => (
        <Space size={[0, 4]} wrap>
          {roles.map(item => (
            <Tag key={item} color={roleColors[item]}>
              {item}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      width: 65,
      render: (value: boolean, user) => (
        <Switch
          size="small"
          checked={value}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          aria-label={`${user.username}状态`}
          onChange={checked => {
            setUsers(current => current.map(item => (item.id === user.id ? { ...item, enabled: checked } : item)));
            message.success(checked ? '用户已启用' : '用户已禁用');
          }}
        />
      ),
    },
    {
      title: '最近登录',
      dataIndex: 'lastLoginAt',
      width: 150,
      render: (value: string) => <span style={{ whiteSpace: 'nowrap' }}>{value}</span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 100,
      render: (value: string) => <span style={{ whiteSpace: 'nowrap' }}>{value}</span>,
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render: (_, user) => (
        <Space size={2}>
          <Button type="link" size="small" onClick={() => openEdit(user)}>
            编辑
          </Button>
          <Button type="link" size="small" onClick={() => openResetPassword(user)}>
            重置密码
          </Button>
          <Popconfirm title={`确定删除用户 ${user.username}？`} onConfirm={() => deleteUser(user)}>
            <Button type="link" danger size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <ProCard variant="outlined">
        <Space vertical size={16} style={{ width: '100%' }}>
          <div>
            <Typography.Title level={5} style={{ margin: 0 }}>
              用户管理
            </Typography.Title>
            <Typography.Text type="secondary">管理系统用户账号、角色绑定与启用状态。</Typography.Text>
          </div>

          <Row gutter={[12, 12]} justify="space-between">
            <Col flex="auto">
              <Space wrap>
                <Input
                  allowClear
                  prefix={<SearchOutlined />}
                  placeholder="搜索用户名 / 邮箱 / 手机号"
                  style={{ width: 260 }}
                  value={keyword}
                  onChange={event => setKeyword(event.target.value)}
                />
                <Select
                  allowClear
                  placeholder="全部角色"
                  style={{ width: 140 }}
                  options={roleOptions.map(value => ({ label: value, value }))}
                  value={role}
                  onChange={setRole}
                />
                <Select
                  allowClear
                  placeholder="全部状态"
                  style={{ width: 130 }}
                  options={[
                    { label: '已启用', value: true },
                    { label: '已禁用', value: false },
                  ]}
                  value={enabled}
                  onChange={setEnabled}
                />
              </Space>
            </Col>
            <Col>
              <Space>
                <Popconfirm
                  title={`确定禁用选中的 ${selectedKeys.length} 个用户？`}
                  disabled={!selectedKeys.length}
                  onConfirm={batchDisable}
                >
                  <Button disabled={!selectedKeys.length}>批量禁用</Button>
                </Popconfirm>
                <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
                  新增用户
                </Button>
              </Space>
            </Col>
          </Row>

          <Table<UserItem>
            rowKey="id"
            columns={columns}
            dataSource={filteredUsers}
            rowSelection={{ selectedRowKeys: selectedKeys, onChange: setSelectedKeys }}
            scroll={{ x: 1045 }}
            pagination={{ pageSize: 10, showSizeChanger: true, showTotal: total => `共 ${total} 条` }}
          />
        </Space>
      </ProCard>

      <Modal
        open={formOpen}
        title={editingUser ? '编辑用户' : '新增用户'}
        okText="保存"
        cancelText="取消"
        width={640}
        onOk={saveUser}
        onCancel={closeUserForm}
      >
        <Form<UserFormValues> form={userForm} layout="vertical" requiredMark="optional">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input disabled={Boolean(editingUser)} placeholder="登录账号，创建后不可修改" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="昵称" name="nickname" rules={[{ required: true, message: '请输入昵称' }]}>
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效邮箱' },
                ]}
              >
                <Input placeholder="name@example.com" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1\d{10}$/, message: '请输入 11 位手机号' },
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="角色" name="roles" rules={[{ required: true, message: '请选择角色' }]}>
                <Select
                  mode="multiple"
                  placeholder="请选择角色"
                  options={roleOptions.map(value => ({ label: value, value }))}
                />
              </Form.Item>
            </Col>
            {!editingUser && (
              <Col span={12}>
                <Form.Item
                  label="初始密码"
                  name="password"
                  extra="首次登录后建议修改"
                  rules={[
                    { required: true, message: '请输入初始密码' },
                    { min: 8, message: '密码至少 8 位' },
                  ]}
                >
                  <Input.Password placeholder="请输入初始密码" />
                </Form.Item>
              </Col>
            )}
            <Col span={12}>
              <Form.Item label="状态" name="enabled" valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item label="备注" name="remark">
                <Input.TextArea rows={2} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        open={Boolean(resetUser)}
        title={`重置密码 - ${resetUser?.username ?? ''}`}
        okText="确认重置"
        cancelText="取消"
        onOk={resetPassword}
        onCancel={() => {
          setResetUser(undefined);
          passwordForm.resetFields();
        }}
      >
        <Typography.Paragraph type="secondary">
          重置后将生成新的临时密码，用户下次登录时可按策略修改。
        </Typography.Paragraph>
        <Form<PasswordFormValues> form={passwordForm} layout="vertical">
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 8, message: '密码至少 8 位' },
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请再次输入密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  return !value || getFieldValue('password') === value
                    ? Promise.resolve()
                    : Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入密码" />
          </Form.Item>
          <Form.Item name="forceChange" valuePropName="checked">
            <Checkbox>重置后强制用户修改密码</Checkbox>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
