/* eslint-disable @next/next/no-img-element */
/* eslint-disable react/jsx-no-comment-textnodes */
/* eslint-disable jsx-a11y/alt-text */
import styles from './style.module.css'
import { useEffect, useState, useContext } from 'react'
import AppContext from '../hooks/createContext'
import Image from 'next/image'
import Toast from '../Toast'
import * as _ from 'underscore'
import { getMask, getOffsetv2, canvasToImage, getIndex } from './util'
import { compositeImage } from '@/common/utils'
import { useTranslation } from 'next-i18next'
import { MAIN_CUT_AGENT } from '@/common/constans'
import { Modal, Spin } from 'antd'
import ManualMask from '../ManualMask'
import { getBodySegment } from '@/pages/api/base'

interface WH {
    width: number
    height: number
}

interface cums {
    cums: number[]
}
interface segmentation {
    segmentation: cums
}

interface Iprops {
    iWidth: number
    iHeight: number
    imageData: segmentation[]
    mainCutImageData: { [key: string]: string }
}

interface Iposition {
    x: number
    y: number
}

const NewGenerateMask = ({ iWidth, iHeight, imageData }: Iprops) => {
    const { t } = useTranslation('studio')

    const {
        agentName: [agentName],
        taskId: [taskId],
        taskResult: [taskResult],
        segementModal: [segementModal, setSegmentModal],
        mainCutMask: [, setMainCutMask],
        handleTaskResult,
        samMask,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!
    const [index, setIndex] = useState(-1)

    const [maskImage, setMask] = useState('')
    const [selectImg, setSelectImg] = useState<any[]>([taskResult?.mask])
    const [containerAtrr, setContainerAtrr] = useState<WH>()
    const [scale, setScale] = useState(1)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [XY, setPosition] = useState<Iposition>({
        x: -1,
        y: -1,
    })
    const [manualMask, setManualMask] = useState('')
    const handleMouseMove = _.throttle((event: any) => {
        const { x, y } = getOffsetv2(event)
        setPosition({ x, y })
        if (XY.x < 0 || XY.y < 0) return

        const position = Math.ceil(XY.x) * iHeight * scale + Math.ceil(XY.y) * scale
        const cums = imageData?.map((ann) => ann?.segmentation?.cums)
        const index = getIndex(cums, position)
        if (index < 0) return
        setIndex(index)
    }, 200)

    useEffect(() => {
        if (iWidth > 800) {
            setScale(2)
            setContainerAtrr({ width: Math.ceil(iWidth / 2), height: Math.ceil(iHeight / 2) })
        } else {
            setScale(1)
            setContainerAtrr({ width: iWidth, height: iHeight })
        }
    }, [iWidth, iHeight])

    useEffect(() => {
        if (index < 0) return
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        canvas.width = iWidth
        canvas.height = iHeight

        const result = imageData ? getMask(imageData[index]?.segmentation || []) || [] : []
        if (!result.length) return

        for (let row = 0; row < result?.length; row++) {
            for (let col = 0; col < result[row]?.length; col++) {
                const cell = result[row][col]
                if (cell === 1) {
                    if (ctx) {
                        ctx.fillStyle = 'rgba(117, 48, 254, 0.5)'
                        ctx.fillRect(row, col, 1, 1)
                    }
                }
            }
        }

        const image = canvasToImage(canvas)
        if (image.src) {
            if (!selectImg?.includes(image.src)) {
                setMask(image.src)
            }
        }
    }, [index, iWidth, iHeight])

    const saveMask = async () => {
        if (maskImage && !selectImg?.includes(maskImage)) {
            const list = selectImg.filter((item) => item)
            list.push(maskImage)
            setSelectImg(list)
        }
    }

    // 清除重新选择切片
    const clear = () => {
        if (taskResult) {
            handleTaskResult('mask', '', true)
        }
        setSelectImg([])
    }

    // 撤回
    const revoke = () => {
        if (selectImg?.length) {
            const newSelectImg = [...selectImg]
            newSelectImg.splice(newSelectImg.length - 1, 1)
            setSelectImg(newSelectImg)
        }
    }

    // 提交切片
    const confirm = () => {
        if (!selectImg.length) {
            Toast({
                message: t('toast.keepSelect'),
                duration: 3000,
            })
            return
        }

        compositeImage(selectImg, iWidth, iHeight)
            .then((dataUrl: any) => {
                if (taskResult) {
                    // 需要手动调用接口保存mask
                    handleTaskResult('mask', dataUrl, true)
                    samMask(dataUrl)
                    setSegmentModal(false)
                }
            })
            .catch((error) => {
                console.log(error)
                Toast({
                    message: t('toast.keepSelectFail'),
                    duration: 3000,
                })
            })
    }

    const selectManualMask = () => {
        if (selectImg.length) {
            compositeImage(selectImg, iWidth, iHeight)
                .then((dataUrl: any) => {
                    setManualMask(dataUrl)
                    setIsModalOpen(true)
                })
                .catch((error) => {
                    console.log(error)
                })
        } else {
            setIsModalOpen(true)
        }
    }

    const [mainCutLoading, setMainCutLoading] = useState<boolean>(false)

    const mainCut = async () => {
        setMainCutLoading(true)
        const value = await getBodySegment({
            taskId,
            image: taskResult?.showImage || '',
            noShowToast: true,
        })
        if (value?.base64Mask) {
            setSelectImg([value.base64Mask])
            setMainCutMask(value.base64Mask)
            setMainCutLoading(false)
        } else if (value?.status === 'Closed') {
            Toast({ message: t('toast.mainError') })
            setMainCutLoading(false)
        }
    }

    const counterSelect = () => {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        canvas.width = iWidth
        canvas.height = iHeight
        if (!ctx) return
        if (selectImg.length === 0) {
            ctx.fillStyle = 'rgba(117, 48, 254, 0.5)'
            ctx.fillRect(0, 0, iWidth, iHeight)
            const base64Image = canvas.toDataURL() // Generates base64 representation of the image
            const newSelectImg = [base64Image]
            setSelectImg(newSelectImg)
        } else {
            compositeImage(selectImg, iWidth, iHeight, true)
                .then((dataUrl: any) => {
                    const newSelectImg = [dataUrl]
                    setSelectImg(newSelectImg)
                })
                .catch((error) => {
                    console.log(error)
                })
        }
    }

    return (
        <>
            <Modal
                open={segementModal === null ? false : segementModal}
                width={`100%`}
                footer={false}
                closable={false}
                className={styles.modalMask}
                style={{
                    top: 0,
                    padding: 0,
                    margin: 0,
                    maxWidth: '100%',
                }}
                maskStyle={{
                    background: 'rgba(20, 20, 20, 0.9)',
                }}
            >
                <div
                    className={styles.closeModalIcon}
                    onClick={() => {
                        setSegmentModal(false)
                    }}
                >
                    <Image src="/close.svg" alt="close_icon" width={40} height={40}></Image>
                </div>
                <div className={`${styles.message} ag16`}>{t('tool.title')}</div>
                <Spin
                    spinning={mainCutLoading}
                    size="large"
                    style={{ maxHeight: containerAtrr?.height + 'px' }}
                >
                    <div
                        className={styles.content}
                        style={{ height: containerAtrr?.height + 'px' }}
                    >
                        <div
                            className={styles.wrap}
                            style={{
                                width: containerAtrr?.width + 'px',
                                height: containerAtrr?.height + 'px',
                            }}
                            onMouseMove={(event) => {
                                event.stopPropagation()
                                handleMouseMove(event)
                            }}
                            onMouseLeave={() =>
                                _.defer(() => {
                                    setPosition({ x: -1, y: -1 })
                                    setMask('')
                                })
                            }
                            onTouchStart={(event) => {
                                event.stopPropagation()
                                handleMouseMove(event)
                            }}
                            onClick={() => {
                                saveMask()
                            }}
                        >
                            {/* 原图 */}
                            <img
                                src={taskResult?.showImage || ''}
                                alt="test"
                                className={styles.image}
                            ></img>

                            {/* mask图 */}
                            {maskImage && (
                                <img
                                    id="maskImage"
                                    src={maskImage}
                                    className={`${styles.maskImag} ${styles.image}`}
                                ></img>
                            )}

                            {/* 选择图 */}
                            {selectImg?.length && selectImg[0]
                                ? selectImg.map((item, index) => {
                                      return (
                                          <img
                                              key={index}
                                              src={item}
                                              className={`${styles.selectImg} ${styles.image}`}
                                          ></img>
                                      )
                                  })
                                : null}
                        </div>
                    </div>
                </Spin>

                <div className={styles.opreate}>
                    {MAIN_CUT_AGENT.includes(agentName as string) ? (
                        <div className={`${styles.btn} ${styles.clear} ag16`} onClick={mainCut}>
                            <Image
                                className={styles.startBtnSvg}
                                src="/gallery.svg"
                                alt="clear"
                                width={20}
                                height={20}
                            />
                            <span> </span>
                            <span>{t('tool.main')}</span>
                        </div>
                    ) : null}
                    <div
                        className={`${styles.btn} ${
                            MAIN_CUT_AGENT.includes(agentName as string)
                                ? styles.revoke
                                : styles.clear
                        } ag16`}
                        onClick={clear}
                    >
                        <Image
                            className={
                                MAIN_CUT_AGENT.includes(agentName as string)
                                    ? styles.btnSvg
                                    : styles.startBtnSvg
                            }
                            src="/rotate-right.svg"
                            alt="clear"
                            width={20}
                            height={20}
                        />
                        <span> </span>
                        <span>{t('tool.reset')}</span>
                    </div>
                    <div className={`${styles.btn} ${styles.revoke} ag16`} onClick={revoke}>
                        <Image
                            className={styles.btnSvg}
                            src="/return.svg"
                            alt="revoke"
                            width={20}
                            height={20}
                        />
                        <span> </span>
                        <span>{t('tool.undo')}</span>
                    </div>
                    <div className={`${styles.btn} ${styles.revoke} ag16`} onClick={counterSelect}>
                        <Image
                            className={styles.btnSvg}
                            src="/counterSelect.svg"
                            alt="revoke"
                            width={20}
                            height={20}
                        />
                        <span> </span>
                        <span>{t('tool.counterSelect')}</span>
                    </div>
                    <div
                        className={`${styles.btn} ${styles.revoke} ag16`}
                        onClick={() => {
                            selectManualMask()
                        }}
                    >
                        <Image
                            className={styles.btnSvg}
                            src="/brush.svg"
                            alt="brush"
                            width={20}
                            height={20}
                        />
                        <span> </span>
                        <span>{t('tool.brush')}</span>
                    </div>
                    <div
                        className={`${styles.endBtn} ${styles.comfirm} ag16`}
                        onClick={() => {
                            confirm()
                        }}
                    >
                        <Image
                            className={styles.btnSvg}
                            src="/tick-square.svg"
                            alt="revoke"
                            width={20}
                            height={20}
                        />
                        <span> </span>
                        <span>{t('tool.done')}</span>
                    </div>
                </div>
            </Modal>

            {isModalOpen ? (
                <ManualMask
                    isModalOpen={isModalOpen}
                    setIsModalOpen={setIsModalOpen}
                    mask={manualMask}
                    width={iWidth}
                    height={iHeight}
                ></ManualMask>
            ) : null}
        </>
    )
}

export default NewGenerateMask
