import React, { FC, useState, useRef, useEffect } from 'react';
import styled from 'styled-components';
import { Input } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useEmployeeList } from './useEmployeeList';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const Container = styled.div`
  width: 220px;
  height: calc(100vh - 77px);
  border-radius: 4px;
  background-color: #fff;
  display: flex;
  padding: 0 8px;
  box-sizing: border-box;
  flex-direction: column;
`;

const SearchBar = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 16px 8px;
`;

const ListContainer = styled.div`
  flex: 1;
  overflow-y: auto;
`;

const FreshButton = styled.div<{ $syncing?: boolean }>`
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: ${({ $syncing }) => $syncing ? '#f5f5f5' : '#fafcff'};
  border-radius: 4px;
  width: 24px;
  height: 24px;
  border: 1px solid #dae2f2;
  cursor: ${({ $syncing }) => $syncing ? 'not-allowed' : 'pointer'};
  margin-left: 8px;
  opacity: ${({ $syncing }) => $syncing ? 0.6 : 1};
  
  .icon {
    animation: ${({ $syncing }) => $syncing ? 'spin 1s linear infinite' : 'none'};
  }
  
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
`;

interface ListItemProps {
  active?: boolean;
}

const ListItem = styled.div<ListItemProps>`
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  background-color: ${({ active }) => (active ? '#F0F2F5' : 'transparent')};

  &:hover {
    background-color: #f0f2f5;
  }

  & > img {
    width: 24px;
    height: 24px;
  }

  .info {
    margin-left: 8px;
    display: flex;
    flex-direction: column;

    .name {
      font-size: 14px;
      height: 14px;
      line-height: 14px;
      color: #17181a;
      font-weight: bold;
      margin-bottom: 4px;
    }

    .id {
      height: 12px;
      line-height: 12px;
      font-size: 12px;
      color: #7a8599;
    }
  }
`;

// 假设 employee 的数据结构如下
interface Employee {
  id: number;
  name: string;
  code: string;
}

// 定义组件的 props
interface EmployeeListProps {
  // 父组件通过 onSelect 接收选中的员工信息
  onSelect?: (employee: Employee) => void;
}

const EmployeeList: FC<EmployeeListProps> = ({ onSelect }) => {
  // 搜索框输入值
  const [searchValue, setSearchValue] = useState('');

  const [selectedId, setSelectedId] = useState<number | null>(null);
  // 使用自定义 Hook 获取员工数据及操作方法
  const { employees, loadMore, refresh, syncEmpData, hasMore, loading, syncing, error } =
    useEmployeeList(searchValue, 50);

  // 列表容器 ref，用于绑定滚动监听事件
  const listContainerRef = useRef<HTMLDivElement>(null);

  // 当员工数据更新时，如果没有选中项或选中项在新数据中不存在，则默认选中第一项
  useEffect(() => {
    if (employees.length > 0) {
      const exists = employees.some((emp) => emp.id === selectedId);
      if (!exists) {
        setSelectedId(employees[0].id);
        onSelect && onSelect(employees[0]);
      }
    }
  }, [employees, selectedId, onSelect]);

  useEffect(() => {
    const container = listContainerRef.current;
    if (!container) return;

    let scrollTimeout: NodeJS.Timeout | null = null;

    const handleScroll = () => {
      // 清除之前的定时器
      if (scrollTimeout) {
        clearTimeout(scrollTimeout);
      }
      
      // 设置防抖延迟
      scrollTimeout = setTimeout(() => {
        const { scrollTop, clientHeight, scrollHeight } = container;
        const isNearBottom = scrollTop + clientHeight >= scrollHeight - 10;
        
        // 当滚动到底部时，加载更多
        if (isNearBottom && hasMore && !loading) {
          loadMore();
        }
      }, 100); // 100ms 防抖延迟
    };

    container.addEventListener('scroll', handleScroll);
    return () => {
      container.removeEventListener('scroll', handleScroll);
      if (scrollTimeout) {
        clearTimeout(scrollTimeout);
      }
    };
  }, [loadMore, hasMore, loading]); // 添加 hasMore 和 loading 到依赖数组

  return (
    <Container>
      {/* 搜索区域 */}
      <SearchBar>
        <Input
          placeholder={'姓名/工号'}
          allowClear
          style={{ width: 155 }}
          suffix={
            <IconFont
              type="iconsousuo"
              style={{ color: '#99A6BF', cursor: 'pointer' }}
              onClick={() => {}}
            />
          }
          onChange={(e) => setSearchValue(e.target.value)}
          onPressEnter={() => {}}
        />
        <FreshButton 
          $syncing={syncing}
          onClick={syncing ? undefined : syncEmpData}
        >
          <IconFont 
            type="icon-shuaxin"
            className="icon"
            style={{ color: '#17181A' }} 
          />
        </FreshButton>
      </SearchBar>

      {/* 列表区域 */}
      <ListContainer ref={listContainerRef}>
        {employees.map((employee) => {
          const { id, name, code } = employee;
          const isActive = selectedId === id;
          return (
            <ListItem
              key={id}
              active={isActive}
              onClick={() => {
                setSelectedId(id);
                onSelect && onSelect(employee);
              }}
            >
              <img src={require('./images/emp_icon.png')} alt="" />
              <div className="info">
                <span className="name">{name}</span>
                <span className="id">{code}</span>
              </div>
            </ListItem>
          );
        })}
        
        {/* 状态显示区域 */}
        <div style={{ padding: '8px', fontSize: '12px', color: '#999', textAlign: 'center' }}>
          {syncing && (
            <div style={{ color: '#cfd7e6', marginBottom: 4 }}>
              正在同步员工数据...
            </div>
          )}
          {loading && (
            <div style={{ color: '#cfd7e6' }}>
              加载中...
            </div>
          )}
          {error && (
            <div style={{ color: 'red', marginTop: 4 }}>
              {error}
            </div>
          )}
          {!hasMore && !loading && employees.length > 0 && (
            <div style={{ color: '#999', marginTop: 4 }}>
              没有更多数据了 (共 {employees.length} 条)
            </div>
          )}
          {employees.length === 0 && !loading && !syncing && (
            <div style={{ color: '#999', marginTop: 4 }}>
              暂无数据
            </div>
          )}
        </div>
      </ListContainer>
    </Container>
  );
};

export default EmployeeList;
