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

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

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

const GeneralNormalList = ({
  batchNo,
  setBatchNo,
  value,
  onChange,
  imageViewer,
}: {
  batchNo: string | null;
  setBatchNo: (batchNo: string | null) => void;
  value: Array<string>;
  onChange: (images: Array<string> | ((prev: Array<string>) => Array<string>)) => void;
  imageViewer: ReturnType<typeof useImageViewer>;
}) => {
  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
    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]);

  // 处理图片点击查看大图
  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(p => {
      if (p.some(v => v === image)) {
        return p.filter(v => v !== image);
      }
      return [...p, 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) => (
            <GeneralImageCard 
              key={index} 
              image={item} 
              checked={value.some(v => v === item.imageUrl)} 
              onClick={handleChange}
              onImageView={handleImageView}
              lockPriceImages={[]}
              setLockPriceImages={() => {}}
            />
          ))
        }
      </div>
    </div>
  );
}
 
export default React.memo(GeneralNormalList);