import { DeleteOutlined, PlusOutlined, TeamOutlined } from '@ant-design/icons';
import { Button, Col, Input, Pagination, Row, Table, Tree } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import React, { useEffect, useState } from 'react';
import CreatGroup from './mod/group';
import styles from './index.less';

interface User {
  id: string;
  username: string;
  loginName: string;
  userGroup: string;
  userType: string;
}

interface OrganizationNode {
  id: string;
  name: string;
  children?: OrganizationNode[];
}

const UserListPage: React.FC = () => {
  // State for organization tree
  const [orgTreeData, setOrgTreeData] = useState<DataNode[]>([]);
  const [selectedOrg, setSelectedOrg] = useState<string>('');

  // State for user list
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // State for pagination
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [totalUsers, setTotalUsers] = useState<number>(0);

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

  // Mock data for organization tree
  useEffect(() => {
    // In a real application, this would come from an API
    const mockOrgData: DataNode[] = [
      {
        title: 'Headquarters',
        key: '1',
        children: [
          {
            title: 'HR Department',
            key: '2',
          },
          {
            title: 'IT Department',
            key: '3',
            children: [
              {
                title: 'Frontend Team',
                key: '4',
              },
              {
                title: 'Backend Team',
                key: '5',
              },
            ],
          },
          {
            title: 'Finance Department',
            key: '6',
          },
        ],
      },
    ];
    setSelectedOrg(mockOrgData[0].key as string);
    setOrgTreeData(mockOrgData);
  }, []);

  // Mock data for users with pagination
  useEffect(() => {
    // In a real application, this would come from an API based on selected organization
    setLoading(true);

    // Simulate API call delay
    setTimeout(() => {
      // Generate mock users based on current page and page size
      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); // Mock total count
      setLoading(false);
    }, 300);
  }, [selectedOrg, currentPage, pageSize]);

  // Define columns for the user table
  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',
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handleUserAction(record)}>
            重置密码
          </Button>
          <Button type="link" onClick={() => handleUserAction(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleUserAction(record)}>
            删除
          </Button>
        </div>
      ),
    },
  ];

  const handleUserAction = (user: User) => {
    console.log('Editing user:', user);
    // Implement user edit logic here
  };

  const onOrgSelect = (selectedKeys: React.Key[]) => {
    if (selectedKeys.length > 0) {
      setSelectedOrg(selectedKeys[0] as string);
      // Reset to first page when organization changes
      setCurrentPage(1);
    }
  };

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

  const handlePageSizeChange = (current: number, size: number) => {
    setCurrentPage(1); // Reset to first page when page size changes
    setPageSize(size);
  };

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

  return (
    <div className={styles.user_content}>
      <Row gutter={8} style={{ height: '100%' }}>
        <Col span={5}>
          <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)}  
                />
                <Button
                  type="text"
                  style={{ fontSize: '16px' }}
                  icon={<DeleteOutlined />}
                />
              </div>
              <Input.Search
                placeholder="请输入名称"
                style={{ marginBottom: 6 }}
                onSearch={(value) => console.log('Search org:', value)}
              />
            </div>
            <div className={styles.tree_box}>
              <Tree
                showIcon={true}
                treeData={orgTreeData}
                defaultExpandAll
                onSelect={onOrgSelect}
                selectedKeys={[selectedOrg]}
                icon={<TeamOutlined style={{fontSize:"15px"}} />}
              />
            </div>
          </div>
        </Col>
        <Col span={19}>
          <div className={styles.right_content}>
            <div className={styles.teble_content}>
              <div
                style={{
                  marginBottom: 16,
                  display: 'flex',
                  justifyContent: 'space-between',
                }}
              >
                <div>
                  <Button style={{ marginRight: '8px' }}>刷新</Button>
                  <Button
                    disabled={selectedRowKeys.length === 0}
                    style={{ marginRight: '8px' }}
                  >
                    删除
                  </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>

              <Table
                columns={columns}
                dataSource={users}
                loading={loading}
                rowKey="id"
                pagination={false}
                rowSelection={{
                  selectedRowKeys,
                  onChange: onSelectChange,
                }}
              />

              <div style={{ marginTop: 16, textAlign: 'right' }}>
                <Pagination
                  current={currentPage}
                  pageSize={pageSize}
                  total={totalUsers}
                  onChange={handlePageChange}
                  onShowSizeChange={handlePageSizeChange}
                  showSizeChanger
                  showQuickJumper
                  showTotal={(total, range) =>
                    `Showing ${range[0]}-${range[1]} of ${total} items`
                  }
                />
              </div>
            </div>
          </div>
        </Col>
      </Row>
      <CreatGroup visible={visible} onCancel={()=>{setVisible(false)}} onOk={()=>{}} orgTreeData={[]}/>
    </div>
  );
};

export default UserListPage;
