import React, { useEffect, useState } from 'react'
import { InferResultRes, ItaskDetail, IuserInfosParams, IpowerDetail } from '@/pages/api/base/type'
import AppContext from './createContext'
import { PARAMS } from './constants'
import { getTaskDetail, saveTask, saveSAMMask } from '@/pages/api/base'
import { INIT_GOURP } from '@/common/constans/international'

const AppContextProvider = (props: {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    children: React.ReactElement<any, string | React.JSXElementConstructor<any>>
}) => {
    const [inferResult, setInferResult] = useState<InferResultRes[] | null>([]) // 执行结果查询
    const [inferStarList, setInferStarList] = useState<InferResultRes[]>([])
    const [newInferResult, setNewInferResult] = useState<InferResultRes[] | null>([])
    const [taskResult, setTaskResult] = useState<ItaskDetail>({})
    const [agentName, setAgentName] = useState<string | null>(INIT_GOURP)
    const [pageRefreshState, setPageRefreshState] = useState<number>(0) // 去通知列表刷新的状态
    const [taskId, setTaskId] = useState<string | null>(null)
    const [segementModal, setSegmentModal] = useState<boolean | null>(false) // 是否显示分割片的弹框
    const [requestLoading, setRequestLoading] = useState(false)
    const [showEdit, setShowEdit] = useState(false)
    const [userInfos, setUserInfos] = useState<IuserInfosParams | null>(null)
    const [hasTriggeredTaskDetail, setHasTriggeredTaskDetail] = useState(false)
    const [powerBalanceAmount, setPowerBalance] = useState(0)
    const [needPower, setNeedPower] = useState(40)
    const [startTaskExecutions, setStartExecutions] = useState(false)
    const [mainCutMask, setMainCutMask] = useState('')
    const [batchTaskPowerDetail, setBatchTaskPowerDetail] = useState<IpowerDetail>({})

    // get task detail
    const taskDetail = async (executionId?: string) => {
        let data = {
            taskId,
        }
        if (executionId) data = Object.assign(data, { executionId })
        const value = await getTaskDetail(data)
        if (value?.maskType === 'rgba' && value?.mask) {
            setMainCutMask(value.mask)
        }
        setTaskResult({ ...value })
        setNeedPower(value?.power || 40)
        setBatchTaskPowerDetail(value?.powerDetail)
        setHasTriggeredTaskDetail(true)
        return value
    }

    const samMask = async (mask: string) => {
        if (!taskId) return
        const data = {
            taskId,
            mask,
            maskType: mainCutMask === mask ? 'rgba' : 'rgb',
        }
        await saveSAMMask(data)
    }

    // modify task result
    const handleTaskResult = (key: string, value: any, trigger?: boolean) => {
        setHasTriggeredTaskDetail(trigger || false)
        setTaskResult((prevState) => ({
            ...prevState,
            [key]: value,
        }))
    }

    const saveTaskDetail = async (params?: object) => {
        let data = {
            agentVersion: taskResult?.agentVersion,
            agentName,
            image: taskResult.image,
            showImage: taskResult?.showImage,
            taskId,
            paramType: taskResult.paramType,
            batchTask: taskResult?.batchTask || false,
        }

        if (params) data = Object.assign(data, params)

        if (!taskResult.paramType) return

        PARAMS[taskResult.paramType]?.forEach((item: string) => {
            if (item === 'denoiseType') {
                data = Object.assign(data, {
                    [item]: taskResult[item] || 14,
                })
            } else {
                data = Object.assign(data, {
                    [item]: taskResult[item],
                })
            }
        })

        if (agentName == 'replicate') {
            PARAMS['replicate'].forEach((item: string) => {
                data = Object.assign(data, {
                    [item]: taskResult[item],
                })
            })
        }

        const value = await saveTask(data)
        if (value?.power) setNeedPower(value?.power)
        if (value?.powerDetail) setBatchTaskPowerDetail(value.powerDetail)
        return value
    }

    useEffect(() => {
        if (taskResult.taskId && !hasTriggeredTaskDetail) saveTaskDetail()
    }, [taskResult, hasTriggeredTaskDetail])

    const refreshPageList = () => {
        setPageRefreshState((value) => {
            return value + 1
        })
    }

    return (
        <AppContext.Provider
            value={{
                inferResult: [inferResult, setInferResult],
                inferStarList: [inferStarList, setInferStarList],
                taskResult: [taskResult, setTaskResult],
                agentName: [agentName, setAgentName],
                pageRefreshState: [pageRefreshState],
                refreshPageList,
                taskId: [taskId, setTaskId],
                segementModal: [segementModal, setSegmentModal],
                taskDetail,
                saveTaskDetail,
                handleTaskResult,
                samMask,
                mainCutMask: [mainCutMask, setMainCutMask],
                newInferResult: [newInferResult, setNewInferResult],
                requestLoading: [requestLoading, setRequestLoading],
                showEdit: [showEdit, setShowEdit],
                userInfos: [userInfos, setUserInfos],
                powerBalanceAmount: [powerBalanceAmount, setPowerBalance],
                needPower: [needPower, setNeedPower],
                startTaskExecutions: [startTaskExecutions, setStartExecutions],
                batchTaskPowerDetail: [batchTaskPowerDetail, setBatchTaskPowerDetail],
            }}
        >
            {props.children}
        </AppContext.Provider>
    )
}

export default AppContextProvider
