/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomTree from '@/pages/components/customTree';
import { deleteUser } from '@/services/userList';
import { DeleteOutlined, PlusOutlined, TeamOutlined } from '@ant-design/icons';
import { Button, Input, Popconfirm, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import { OrganizationNode, User } from './contast';
import styles from './index.less';
import UserEditModal from './mod/eidtUser';
import CreatGroup from './mod/group';
import PasswordResetModal from './mod/passwordEdit';

const UserListPage: React.FC = () => {
  const [orgTreeData, setOrgTreeData] = useState<OrganizationNode[]>([]);
  const [selectedOrg, setSelectedOrg] = useState<string>('');

  // 用户列表
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<[]>([]);

  // 分页参数
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [totalUsers, setTotalUsers] = useState<number>(0);
  // 编辑用户
  const [currentUserInfo, setCurrentUserInfo] = useState<any>({
    visible: false,
  });
  // 重置密码
  const [eidtPassword, setEidtPassword] = useState<any>({
    visible: false,
  });

  // 添加分组
  const [visible, setVisible] = useState<boolean>(false);

  // 获取用户分组组织树
  useEffect(() => {
    getUserGroupList();
  }, []);

  // 获取用户列表数据
  useEffect(() => {
    getUserListInit();
  }, [selectedOrg, currentPage, pageSize]);

  const getUserGroupList = () => {
    const mockOrgData: OrganizationNode[] = [
      {
        name: 'Headquarters',
        id: '1',
        children: [
          {
            name: 'HR Department',
            id: '2',
          },
          {
            name: 'IT Department',
            id: '3',
            children: [
              {
                name: 'Frontend Team',
                id: '4',
              },
              {
                name: 'Backend Team',
                id: '5',
              },
            ],
          },
          {
            name: 'Finance Department',
            id: '6',
          },
        ],
      },
    ];
    setSelectedOrg(mockOrgData[0].id as string);
    setOrgTreeData(mockOrgData);
  };

  const getUserListInit = () => {
    setLoading(true);
    setTimeout(() => {
      const startIndex = (currentPage - 1) * pageSize;
      const mockUsers: User[] = Array.from(
        { length: pageSize },
        (_, index) => ({
          id: `${startIndex + index + 1}`,
          username: `User ${startIndex + index + 1}`,
          loginName: `login${startIndex + index + 1}`,
          userGroup:
            index % 3 === 0 ? 'Admin' : index % 3 === 1 ? 'Manager' : 'User',
          userType:
            index % 4 === 0
              ? 'Full-time'
              : index % 4 === 1
              ? 'Part-time'
              : index % 4 === 2
              ? 'Contractor'
              : 'Intern',
        }),
      );

      setUsers(mockUsers);
      setTotalUsers(100);
      setLoading(false);
    }, 300);
  };

  const onDelete = (user?: User) => {
    const { user_id } = user || {};
    const payload = {
      ids: user_id ? [user_id] : selectedRowKeys,
    };
    deleteUser(payload as any).then((res) => {
      console.log('res=====', res);
      const { success } = res || {};
      if (success) {
        message.success('删除成功');
        setSelectedRowKeys([]);
        getUserListInit();
      }
    });
  };

  const handlePassword = (user: User) => {
    setEidtPassword({
      recordData: { ...user },
      visible: true,
    });
  };

  const handleCreatUserInfo = () => {
    setCurrentUserInfo({
      visible: true,
    });
  };

  const handleEditUserInfo = (user: User) => {
    setCurrentUserInfo({
      recordData: { ...user },
      visible: true,
    });
  };

  const columns: ColumnsType<User> = [
    {
      title: '登录名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '用户姓名',
      dataIndex: 'loginName',
      key: 'loginName',
    },
    {
      title: '用户分组',
      dataIndex: 'userGroup',
      key: 'userGroup',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '用户类别',
      dataIndex: 'userType',
      key: 'userType',
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      render: (_, record) => (
        <div style={{ display: 'flex' }}>
          <Button type="link" onClick={() => handlePassword(record)}>
            重置密码
          </Button>
          <Button type="link" onClick={() => handleEditUserInfo(record)}>
            编辑
          </Button>
          <Popconfirm
            title=""
            description="删除操作不可逆，请确认是否删除?"
            onConfirm={() => onDelete(record)}
            // onCancel={cancel}
            okText="删除"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const onOrgSelect = (selectedKeys: React.Key[]) => {
    if (selectedKeys.length > 0) {
      setSelectedOrg(selectedKeys[0] as string);
      setCurrentPage(1);
    }
  };

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  const handlePageSizeChange = (current: number, size: number) => {
    setCurrentPage(1);
    setPageSize(size);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys as any);
  };

  const onDeleteGroup = () => {};

  return (
    <div className={styles.user_content}>
      <div className={styles.left_content}>
        <div className={styles.search}>
          <div style={{ paddingBottom: '5px' }}>
            <Button
              type="text"
              style={{ marginRight: '8px', fontSize: '16px' }}
              icon={<PlusOutlined />}
              onClick={() => setVisible(true)}
            />
            <Popconfirm
              title=""
              description="删除操作不可逆，请确认是否删除?"
              onConfirm={() => onDeleteGroup()}
              // onCancel={cancel}
              okText="删除"
              cancelText="取消"
              disabled={selectedOrg === ''}
            >
              <Button
                type="text"
                style={{ fontSize: '16px' }}
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </div>
          <Input.Search
            placeholder="请输入名称"
            style={{ marginBottom: 6 }}
            onSearch={(value) => console.log('Search org:', value)}
          />
        </div>
        <div className={styles.tree_box}>
          <CustomTree
            treeData={orgTreeData}
            titleField="name"
            keyField="id"
            childrenField="children"
            defaultExpandAll
            onSelect={onOrgSelect}
            selectedKeys={[selectedOrg]}
            icon={<TeamOutlined style={{ fontSize: '15px' }} />}
          />
        </div>
      </div>
      <div className={styles.right_content}>
        <div className={styles.teble_content}>
          <div
            style={{
              marginBottom: 16,
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <div>
              <Button
                style={{ marginRight: '8px' }}
                onClick={() => handleCreatUserInfo()}
              >
                新建用户
              </Button>
              <Popconfirm
                title=""
                description="删除操作不可逆，请确认是否删除?"
                onConfirm={() => onDelete()}
                // onCancel={cancel}
                okText="删除"
                cancelText="取消"
                disabled={selectedRowKeys.length === 0}
              >
                <Button
                  disabled={selectedRowKeys.length === 0}
                  style={{ marginRight: '8px' }}
                >
                  删除
                </Button>
              </Popconfirm>
              <Button style={{ marginRight: '8px' }} onClick={getUserListInit}>
                刷新
              </Button>
            </div>
            <div>
              <div>
                <Input.Search
                  placeholder="Search users"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={{ width: 300 }}
                  onSearch={(value) => {
                    console.log('Search user:', value);
                    setCurrentPage(1); // Reset to first page when searching
                  }}
                />
              </div>
            </div>
          </div>
          <div className={styles.teble_box}>
            <Table
              columns={columns}
              dataSource={users}
              loading={loading}
              rowKey="id"
              pagination={{
                current: currentPage,
                pageSize: pageSize,
                total: totalUsers,
                onChange: handlePageChange,
                onShowSizeChange: handlePageSizeChange,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => {
                  return `共${total}条数据`;
                },
              }}
              rowSelection={{
                selectedRowKeys,
                onChange: onSelectChange,
              }}
              scroll={{ x: 'max-content', y: 55 * 12 }}
            />
          </div>
        </div>
      </div>
      <CreatGroup
        visible={visible}
        selectedOrg={selectedOrg}
        onCancel={() => {
          setVisible(false);
        }}
        onOk={() => {}}
        orgTreeData={orgTreeData}
      />
      <UserEditModal
        selectedOrg={selectedOrg}
        orgTreeData={orgTreeData}
        currentUserInfo={currentUserInfo}
        onCancel={() => {
          setCurrentUserInfo({
            recordData: {},
            visible: false,
          });
        }}
        onOk={() => {}}
      />
      <PasswordResetModal
        visible={eidtPassword.visible}
        onCancel={() => {
          setEidtPassword({
            recordData: {},
            visible: false,
          });
        }}
        onOk={() => {}}
      />
    </div>
  );
};

export default UserListPage;
