import { useContext, useEffect, useRef, useState } from 'react'
import styles from './style.module.css'
import ShowPrompt from './components/ShowPrompt'
import AppContext from '../hooks/createContext'
import { taskExecutions, taskExecutionStars } from '@/pages/api/base'
import InferResult from './components/InferResult'
import ListHeader from './components/ListHeader'
import BatchTaskProgress from './components/BatchTaskProgress'
import InferStar from './components/InferStar'

const ImageList = () => {

    const [executeSeq, setExecuteSeq] = useState<number>(0)
    const [currentPage, setCurrentPage] = useState<number>(1)
    const [isEnd, setIsEnd] = useState(true)
    const [batchStartAt, setBatchStartAt] = useState(null)
    const [executeSummary, setExecuteSummary] = useState('')

    const {
        inferResult: [inferResult],
        taskId: [taskId],
        startTaskExecutions: [startTaskExecutions],
        inferStarList: [inferStarList, setInferStarList],
        inferResult: [, setInferResult],
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const currentTaskId = useRef<string | null>(null)
    const currentStartTaskExecutions = useRef<boolean | null>(null)

    useEffect(() => {
        if (executeSeq) {
            // 模拟滚动到列表的指定位置
            const listItem = document.getElementById(`item-${executeSeq}`)

            if (listItem) {
                listItem.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'start' })
            }
        }
        setExecuteSeq(0)
    }, [executeSeq])

    const getStartList = async () => {
        const value = await taskExecutionStars({ taskId })
        setInferStarList(value ?? [])
    }

    // 执行结果轮询
    useEffect(() => {
        let intervalId: NodeJS.Timeout | null = null
        let isRequestCompleted = true
        let page = currentPage

        if (currentTaskId.current !== taskId) {
            page = 1
            setCurrentPage(page)
            currentTaskId.current = taskId
        }

        const fetchData = async () => {
            if (isRequestCompleted && startTaskExecutions && taskId) {
                isRequestCompleted = false
                try {
                    const value = await taskExecutions({
                        taskId,
                        page,
                        requestTaskExecutions: true,
                    })
                    setExecuteSummary(value?.executeSummary || '当前执行进度')
                    setInferResult(value?.list || [])
                    setIsEnd(value?.isLastPage || false)
                    setBatchStartAt(value?.batchStartAt)
                    if (value?.clearInterval) {
                        if (intervalId) clearInterval(intervalId)
                    }
                } catch (error) {
                    console.error(error)
                }
                isRequestCompleted = true
            }
        }
        if (currentStartTaskExecutions.current == startTaskExecutions) {
            fetchData()
        }
        currentStartTaskExecutions.current = startTaskExecutions
        intervalId = setInterval(fetchData, 2000)
        return () => {
            if (intervalId) clearInterval(intervalId)
        }
    }, [startTaskExecutions, currentPage])

    const executionClick = (executeSeq: number, page?: number) => {
        if (page && page !== currentPage) {
            setCurrentPage(page)
            setTimeout(() => {
                setExecuteSeq(executeSeq)
            }, 1000)
        } else {
            setExecuteSeq(executeSeq)
        }
    }

    const turnPage = (num: number) => {
        const element = document.getElementById('output')
        if (element) element.scrollTop = 0
        setCurrentPage(num)
        if (num === 1) {
            getStartList()
        }
    }

    return (
        <>
            <ListHeader currentPage={currentPage} isEnd={isEnd} turnPage={turnPage}></ListHeader>
            {inferStarList?.length && currentPage === 1 ? (
                <InferStar
                    taskId={taskId ?? ""}
                    inferStarList={inferStarList}
                    setInferStarList={setInferStarList}
                    executionClick={executionClick}
                ></InferStar>
            ) : null}
            <div>
                {inferResult?.length ? (
                    <div className={styles.inferResult}>
                        {inferResult?.map((item, key) => {
                            return (
                                <div
                                    key={key}
                                    className={styles.imageResult}
                                    id={`item-${item.executeSeq}`}
                                >
                                    {key === batchStartAt && executeSummary ? (
                                        <BatchTaskProgress
                                            executeSummary={executeSummary}
                                        ></BatchTaskProgress>
                                    ) : null}

                                    <ShowPrompt item={item}></ShowPrompt>
                                    <InferResult item={item}></InferResult>
                                </div>
                            )
                        })}
                    </div>
                ) : null}
            </div>
        </>
    )
}

export default ImageList
