import { useState, useEffect, useCallback } from 'react'
import { useSelector } from 'react-redux'
import { Spin, Empty } from 'antd'
import { useWebSocket, useInterval } from 'ahooks'
import { getDesignList, getSourceImage } from '@/api/chuangkit'
import { uploadFileByUrl } from '@/utils/oss'

export default function OnlineImageList({ imgUrl, onChange }) {
  const [isLoading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const { userInfo } = useSelector((state) => state.user)

  const fetchDesignList = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getDesignList({
        params: {
          time_order: 1,
          user_flag: userInfo.id,
          page_no: 1,
          page_size: 1000
        }
      })
      setList(res.data.list || [])
    } catch (error) {
      console.error('Failed to fetch design list:', error)
    } finally {
      setLoading(false)
    }
  }, [userInfo.id])

  useEffect(() => {
    fetchDesignList()
  }, [fetchDesignList])

  const { readyState, latestMessage, sendMessage, disconnect } = useWebSocket(import.meta.env.VITE_API_WEBSOCKET_URL)

  useEffect(() => {
    if (readyState === 1) {
      sendMessage(JSON.stringify({ user_id: userInfo.id }))
    }
    return () => {
      if (readyState === 1) {
        disconnect()
      }
    }
  }, [readyState, sendMessage, userInfo.id, disconnect])

  useInterval(() => {
    if (readyState === 1) {
      sendMessage(JSON.stringify({ heart: 1 }))
    }
  }, 5000)

  const handleMessage = useCallback(
    async (message) => {
      const data = JSON.parse(message.data)
      const designId = data.data?.designId || ''
      const downloadUrls = data.data?.downloadUrls || []
      if (designId && downloadUrls.length) {
        const [firstUrl = ''] = downloadUrls
        const url = await uploadFileByUrl(firstUrl)
        setList((prevList) =>
          prevList.map((item) =>
            item.designId === designId
              ? {
                  ...item,
                  thumbUrl: url,
                  isDownload: true
                }
              : item
          )
        )
        onChange(url)
      }
    },
    [onChange]
  )

  useEffect(() => {
    if (latestMessage) handleMessage(latestMessage)
  }, [latestMessage, handleMessage])

  const handleClick = useCallback(
    async (item) => {
      onChange(item.thumbUrl)
      if (!item.isDownload) {
        await getSourceImage({
          params: {
            userFlag: userInfo.id,
            designId: item.designId
          }
        })
      }
    },
    [onChange, userInfo.id]
  )

  return (
    <Spin spinning={isLoading}>
      <div className="online-image-list">
        {list.length ? (
          list.map((item) => (
            <div className={`online-image-list-item ${imgUrl === item.thumbUrl ? 'is-active' : ''}`} key={item.designId} onClick={() => handleClick(item)}>
              <img src={item.thumbUrl} alt="" />
            </div>
          ))
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        )}
      </div>
    </Spin>
  )
}
