import WemetaTabs from "@/components/wemeta-tabs/index";
import VoicePlayerBar, { IVoicePlayerBar } from "@/components/voice-player-bar";
import VoiceList from "./components/VoiceList";
import MyVoiceList from "./components/MyVoiceList/index";
import { View, ScrollView } from "@tarojs/components";
import React, { useEffect, useRef, useState } from "react";
import NavBarNormal from "@/components/NavBarNormal/index";
import style from "./index.module.less";
import PageCustom from "@/components/page-custom/index";
import { useVoiceStore } from "@/store/voiceStore";
import { TVoiceItem } from "@/types/voice";
import { useAgentStore } from "@/store/agentStore";

interface Props {}

const VoiceTabs: React.FC<Props> = ({}) => {
  const playerRef = useRef<IVoicePlayerBar>(null);
  const [sysVoice, setSysVoice] = useState<TVoiceItem | null>(
    null
  );

  const {agent, agentCharacter, editAgentCharacter} = useAgentStore()

  const {
    voices,
    femaleVoices,
    femalePagination,
    maleVoices,
    malePagination,
    isLoading,
    pagination,
    getVoices,
    getFemaleVoices,
    getMaleVoices,
    setPagination,
    setMalePagination,
    setFemalePagination,
    
  } = useVoiceStore();

  const handleScrollEnd = () => {
    if (isLoading) {
      return;
    }
    setPagination({ pageIndex: pagination.pageIndex + 1 });
  };

  useEffect(() => {
    getVoices();
  }, []);

  // 获取女声列表
  useEffect(() => {
    getFemaleVoices();
  }, []);

  // 获取男声列表
  useEffect(() => {
    getMaleVoices();
  }, []);

  // 处理滚动加载更多
  const handleFemaleScrollEnd = () => {
    if (isLoading) return;
    setFemalePagination({ pageIndex: femalePagination.pageIndex + 1 });
  };

  // 处理滚动加载更多
  const handleMaleScrollEnd = () => {
    if (isLoading) return;
    setMalePagination({ pageIndex: malePagination.pageIndex + 1 });
  };

  // 保存默认 voiceId
  const saveAgentVoiceId = async (voiceItem: TVoiceItem) => {
    if(!agent?.agentId || !voiceItem?.voiceId || !agentCharacter){
      return
    }
    const result = await editAgentCharacter(agent?.agentId, {
      ...agentCharacter,
      voiceId: voiceItem.voiceId
    })
    console.log(result)
  }

  // 设置当前播放器的播放音频信息
  const setPlayerItem = async (voiceItem: TVoiceItem, type: "system" | "cloned") => {
    if(playerRef.current){
      playerRef.current.stop();
      playerRef.current.play(voiceItem.voiceUrl)
    }
    setSysVoice(voiceItem);
    saveAgentVoiceId(voiceItem)
  };

  const tabList = [
    {
      label: "我的",
      key: "1",
      children: (
        <View className={style.tabContent}>
          <MyVoiceList
          agent={agent}
          onPlay={(item) => {
            console.log(item,'cloned')
            setPlayerItem(item, "cloned");
          }}
          ></MyVoiceList>
        </View>
      ),
    },
    {
      label: "全部",
      key: "2",
      children: (
        <View className={style.tabContent}>
          <ScrollView
            scrollY
            id="scrollView"
            onScrollEnd={handleScrollEnd}
            style={{
              flex: 1,
              height: "100%", // 高度自适应
            }}
          >
            <View className="px-16 py-12">
              <VoiceList
                agent={agent}
                list={voices}
                onPlay={(item) => {
                  setPlayerItem(item, "system");
                }}
              ></VoiceList>
            </View>
          </ScrollView>
        </View>
      ),
    },
    {
      label: "女声",
      key: "3",
      children: (
        <View className={style.tabContent}>
          <ScrollView
            scrollY
            id="scrollView"
            onScrollEnd={handleFemaleScrollEnd}
            style={{
              flex: 1,
              height: "100%", // 高度自适应
            }}
          >
            <View className="px-16 py-12">
              <VoiceList
                agent={agent}
                list={femaleVoices}
                onPlay={(item) => {
                  setPlayerItem(item, "system");
                }}
              ></VoiceList>
            </View>
          </ScrollView>
        </View>
      ),
    },
    {
      label: "男声",
      key: "4",
      children: (
        <View className={style.tabContent}>
          <ScrollView
            scrollY
            onScrollEnd={handleMaleScrollEnd}
            style={{
              flex: 1,
              height: "100%", // 高度自适应
            }}
          >
            <View className="px-16 py-12">
              <VoiceList
                agent={agent}
                list={maleVoices}
                onPlay={(item) => {
                  setPlayerItem(item, "system");
                }}
              ></VoiceList>
            </View>
          </ScrollView>
        </View>
      ),
    },
  ];

  

  return (
    <PageCustom>
      <NavBarNormal backText="声音"></NavBarNormal>
      <View className={style.container}>
        <View className={style.playContainer}>
          <VoicePlayerBar
            ref={playerRef}
            voiceItem={sysVoice}
          />
        </View>
        <View className={style.voiceTab}>
          <WemetaTabs
            full
            list={tabList}
            current="1"
            tabStyle="outline"
          ></WemetaTabs>
        </View>
      </View>
    </PageCustom>
  );
};

export default VoiceTabs;
