import { useGetImageGenerateResult } from "@/hooks/create";
import React, { useEffect, useState } from "react";
import { ContentStatus, GenImageOutput } from "@/services/create";
import { useImageViewer } from "@/hooks/useImageViewer";
import GenaralImageCardMultiple from "./GeneralImageCardMultiple";

const initialDatas = new Array(6).fill(0).map((item, index) => ({
  imageUrl: '',
  status: ContentStatus.Pending,
}));

type SelectedImage = {
  url: string;
  width: number;
  height: number;
}

const GeneralImageListMultiple = ({
  batchNo,
  setBatchNo,
  value,
  onChange,
  imageViewer,
  lockPriceImages,
  setLockPriceImages,
  showPrice = true,
  onAllImagesCompleted,
}: {
  batchNo: string | null;
  setBatchNo: (batchNo: string | null) => void;
  value: string | null;
  onChange: (image: string | null | ((prev: string | null) => string | null)) => void;
  imageViewer: ReturnType<typeof useImageViewer>;
  lockPriceImages: Array<SelectedImage & { unlockPrice: number }>;
  setLockPriceImages: (datas: Array<SelectedImage & { unlockPrice: number }> | ((prev: Array<SelectedImage & { unlockPrice: number }>) => Array<SelectedImage & { unlockPrice: number }>)) => void;
  showPrice?: boolean;
  onAllImagesCompleted?: (allCompleted: boolean) => void;
}) => {
  const [datas, setDatas] = useState<Array<GenImageOutput>>(initialDatas);
  const { mutate: getImageGenerateResult, data, isPending: isLoading, error } = useGetImageGenerateResult()

  useEffect(() => {
    if (error) {
      setBatchNo(null)
    }
  }, [error])

  // 轮训请求
  useEffect(() => {
    if (!batchNo) return
    setDatas(initialDatas)
    getImageGenerateResult({
      batchNo,
    })
  }, [batchNo])

  // 轮训请求
  useEffect(() => {
    if (!batchNo) return
    // 如果还有图片在pending中，则轮训请求
    const pendingImages = datas.filter(item => item.status === ContentStatus.Pending)
    if (pendingImages.length > 0) {
      const interval = setInterval(() => {
        getImageGenerateResult({
          batchNo,
        })
      }, 3000)
      return () => clearInterval(interval)  
    }
  }, [batchNo, datas])

  useEffect(() => {
    setDatas(p => p.map((item, index) => {
      if (data && data[index]) {
        return {
          ...item,
          ...data[index],
        }
      }
      return item
    }));
  }, [data]);

  // 获取所有已生成的图片URL用于大图查看
  const availableImages = React.useMemo(() => {
    return datas
      .filter(item => item.status === ContentStatus.Completed && item.imageUrl)
      .map(item => item.imageUrl)
      .filter((url): url is string => !!url);
  }, [datas]);

  // 检查是否所有图片都不是 pending 状态
  const allImagesCompleted = React.useMemo(() => {
    if (!batchNo) return false;
    return datas.every(item => item.status !== ContentStatus.Pending);
  }, [datas, batchNo]);

  // 当所有图片完成生成时通知父组件
  useEffect(() => {
    if (onAllImagesCompleted) {
      onAllImagesCompleted(allImagesCompleted);
    }
  }, [allImagesCompleted, onAllImagesCompleted]);

  // 处理图片点击查看大图
  const handleImageView = (imageUrl: string) => {
    if (availableImages.length > 0) {
      const index = availableImages.indexOf(imageUrl);
      imageViewer.openViewer(availableImages, index >= 0 ? index : 0);
    }
  };

  const handleChange = (image: string) => {
    onChange(image);
  }

  if (!batchNo) {
    return (
      <div className="max-w-[752px] h-[572px] mx-auto border border-dashed border-outline-normal rounded-lg p-6 flex flex-col justify-center items-center">
        <div className="flex flex-col justify-center items-center gap-3 ">
          <i className="iconfont icon-uploadimg !text-[32px] text-txt-tertiary-normal" />
          <p className="text-txt-tertiary-normal txt-title-s">
            Your image will show here
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-[752px] mx-auto">
      <div className="grid grid-cols-3 gap-4">
        {
          datas.map((item, index) => (
            <GenaralImageCardMultiple 
              key={index}
              image={item}
              checked={value === item.imageUrl} 
              onClick={handleChange}
              onImageView={handleImageView}
              lockPriceImages={lockPriceImages}
              setLockPriceImages={setLockPriceImages}
              showPrice={showPrice}
              uniqueId={`${batchNo}-${index}`}
            />
          ))
        }
      </div>
    </div>
  );
}
 
export default React.memo(GeneralImageListMultiple);