import React, { useState, useEffect, useRef, useCallback } from 'react'
import { BsSearch, BsPersonCircle } from 'react-icons/bs'
import { api, UserContact } from '../services/api'
import { logger } from '../utils/logger'
import { getDefaultAvatar } from '../utils/avatarUtils'
import './ContactList.css'

interface ContactListProps {
  token: string
  onSelect?: (contact: UserContact) => void
  useAdminApi?: boolean // 是否使用管理员接口（支持完整分页）
}

const ContactList: React.FC<ContactListProps> = ({ token, onSelect, useAdminApi = false }) => {
  const [contacts, setContacts] = useState<UserContact[]>([])
  const [searchKeyword, setSearchKeyword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // 分页状态
  const [page, setPage] = useState(1)
  const pageRef = useRef(1) // 用于在回调中获取最新页数
  const pageSize = 20
  const [total, setTotal] = useState(0)

  // 滚动容器引用
  const scrollContainerRef = useRef<HTMLDivElement>(null)
  const searchTimerRef = useRef<NodeJS.Timeout | null>(null)

  // 同步 pageRef
  useEffect(() => {
    pageRef.current = page
  }, [page])

  // 加载联系人
  const loadContacts = useCallback(async (isRefresh: boolean = false) => {
    if (isLoading || (isLoadingMore && !isRefresh)) return

    try {
      if (isRefresh) {
        setIsRefreshing(true)
        setPage(1)
        pageRef.current = 1
        setContacts([])
      } else {
        setIsLoadingMore(true)
      }
      setIsLoading(true)
      setError(null)

      const currentPage = isRefresh ? 1 : pageRef.current
      let response: UserContact[] | { users: UserContact[]; total: number }
      let currentLimit = pageSize * currentPage // 用于搜索接口的 limit
      
      if (useAdminApi) {
        // 使用管理员接口（支持完整分页）
        try {
          const result = await api.getContactsPaginated(token, {
            skip: isRefresh ? 0 : (currentPage - 1) * pageSize,
            limit: pageSize,
            keyword: searchKeyword || undefined,
            status: 'ACTIVE'
          })
          response = {
            users: result.items,
            total: result.total
          }
        } catch (err: any) {
          // 如果是权限错误，降级到搜索接口
          if (err.message === 'PERMISSION_DENIED') {
            logger.warn('ContactList: Permission denied, falling back to search API')
            currentLimit = pageSize * currentPage
            const searchResult = await api.searchContacts(token, searchKeyword, currentLimit)
            response = searchResult
            setHasMore(searchResult.length >= currentLimit)
          } else {
            throw err
          }
        }
      } else {
        // 使用搜索接口（不支持分页）
        currentLimit = isRefresh ? pageSize : pageSize * currentPage
        const searchResult = await api.searchContacts(token, searchKeyword, currentLimit)
        response = searchResult
      }

      const newContacts = Array.isArray(response) ? response : response.users
      
      if (isRefresh) {
        setContacts(newContacts)
        if (!Array.isArray(response)) {
          setTotal(response.total)
          setHasMore(newContacts.length < response.total)
        } else {
          // 搜索接口不支持分页，如果返回数量小于 limit，说明没有更多了
          setHasMore(newContacts.length >= currentLimit)
        }
      } else {
        // 去重（避免重复数据）
        setContacts(prev => {
          const existingIds = new Set(prev.map(c => c.id))
          const uniqueNewContacts = newContacts.filter(c => !existingIds.has(c.id))
          
          if (!Array.isArray(response)) {
            setHasMore(prev.length + uniqueNewContacts.length < response.total)
          } else {
            setHasMore(uniqueNewContacts.length > 0 && newContacts.length >= currentLimit)
          }
          
          return [...prev, ...uniqueNewContacts]
        })
      }

      if (isRefresh) {
        setIsRefreshing(false)
      } else {
        setIsLoadingMore(false)
      }
    } catch (err: any) {
      logger.error('ContactList: Failed to load contacts', err)
      setError(err.message || '加载联系人失败')
      setIsRefreshing(false)
      setIsLoadingMore(false)
    } finally {
      setIsLoading(false)
    }
  }, [token, searchKeyword, pageSize, useAdminApi])

  // 初始化加载
  useEffect(() => {
    loadContacts(true)
  }, [token, useAdminApi])

  // 处理搜索（防抖）
  useEffect(() => {
    if (searchTimerRef.current) {
      clearTimeout(searchTimerRef.current)
    }

    searchTimerRef.current = setTimeout(() => {
      loadContacts(true)
    }, 500)

    return () => {
      if (searchTimerRef.current) {
        clearTimeout(searchTimerRef.current)
      }
    }
  }, [searchKeyword])

  // 处理滚动事件（使用节流避免频繁触发）
  const scrollTimerRef = useRef<NodeJS.Timeout | null>(null)
  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    // 不阻止默认滚动行为
    const container = e.currentTarget
    if (!container) return

    const { scrollTop, scrollHeight, clientHeight } = container

    // 节流处理加载逻辑
    if (scrollTimerRef.current) {
      clearTimeout(scrollTimerRef.current)
    }

    scrollTimerRef.current = setTimeout(() => {
      // 下拉刷新：滚动到顶部附近（往上拉）
      if (scrollTop < 50 && !isRefreshing && !isLoading) {
        loadContacts(true)
      }

      // 上拉加载更多：滚动到底部附近（往下拉）
      const distanceToBottom = scrollHeight - scrollTop - clientHeight
      if (distanceToBottom < 100 && hasMore && !isLoadingMore && !isLoading) {
        const nextPage = pageRef.current + 1
        setPage(nextPage)
        pageRef.current = nextPage
        loadContacts(false)
      }
    }, 100)
  }, [isRefreshing, isLoading, isLoadingMore, hasMore, loadContacts])

  // 选择联系人
  const handleSelectContact = (contact: UserContact) => {
    if (onSelect) {
      onSelect(contact)
    }
  }

  // 获取联系人显示名称（中文名和英文名）
  const getContactDisplayName = (contact: UserContact): string => {
    const parts: string[] = []
    if (contact.name) {
      parts.push(contact.name)
    }
    if (contact.english_name) {
      parts.push(contact.english_name)
    }
    return parts.length > 0 ? parts.join(' / ') : `用户${contact.id}`
  }

  return (
    <div className="contact-list-container">
      {/* 搜索框 */}
      <div className="contact-search-box">
        <div className="search-input-wrapper">
          <BsSearch className="search-icon" />
          <input
            type="text"
            className="search-input"
            placeholder="搜索联系人（手机号/姓名/英文名）"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
          />
          {searchKeyword && (
            <button
              className="search-clear-btn"
              onClick={() => setSearchKeyword('')}
            >
              ×
            </button>
          )}
        </div>
      </div>

      {/* 联系人列表 */}
      <div
        ref={scrollContainerRef}
        className="contact-list"
        onScroll={handleScroll}
        style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
      >
        {/* 下拉刷新提示 */}
        {isRefreshing && (
          <div className="refresh-tip">
            <div className="loading-spinner" />
            <span>正在刷新...</span>
          </div>
        )}

        {/* 错误提示 */}
        {error && (
          <div className="error-tip">
            {error}
          </div>
        )}

        {/* 联系人项 */}
        {contacts.map((contact) => (
          <div
            key={contact.id}
            className="contact-item"
            onClick={() => handleSelectContact(contact)}
          >
            <div className="contact-avatar">
              {getDefaultAvatar(contact.id, contact.name || contact.english_name, { sizePx: 40 })}
            </div>
            <div className="contact-info">
              <div className="contact-name">{getContactDisplayName(contact)}</div>
            </div>
          </div>
        ))}

        {/* 加载更多提示 */}
        {isLoadingMore && (
          <div className="load-more-tip">
            <div className="loading-spinner" />
            <span>加载中...</span>
          </div>
        )}

        {/* 没有更多数据提示 */}
        {!hasMore && contacts.length > 0 && (
          <div className="no-more-tip">
            没有更多了
          </div>
        )}

        {/* 空状态 */}
        {!isLoading && contacts.length === 0 && !error && (
          <div className="empty-state">
            <div className="empty-icon">👥</div>
            <div className="empty-text">暂无联系人</div>
          </div>
        )}
      </div>
    </div>
  )
}

export default ContactList
