import { Image, View, ScrollView } from "@tarojs/components";
import EmptyData from "@/components/EmptyData";
import CardListItem from "@/components/list/card-list-item/index";

import WemetaRadio from "@/components/WemetaRadio/index";
import IconWave from "@/images/icon-wave-20.png";

import { useEffect, useRef, useState } from "react";
import Popup from "@/components/popup/popup";
import PopupRecorder, { ECloneStatus } from "./components/popup-recorder/index";
import SliderAction from "@/components/SliderAction";
import style from "./index.module.less";
import { useVoiceStore } from "@/store/voiceStore";
import { EVoiceStatus, EVoiceType, TVoiceItem } from "@/types/voice";
import { TAgentDetail } from "@/types/agent";

import { deleteVoice, getVoiceStatus } from "@/service/voice";
import ThinkingAnimation from "@/components/think-animation";
import { useModalStore } from "@/store/modalStore";
import { isSuccess } from "@/utils";
import Taro, { useDidShow } from "@tarojs/taro";

import { getVoices, cloneVoice as _cloneVoice } from "@/service/voice";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import BottomBar from "@/components/BottomBar";
import { useAppStore } from "@/store/appStore";

interface Props {
  agent: Partial<TAgentDetail> | null;
  onPlay: (voice: any) => void;
  onSelect: (voice: any) => void;
}

type TTask = {
  message: string;
  status: "processing" | "success" | "process_fail";
  taskId: string;
};

export default ({ onPlay, onSelect, agent }: Props) => {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const [show, setShow] = useState(false);
  const { showModal } = useModalStore((state) => state.actions);
  const bottomSafeHeight = useAppStore((state) => state.bottomSafeHeight);

  const fetcher = async ([url, { pageSize, pageIndex }, [entId]]) => {
    console.log([url, { pageSize, pageIndex }], entId);
    const res = await getVoices({
      pageSize,
      pageIndex,
      entId,
      type: EVoiceType.MINE,
    });
    return res.data;
  };
  const entId = agent?.entId || 0
  const { list, mutate, loadMore } = useLoadMoreInfinite<TVoiceItem[]>(
    createKey(`api/getvoices/${entId}`, 10, [entId]),
    fetcher
  );

  // const myVoices = useVoiceStore((state) => state.myVoices);

  const voices = useVoiceStore((state) => state.voices);

  // {
  //   message: '生成中',
  //   taskId: 'abc',
  //   status: 'processing'
  // }
  const [cloning, setCloning] = useState<TTask | null>();

  //获取一个默认声音
  const getDefaultVoice = () => {
    // 优先使用我的声音
    if (list.length) {
      return list[0];
    }
    // // 其次使用系统声音
    const systemVoices = voices.filter((item) => item.isSystem);
    if (systemVoices.length) {
      return systemVoices[0];
    }
    return null;
  };

  // 检查需要不要改变默认声音
  const syncDefaultVoice = (item: TVoiceItem) => {
    // 说明删除的声音是当前使用的声音
    if (agent?.voiceId === item.voiceId) {
      // 需要默认找一个声音
      const defaultVoice = getDefaultVoice();
      if (defaultVoice) {
        handleSelect(defaultVoice);
      }
    }
  };

  const handleSelect = (item: TVoiceItem) => {
    if (item.status == EVoiceStatus.DONE) {
      if (item.voiceName) {
        onSelect && onSelect(item);
      }
    }
  };

  const handleTry = (e: any, item: TVoiceItem) => {
    e.stopPropagation();
    if (item.status == EVoiceStatus.DONE) {
      if (item.voiceName) {
        onPlay && onPlay(item);
      }
    }
  };
  const handleDeleteItem = (item: TVoiceItem) => {
    if (voices.length <= 1) {
      return;
    }
    if (!item.canDel) {
      Taro.showToast({ title: "该声音无法删除" });
      return;
    }
    showModal({
      content: "确认删除该声音？",
      onConfirm: async () => {
        const response = await deleteVoice(item.voiceId);
        if (isSuccess(response.status)) {
          await mutate();
          syncDefaultVoice(item);
        }
      },
    });
  };

  // 克隆按钮状态
  const handleCloneStatus = (status: ECloneStatus) => {
    console.log(status);
  };

  const fetchVoiceList = async (taskId: string) => {
    const response = await getVoiceStatus(taskId);
    console.log(response.data);
    if (response.data.status === "processing") {
      setCloning({
        message: response.data.message,
        status: response.data.status,
        taskId: response.data.taskId,
      });
      intervalRef.current = setTimeout(() => fetchVoiceList(taskId), 3000);
      return;
    }
    if (
      response.data.status === "process_fail" ||
      response.data.status === "success"
    ) {
      setCloning({
        message: response.data.message,
        status: response.data.status,
        taskId: response.data.taskId,
      });
      stopTimer();
      await mutate();
      setCloning(null);
    }
  };

  // 声音录制完成
  const onRecordEnd = (taskId: string) => {
    console.log("onRecordEnd:", taskId);
    fetchVoiceList(taskId);
  };

  const stopTimer = () => {
    if (intervalRef.current !== null) {
      clearTimeout(intervalRef.current);
      intervalRef.current = null;
    }
  };

  const onScrollToLower = () => {
    loadMore();
  };

  // 清除定时器
  useEffect(() => {
    return () => {
      stopTimer();
    };
  }, []);

  const createSliderButtons = (item: TVoiceItem) => {
    return [
      {
        text: "删除",
        color: "#FF8200",
        onClick: () => {
          handleDeleteItem(item);
        },
      },
    ];
  };

  // 克隆列表右侧操作栏
  const renderRightColumn = (item: TVoiceItem) => {
    if (item.status == EVoiceStatus.DONE) {
      return (
        <View className="flex items-center h-full">
          <View
            className="text-primary px-12 text-12"
            onClick={(e) => handleTry(e, item)}
          >
            试听
          </View>
          <WemetaRadio checked={item.voiceId === agent?.voiceId}></WemetaRadio>
        </View>
      );
    }

    return <></>;
  };

  // 克隆状态栏
  const renderCloneStatus = (item: TTask) => {
    if (item.status === "success") {
      return (
        <View className={`text-12 leading-20 text-green`}>{item.message}</View>
      );
    }
    if (item.status === "processing") {
      return (
        <View className={`text-12 leading-20 text-primary`}>
          {item.message}
          <ThinkingAnimation />
        </View>
      );
    }

    if (item.status === "process_fail") {
      return (
        <View className={`text-12 leading-20 text-orange`}>{item.message}</View>
      );
    }
    console.log(item.status);
    return <></>;
  };

  const renderItem = (_item: TVoiceItem|TTask, isLast: boolean) => {
    if (('taskId' in _item) && _item.taskId) {
      return (
        <CardListItem
          underline
          className="px-16"
          leftRenderer={() => {
            return (
              <View className={style.listIcon}>
                <Image src={IconWave} className={style.iconImage}></Image>
              </View>
            );
          }}
        >
          <View className="flex items-center h-full py-16">
            {renderCloneStatus(_item as TTask)}
          </View>
        </CardListItem>
      );
    }
    const item = _item as TVoiceItem
    return (
      <SliderAction actions={createSliderButtons(item)}>
        <CardListItem
          underline={!isLast}
          className="px-16"
          leftRenderer={() => {
            return (
              <View className={style.listIcon}>
                <Image src={IconWave} className={style.iconImage}></Image>
              </View>
            );
          }}
          rightRenderer={() => {
            return renderRightColumn(item);
          }}
          onClick={() => handleSelect(item)}
        >
          <View className="flex flex-col gap-4 py-16">
            <View className="flex items-center leading-22">
              {item.voiceName}
            </View>
            <View className="text-12 text-gray-4 leading-20">
              {item.createTime.slice(0, 7)} 创建
            </View>
          </View>
        </CardListItem>
      </SliderAction>
    );
  };

  // 渲染克隆列表
  const renderClonedList = () => {
    //
    const voices = cloning ? [cloning, ...list] : list;
    if (!voices.length) {
      return <EmptyData type={"search"}></EmptyData>;
    }
    return (
      <View className="flex flex-col w-full">
        {voices.map((item, index, array) => {
          return renderItem(item, (index === array.length -1));
        })}
      </View>
    );
  };

  return (
    <View className={`flex flex-col flex-1 h-full`}>
      <View className="flex-1 h-full overflow-hidden bg-white rounded-bl-12 rounded-br-12">
        <ScrollView
          scrollY
          onScrollToLower={onScrollToLower}
          className="flex-1"
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          {renderClonedList()}
        </ScrollView>
      </View>
      <View
        className="button-rounded button-primary mt-16"
        onClick={() =>setShow(true)}
      >
        添加克隆声音
      </View>


      <Popup show={show} setShow={setShow}>
        <PopupRecorder
          onRecordEnd={onRecordEnd}
          show={show}
          entId={agent?.entId || 0}
          setShow={setShow}
          setCloneStatus={(status) => handleCloneStatus(status)}
        ></PopupRecorder>
      </Popup>
    </View>
  );
};
