import { Modal } from 'antd'
import { Slider } from 'antd'
import styles from './style.module.css'
import NextImage from 'next/image'
import React, { useContext, useRef, useState, useEffect } from 'react'
import AppContext from '../hooks/createContext'
import { optionList } from './constans'
import Circle from './Circle'
import Toast from '../Toast'
import { useTranslation } from 'next-i18next'

interface Iporps {
    setIsModalOpen: (value: boolean) => void
    isModalOpen: boolean
    mask: string
    width: number
    height: number
}

const ManualMask = ({ isModalOpen, setIsModalOpen, width, height, mask }: Iporps) => {
    const { t } = useTranslation('studio')

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

    const [svgSelected, setSvgSelected] = useState<string>('')
    const [scaleNum, setScaleNum] = useState<number>(100)
    const canvasRef = useRef<HTMLCanvasElement>(null)
    const prevToolRef = useRef<string>('')
    const [canvas, setCanvas] = useState<any>(null)
    const prevCanvasRef = useRef<any>(null)
    const [lineWidth, setLineWidth] = useState(18)
    const historyRef = useRef<string[]>([])
    const stepRef = useRef<number>(-1)
    const [canvasPosition, setCanvasPosition] = useState<any>(null)

    useEffect(() => {
        if (!taskResult.showImage) return
        const canvas = canvasRef.current
        if (!canvas) return
        const ctx = canvas?.getContext('2d')
        canvas.width = width
        canvas.height = height
        const img = new Image()
        if (mask) {
            img.src = mask
            img.onload = () => {
                ctx?.drawImage(img, 0, 0)
                prevCanvasRef.current = canvas.toDataURL() // 保存画布初始状态
                setSvgSelected('brush')
                prevToolRef.current = 'brush'
                setCanvas(canvas)
            }
        } else {
            ctx?.clearRect(0, 0, width, height)
            prevCanvasRef.current = canvas.toDataURL() // 保存画布初始状态
            setCanvas(canvas)
        }
    }, [])

    useEffect(() => {
        if (!canvas || !(svgSelected === 'brush' || svgSelected === 'eraser')) return
        const ctx = canvas.getContext('2d')
        let isDrawing = false

        const onDrawStart = (e: MouseEvent) => {
            isDrawing = true
            const value = getRelativeCoords(canvas, e)
            ctx.lineWidth = lineWidth
            ctx.lineCap = 'round'
            ctx.lineJoin = 'round'
            ctx.beginPath()
            ctx.moveTo(value.x, value.y)
            draw(value)
        }

        const onDrawing = (e: MouseEvent) => {
            if (isDrawing) {
                window.requestAnimationFrame(() => {
                    draw(getRelativeCoords(canvas, e))
                })
            }
        }

        const onDrawEnd = () => {
            saveSnapshot()
            isDrawing = false
            ctx.globalCompositeOperation = 'source-over'
        }

        const getRelativeCoords = (element: HTMLCanvasElement, event: MouseEvent) => {
            const rect = element.getBoundingClientRect()
            const scaleX = element.width / rect.width
            const scaleY = element.height / rect.height
            return {
                x: (event.clientX - rect.left) * scaleX,
                y: (event.clientY - rect.top) * scaleY,
            }
        }

        const draw = (coords: { x: number; y: number }) => {
            if (prevToolRef.current === 'brush') {
                ctx.strokeStyle = 'rgba(117, 48, 254, 0.5)'
                ctx.lineTo(coords.x, coords.y)
                ctx.stroke()
            } else if (prevToolRef.current === 'eraser') {
                ctx.strokeStyle = '#fff'
                ctx.globalCompositeOperation = 'destination-out'
                ctx.lineTo(coords.x, coords.y)
                ctx.stroke()
            }
        }

        canvas.addEventListener('mousedown', onDrawStart)
        canvas.addEventListener('mousemove', onDrawing)
        canvas.addEventListener('mouseup', onDrawEnd)

        return () => {
            canvas.removeEventListener('mousedown', onDrawStart)
            canvas.removeEventListener('mousemove', onDrawing)
            canvas.removeEventListener('mouseup', onDrawEnd)
        }
    }, [canvas, svgSelected, lineWidth])

    // 保存快照
    const saveSnapshot = () => {
        const snapshot = canvas.toDataURL()
        if (historyRef.current.length && historyRef.current[stepRef.current] === snapshot) return // 避免重复保存相同状态
        historyRef.current = [...historyRef.current.slice(0, stepRef.current + 1), snapshot]
        stepRef.current += 1
        prevCanvasRef.current = snapshot
    }

    // 撤销
    const undo = () => {
        const canvas = canvasRef.current
        const ctx = canvas?.getContext('2d')
        if (stepRef.current < 0 || !canvas || !ctx) return
        const index = stepRef.current - 1
        stepRef.current = index
        const img = new Image()
        if (index < 0) {
            if (mask) img.src = mask
            else {
                ctx?.clearRect(0, 0, canvas.width, canvas.height)
                prevCanvasRef.current = canvas.toDataURL() // 保存画布初始状态
            }
        } else {
            img.src = historyRef.current[index]
        }
        if (!img.src) return
        img.onload = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(img, 0, 0)
            prevCanvasRef.current = canvas.toDataURL()
        }
    }

    // 重做
    const redo = () => {
        const canvas = canvasRef.current
        const ctx = canvas?.getContext('2d')
        if (stepRef.current >= historyRef.current.length - 1 || !canvas || !ctx) return
        stepRef.current += 1
        const img = new Image()
        img.src = historyRef.current[stepRef.current]
        img.onload = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(img, 0, 0)
            prevCanvasRef.current = canvas.toDataURL()
        }
    }

    // 清除
    const clear = () => {
        const canvas = canvasRef.current
        const ctx = canvas?.getContext('2d')
        if (!canvas || !ctx) return
        const img = new Image()
        if (mask) {
            img.src = mask
            img.onload = () => {
                ctx.clearRect(0, 0, canvas?.width, canvas?.height)
                ctx.drawImage(img, 0, 0)
                prevCanvasRef.current = canvas.toDataURL()
            }
        } else {
            ctx?.clearRect(0, 0, canvas.width, canvas.height)
            prevCanvasRef.current = canvas.toDataURL() // 保存画布初始状态
        }
    }
    // 橡皮擦和画笔的切换
    const handleSwitchTool = (value: string) => {
        prevToolRef.current = value
    }

    // 更新选中图标的颜色
    const updateSvgColor = (key: string) => {
        setSvgSelected(key === svgSelected ? '' : key)
    }

    // 操作栏
    const opreate = (key: string) => {
        switch (key) {
            case 'enlarge':
                upScale()
                break
            case 'narrow':
                downScale()
                break
            case 'brush':
                handleSwitchTool(key)
                break
            case 'eraser':
                handleSwitchTool(key)
                break
            case 'undo':
                undo()
                break
            case 'redo':
                redo()
                break
            case 'clear':
                clear()
                break
        }
    }

    // 放大
    const upScale = () => {
        if (scaleNum < 500) {
            setScaleNum((prevScaleNum) => {
                if (prevScaleNum >= 200) return prevScaleNum + 100
                if (prevScaleNum >= 100) return prevScaleNum + 25
                return prevScaleNum + 10
            })
        }
    }

    // 缩小
    const downScale = () => {
        if (scaleNum > 20) {
            setScaleNum((prevScaleNum) =>
                prevScaleNum > 200
                    ? prevScaleNum - 100
                    : prevScaleNum > 100
                    ? prevScaleNum - 25
                    : prevScaleNum - 10,
            )
        }
    }

    // 操作点击
    const onDivClick = (key: string, index: number) => {
        if (optionList[index]?.activeSvg !== '') {
            updateSvgColor(key)
        }
        opreate(key)
    }

    // 设置画笔大小
    const sliderOnChange = (value: number) => {
        setLineWidth(value)
    }

    const submit = () => {
        const logParam = window?.logger.getParams('100000010', window?.logger.EVENT_TYPE.CLICK, {
            taskId,
            type: 1,
        })
        window?.logger.log([logParam])
        const ctx = canvas?.getContext('2d')
        const imageData = ctx?.getImageData(0, 0, canvas.width, canvas.height)
        let hasNonEmptyPixels = false

        // 遍历每个像素，检查RGBA值是否为0
        for (let i = 0; i < imageData?.data?.length; i += 4) {
            const r = imageData.data[i]
            const g = imageData.data[i + 1]
            const b = imageData.data[i + 2]
            const a = imageData.data[i + 3]

            if (r !== 0 || g !== 0 || b !== 0 || a !== 0) {
                hasNonEmptyPixels = true
                break
            }
        }

        if (hasNonEmptyPixels) {
            const maskImg = canvas.toDataURL()
            // 需要手动调用mask接口保存
            handleTaskResult('mask', maskImg, true)
            samMask(maskImg)
            setIsModalOpen(false)
            setSegmentModal(false)
        } else {
            Toast({
                message: t('toast.keepSelect'),
                duration: 3000,
            })
            return
        }
    }

    function handleCanvasMouseDown(event: { clientX: number; clientY: number }) {
        if (svgSelected !== 'hand') return
        const element = document.getElementById('maskParent')
        const canvasRect = element?.getBoundingClientRect()
        if (!canvasRect) return
        const mouseX = event.clientX - canvasRect.left
        const mouseY = event.clientY - canvasRect.top

        const canvasX = element?.offsetLeft || 0
        const canvasY = element?.offsetTop || 0

        // 计算缩放后的坐标
        const scaleX = 1 / (scaleNum / 100)
        const scaleY = 1 / (scaleNum / 100)
        const offsetX = mouseX * scaleX - canvasX
        const offsetY = mouseY * scaleY - canvasY

        function handleMouseMove(event: { clientX: number; clientY: number }) {
            if (!canvasRect) return
            const newMouseX = event.clientX - canvasRect.left
            const newMouseY = event.clientY - canvasRect.top

            // 计算缩放后的坐标
            const newX = newMouseX * scaleX - offsetX
            const newY = newMouseY * scaleY - offsetY

            setCanvasPosition({ x: newX, y: newY })
        }

        function handleMouseUp() {
            document.removeEventListener('mousemove', handleMouseMove)
            document.removeEventListener('mouseup', handleMouseUp)
        }

        document.addEventListener('mousemove', handleMouseMove)
        document.addEventListener('mouseup', handleMouseUp)
    }

    return (
        <Modal
            open={isModalOpen}
            width={`100%`}
            footer={false}
            closable={false}
            className={styles.canvas}
            style={{
                top: 0,
                padding: 0,
                margin: 0,
                maxWidth: '100%',
            }}
        >
            {svgSelected === 'brush' || svgSelected === 'eraser' ? (
                <div
                    className={
                        svgSelected === 'brush'
                            ? `${styles.sliderContent} ${styles.sliderBrush}`
                            : `${styles.sliderContent} ${styles.sliderEraser}`
                    }
                >
                    <NextImage
                        src={
                            svgSelected === 'brush'
                                ? '/canvas-solid-dot.svg'
                                : '/canvas-hollow-dot.svg'
                        }
                        width={16}
                        height={16}
                        alt={'canvas icon'}
                        className={styles.solidBigDot}
                    ></NextImage>
                    <Slider
                        min={1}
                        max={100}
                        vertical
                        value={lineWidth}
                        onChange={sliderOnChange}
                    />
                    <NextImage
                        src={
                            svgSelected === 'brush'
                                ? '/canvas-solid-dot.svg'
                                : '/canvas-hollow-dot.svg'
                        }
                        width={12}
                        height={12}
                        alt={'canvas icon'}
                        className={styles.solidSmallDot}
                    ></NextImage>
                </div>
            ) : null}
            <div className={styles.canvasOption}>
                <div className={styles.canvasOptionLeft}>
                    <div
                        className={styles.canvasOptionDetail}
                        onClick={() => {
                            const logParam = window?.logger.getParams(
                                '100000010',
                                window?.logger.EVENT_TYPE.CLICK,
                                {
                                    taskId,
                                    type: 0,
                                },
                            )
                            window?.logger.log([logParam])
                            setIsModalOpen(false)
                        }}
                    >
                        <NextImage
                            src="/canvas-close.svg"
                            width={24}
                            height={24}
                            alt="canvas close"
                        ></NextImage>
                        <span className={`${styles.canvasOptionText} ag16`}>
                            {t('manual.cancel')}
                        </span>
                    </div>
                </div>
                <div className={styles.canvasOptionCenter}>
                    {optionList.map((item, index) => (
                        <React.Fragment key={index}>
                            <div
                                className={`ag16 ${styles.canvasOptionDetail} 
                                ${
                                    svgSelected === item.key
                                        ? styles.optionActiveColor
                                        : styles.optionDefaultColor
                                }`}
                                onClick={() => {
                                    onDivClick(item.key, index)
                                }}
                            >
                                <NextImage
                                    src={svgSelected === item.key ? item.activeSvg : item.svg}
                                    width={24}
                                    height={24}
                                    alt={item.alt}
                                ></NextImage>
                                <span className={styles.canvasOptionTextRight}>
                                    {t('manual', { returnObjects: true })[item.key]}
                                </span>
                                {item.dropDown && (
                                    <NextImage
                                        src={
                                            svgSelected === item.key
                                                ? `/canvas-drop-down-active.svg`
                                                : `/canvas-drop-down.svg`
                                        }
                                        width={16}
                                        height={16}
                                        alt="canvas drop down"
                                    ></NextImage>
                                )}
                            </div>
                            {item.borderRight && <div className={styles.optionBorderRight}></div>}
                            {index === optionList.length - 2 && (
                                <div className={styles.optionScaleText}>{`${scaleNum}%`}</div>
                            )}
                        </React.Fragment>
                    ))}
                </div>
                <div className={styles.canvasOptionRight}>
                    <div
                        className={styles.canvasOptionDetail}
                        onClick={() => {
                            submit()
                        }}
                    >
                        <NextImage
                            src="/canvas-success.svg"
                            width={24}
                            height={24}
                            alt="canvas success"
                        ></NextImage>
                        <span className={`${styles.canvasOptionText} ag16`}>
                            {t('manual.done')}
                        </span>
                    </div>
                </div>
            </div>
            <div className={`${styles.canvasTip} ag20`}>{t('manual.title')}</div>
            <div className={styles.manualMask} style={{ height: canvas?.height + 'px' }}>
                <div
                    className={`${svgSelected === 'hand' && styles.userSelect} ${
                        styles.canvasMask
                    }`}
                    id="maskParent"
                    style={{
                        width: canvas?.width + 'px',
                        height: canvas?.height + 'px',
                        transform: `scale(${scaleNum / 100})`,
                        cursor: svgSelected === 'hand' ? 'grab' : '',
                        left: canvasPosition?.x,
                        top: canvasPosition?.y,
                    }}
                    onMouseDown={handleCanvasMouseDown}
                >
                    <NextImage
                        width={300}
                        height={300}
                        src={taskResult.showImage || ''}
                        alt="originImag"
                        className={styles.showImage}
                        unoptimized
                    ></NextImage>
                    <canvas ref={canvasRef} className={styles.canvas} id="cavansMask"></canvas>
                    {svgSelected === 'brush' || svgSelected === 'eraser' ? (
                        <Circle width={lineWidth}></Circle>
                    ) : null}
                </div>
            </div>
        </Modal>
    )
}

export default ManualMask
