import styles from './style.module.css'
import { InferResultRes } from '@/pages/api/base/type'
import InferItem from '../InferItem'
import NextImage from 'next/image'
import { useTranslation } from 'next-i18next'
import { useEffect, useMemo, useRef, useState } from 'react'
import CustomModal from '@/components/Modal'
import { Image } from 'antd'
import { IMAGE_WATER_MASK, IS_SUBMIT_TASK, SHOW_WATER_MASK } from '@/common/constans/international'
import StarToTask from '@/components/ShowCase/components/Detail/StarToTask'
import { taskExecutionStars } from '@/pages/api/base'

interface preivew {
    showImage?: string
    previewImage?: string
    finalImage?: string
    // 投稿
    id?: string
    isSubmitted?: boolean
}
interface Iporps {
    taskId: string
    inferStarList?: InferResultRes[]
    setInferStarList: (items: InferResultRes[]) => void
    executionClick: (executeSeq: number, page?: number) => void
}

const InferStar = ({ taskId, inferStarList, setInferStarList, executionClick }: Iporps) => {
    const { t } = useTranslation('studio')

    const [open, setOpen] = useState(false)
    const [activeIndex, setActiveIndex] = useState(-1)
    const [list, setList] = useState<preivew[]>([])

    const [opreateHover, setOpreateHover] = useState(false)
    const [starBtnHover, setStarBtnHover] = useState(false)
    const [height, setHeight] = useState(0)
    const [width, setWidth] = useState(0)
    const [offsetX, setOffsetX] = useState(0)
    const [isSubmitted, setSubmitted] = useState(false)

    const caseDetailRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        const successItems: preivew[] = []
        inferStarList?.forEach((inferResult) => {
            inferResult?.result.forEach((inferItem) => {
                successItems.push({
                    showImage: inferResult.showImage,
                    previewImage: inferItem.previewImage,
                    finalImage: inferItem.finalImage,
                    id: inferItem.id,
                    isSubmitted: inferResult.isSubmitted,
                })
            })
        })
        setList(successItems || [])
    }, [inferStarList])

    const changeImage = (type: number) => {
        if (type && activeIndex < list?.length - 1) {
            setActiveIndex((prevActiveIndex) => prevActiveIndex + 1)
        } else if (!type && activeIndex > 0) {
            setActiveIndex((prevActiveIndex) => prevActiveIndex - 1)
        }
    }

    const handleKeyDown = (event: KeyboardEvent) => {
        if (event.keyCode === 37) {
            // 左箭头键
            changeImage(0)
        } else if (event.keyCode === 39) {
            // 右箭头键
            changeImage(1)
        }
    }

    useEffect(() => {
        window.addEventListener('keydown', handleKeyDown)
        return () => {
            window.removeEventListener('keydown', handleKeyDown)
        }
    }, [activeIndex])

    const outsideClick = (event) => {
        const clickedElement = event.target
        if (clickedElement.id === 'caseDetail' || clickedElement.classList.contains('ant-image')) {
            setOpen(false)
        }
    }

    const activePreview = useMemo(() => {
        return list[activeIndex]
    }, [list, activeIndex])

    useEffect(() => {
        if (activePreview) {
            setSubmitted(activePreview.isSubmitted ?? false)
            const observer = new ResizeObserver((entries) => {
                const contentRect = entries[0].contentRect
                setHeight(contentRect.height)
                setWidth(contentRect.width)
                if (!activePreview.showImage) {
                    const rect = entries[0].target.getBoundingClientRect()
                    const viewportWidth = window.innerWidth
                    setOffsetX(rect.left - viewportWidth / 2)
                }
            })
            const img = caseDetailRef.current?.querySelector('#finalImage img.ant-image-img')
            console.info(img)
            if (img) {
                observer.observe(img)
                return () => {
                    observer.disconnect()
                }
            }
        }
    }, [activePreview])

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

    return (
        <div className={styles.starContainer}>
            <div className={`ag14 ${styles.starTitle}`}>
                <NextImage
                    width={36}
                    height={36}
                    alt="bookmark"
                    src="/ic-tag-star.svg"
                    style={{ marginLeft: '8px', marginRight: '10px' }}
                ></NextImage>
                <span>{t('starred')}</span>
            </div>
            <div className={styles.starlist}>
                {inferStarList?.map((item, index) => {
                    return (
                        <InferItem
                            itemType="star"
                            key={index}
                            item={item}
                            itemData={item.result[0]}
                            executionClick={executionClick}
                            itemChange={(res) => {
                                setInferStarList(
                                    inferStarList?.map((it) => (it.id === res.id ? res : it)),
                                )
                            }}
                            previewIndexChange={() => {
                                const index = list.findIndex((it) => it.id == item.result[0].id)
                                setActiveIndex(index)
                                setOpen(true)
                            }}
                        ></InferItem>
                    )
                })}
            </div>

            <CustomModal
                width={'100%'}
                title=""
                isModalOpen={open}
                setIsModalOpen={setOpen}
                className={styles.detailModal}
            >
                <div className={`ag16 ${styles.head}`}>
                    {activeIndex + 1} / {list?.length}
                </div>
                <div
                    className={styles.showDetail}
                    ref={caseDetailRef}
                    id="caseDetail"
                    onClick={outsideClick}
                >
                    <div className={styles.head}>
                        <div
                            className={styles.closeModalIcon}
                            onClick={() => {
                                setOpen(false)
                            }}
                        >
                            <NextImage
                                src="/close.svg"
                                width={24}
                                height={24}
                                alt="close"
                            ></NextImage>
                        </div>
                    </div>

                    <div
                        className={`${styles.changeBtn} ${
                            activeIndex == 0 ? styles.changeBtnDisable : null
                        }`}
                        onClick={() => changeImage(0)}
                    >
                        <NextImage
                            src="/arrow_white.svg"
                            width={18}
                            height={18}
                            alt="pre"
                            className={styles.preIcon}
                        ></NextImage>
                    </div>

                    {activePreview?.showImage ? (
                        <div className={`${styles.content} ${styles.originImage}`} id="originImage">
                            <Image
                                src={activePreview.showImage}
                                alt="origin-iamge"
                                className={styles.image}
                                preview={false}
                            ></Image>
                        </div>
                    ) : null}

                    <div
                        className={`${styles.content} ${styles.finalImage}`}
                        id="finalImage"
                        onMouseEnter={() => {
                            setOpreateHover(true)
                        }}
                        onMouseLeave={() => {
                            setOpreateHover(false)
                        }}
                    >
                        <Image
                            src={activePreview?.finalImage || ''}
                            alt="origin-iamge"
                            className={styles.image}
                            preview={false}
                        ></Image>
                    </div>

                    <div
                        className={`${styles.changeBtn} ${
                            activeIndex == list?.length - 1 ? styles.changeBtnDisable : null
                        }`}
                        onClick={() => changeImage(1)}
                    >
                        <NextImage
                            src="/arrow_white.svg"
                            width={18}
                            height={18}
                            alt="pre"
                        ></NextImage>
                    </div>

                    {opreateHover || starBtnHover ? (
                        <div
                            className={`${styles.opreateHover} ${
                                activePreview.showImage ? '' : styles.opreateHoverNoOrigin
                            }`}
                            style={{
                                height: height + 'px',
                                width: width - 40 + 'px',
                                pointerEvents: 'none',
                                transform: `translateX(${offsetX}px)`,
                            }}
                        >
                            {IS_SUBMIT_TASK ? 
                                <div className={styles.starSub}>
                                    <StarToTask
                                        id={activePreview.id}
                                        isSubmitted={isSubmitted}
                                        setSubmitted={(value) => {
                                            setSubmitted(value)
                                            getStartList()
                                        }}
                                        mouseChange={(hover) => {
                                            setStarBtnHover(hover)
                                        }}
                                    ></StarToTask>
                                </div> : null
                            }
                        </div>
                    ) : null}

                    {SHOW_WATER_MASK ? (
                        <NextImage
                            src={IMAGE_WATER_MASK}
                            width={200}
                            height={74}
                            alt="water-mask"
                            className={styles.waterMask}
                        ></NextImage>
                    ) : null}
                </div>
            </CustomModal>
        </div>
    )
}

export default InferStar
