import { useState } from "react";
import { View } from "@tarojs/components";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import BottomBar from "@/components/BottomBar";
import WemetaButton from "@/components/buttons/WemetaButton";
import { useComponentStore } from "@/store/componentStore";
import Taro, { useUnload } from "@tarojs/taro";
import WemetaTextarea from "@/components/wemeta-textarea/index";
import { EComponentType } from "@/consts/enum";

export default function Index() {

  let currentComponent = useComponentStore((state)=>  state.currentComponent);

  const { saveComponent } = useComponentStore();
  const loading = useComponentStore((state)=> state.loading);
  const [value, setValue] = useState<string>(currentComponent?.data?.text ?? '');
  const placehoder = currentComponent?.data?.placeholder ?? '点击编辑输入您的文本内容';


  const handleSubmit = async () => {

    if(loading){
      return;
    }
    if(!currentComponent?.data.id){
      return
    }

    const c = {
      data: {
        text: value,
        layout: currentComponent?.data?.layout ?? 'center',
        id: currentComponent?.data.id,
        index: currentComponent?.data?.index,
      },
      enabled: currentComponent?.enabled ?? true,
      type: EComponentType.text,
    };


    await saveComponent(c)

    Taro.navigateBack()
  };


  const onChange = (e: any) => {
    setValue(e);
  };





  return (
    <PageCustom bgColor="global-light-green-bg">
      <NavBarNormal>文本内容</NavBarNormal>
      <View className="flex flex-col items-center w-full">
        <View className="w-full p-16">
          <WemetaTextarea
              value={value}
              onInput={(value: any) => onChange(value)}
              placeholder={placehoder}
              cursorSpacing={100}
              maxlength={2000}
            />
        </View>
        <BottomBar>
          <WemetaButton className="flex-1" disabled={!value.length} onClick={handleSubmit}>保存</WemetaButton>
        </BottomBar>
      </View>
    </PageCustom>
  );
}
