import styles from './style.module.css'
import Image from 'next/image'
import { IgetTaskRes } from '@/pages/api/base/type'
import TaskStatus from './components/Status'
import AppContext from '@/components/hooks/createContext'
import React, { useContext, useEffect, useState } from 'react'
import { getTask, saveTask } from '@/pages/api/base'
import { useTranslation } from 'next-i18next'
import { DEFAULT_AGENT_TIPS } from '@/common/constans'
import { SHOW_BATCH_TASK } from '@/common/constans/international'
import BatchTask from './components/Batch'

interface Iprops {
    onChange: () => void
}

const Task = ({ onChange }: Iprops) => {
    const { t } = useTranslation('studio')
    const {
        taskId: [taskId, setTaskId],
        agentName: [agentName],
        pageRefreshState: [pageRefreshState],
        inferResult: [, setInferResult],
        inferStarList: [, setInferStarList],
        needPower: [, setNeedPower],
        userInfos: [userInfos],
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!
    const [oldAgent, setOldAgent] = useState<any>(agentName)
    const [taskPage, setTaskPage] = useState<number>(1)
    const [isLastPage, setIsLastPage] = useState<boolean>(false)
    const [taskList, setList] = useState<IgetTaskRes[]>([])

    // get task list
    const getTaskList = async (page: number) => {
        const value = await getTask({ page: page, agentName: agentName, noShowToast: true })
        if (!value?.list?.length) {
            setTaskId(null)
            setIsLastPage(false)
            setInferResult([])
            setInferStarList([])
        }
        setList(value?.list)
        setIsLastPage(value?.isLastPage ? value.isLastPage : false)
    }

    const pageTurning = (pageNum: number) => {
        const element = document.getElementById('myList')
        if (element) element.scrollTop = 0
        setTaskPage(pageNum)
    }

    // get task list loop
    useEffect(() => {
        let currentPage = taskPage
        let isRequestCompleted = true

        if (oldAgent !== agentName) {
            setTaskPage(1)
            setOldAgent(agentName)
            currentPage = 1
        }

        const fetchData = async () => {
            try {
                await getTaskList(currentPage)
            } catch (error) {
                console.error(error)
            }
            isRequestCompleted = true
        }

        const startPolling = () => {
            if (!isRequestCompleted) return // Skip if previous request hasn't completed yet

            isRequestCompleted = false // Set flag to indicate that a request is in progress

            fetchData()
        }

        startPolling()
        let intervalId: NodeJS.Timeout | null = null
        intervalId = setInterval(startPolling, 3000) // Start polling with a delay of 3 seconds

        return () => {
            if (intervalId) clearInterval(intervalId)
        }
    }, [agentName, taskPage, pageRefreshState])

    // 切换任务
    const changeTask = async (id: string) => {
        const logParam = window?.logger.getParams(
            window?.logger.EID.COMMON_CLICK,
            window?.logger.EVENT_TYPE.CLICK,
            {
                type: 'task',
                taskId: id,
                agentName,
            },
        )
        window?.logger.log([logParam])
        setTaskId(id)
    }

    useEffect(() => {
        if (taskId) onChange()
    }, [taskId])

    // add task
    const addTask = async (taskType: boolean) => {
        if (!agentName) return
        // 打点
        const logParam = window?.logger.getParams(
            window?.logger.EID.COMMON_CLICK,
            window?.logger.EVENT_TYPE.CLICK,
            {
                type: 'newTask',
                agentName,
                batchTask: taskType,
            },
        )
        window?.logger.log([logParam])

        const value = await saveTask({
            agentName: agentName,
            paramType: DEFAULT_AGENT_TIPS[agentName].paramType,
            tagIds: [],
            batchTask: taskType,
            agentVersion:
                userInfos?.agent15 && DEFAULT_AGENT_TIPS[agentName].isSupportChangeVersion
                    ? userInfos?.agentVersion
                        ? userInfos.agentVersion
                        : 'v1.5'
                    : 'v1.0',
        })
        if (value) {
            setNeedPower(value?.power || 40)
            setTaskId(value.taskId)
            getTaskList(taskPage)
        }
    }

    return (
        <>
            <div className={styles.addTaskWrap}>
                <div
                    className={`ag14 ${styles.addTask}`}
                    onClick={() => {
                        addTask(false)
                    }}
                >
                    <Image
                        src="/add_active.svg"
                        alt="add"
                        width={14}
                        height={14}
                        className={styles.addIcon}
                    ></Image>
                    <span>{t('newTask')}</span>
                </div>
                {agentName &&
                DEFAULT_AGENT_TIPS[agentName]?.isSupportBatchTask &&
                SHOW_BATCH_TASK ? (
                    <BatchTask selectTaskWay={addTask}></BatchTask>
                ) : null}
            </div>
            {taskList?.length ? (
                <div className={styles.taskList} id="myList">
                    {taskList.map((item, key) => {
                        return (
                            <div
                                className={`${styles.item} ${
                                    taskId === item.taskId ? styles.active : ''
                                }`}
                                key={key}
                                onClick={() => {
                                    changeTask(item.taskId)
                                }}
                            >
                                <div className={`ag14 ${styles.origin}`}>
                                    <Image
                                        src={`${item?.image || '/mask.svg'}`}
                                        width={40}
                                        height={40}
                                        alt="original"
                                        className={styles.image}
                                        unoptimized
                                    ></Image>

                                    <p className={styles.taskName}>{item.name}</p>
                                    {item.status ? (
                                        <div className={`ag14 ${styles.statusText}`}>
                                            {item.status === 'Pending'
                                                ? t('taskStatus.pending')
                                                : item.status === 'Running'
                                                ? t('taskStatus.running')
                                                : item.status === 'Segmenting'
                                                ? t('taskStatus.sgmenting')
                                                : item.status === 'Success'
                                                ? t('taskStatus.success')
                                                : ''}
                                        </div>
                                    ) : null}
                                </div>

                                <div className={styles.status}>
                                    <TaskStatus
                                        item={item}
                                        getTaskList={() => getTaskList(taskPage)}
                                    ></TaskStatus>
                                </div>
                            </div>
                        )
                    })}
                    {taskPage === 1 && isLastPage ? null : (
                        <div className={styles.pageTurn}>
                            {taskPage !== 1 ? (
                                <>
                                    <div
                                        className={`${styles.turnButton} ${styles.homeButton}`}
                                        onClick={() => {
                                            if (taskPage !== 1) pageTurning(1)
                                        }}
                                    >
                                        {t('home')}
                                    </div>
                                    <div
                                        className={`${styles.turnButton}`}
                                        onClick={() => {
                                            if (taskPage !== 1) pageTurning(taskPage - 1)
                                        }}
                                    >
                                        {t('previous')}
                                    </div>
                                </>
                            ) : null}
                            {!isLastPage ? (
                                <div
                                    className={`${styles.turnButton}`}
                                    onClick={() => {
                                        if (!isLastPage) pageTurning(taskPage + 1)
                                    }}
                                >
                                    {t('next')}
                                </div>
                            ) : null}
                        </div>
                    )}
                </div>
            ) : null}
        </>
    )
}

export default Task
