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 editorStyle from "../editor.module.less";
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 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="文本内容"
              cursorSpacing={100}
              maxlength={2000}
            />
        </View>
        <BottomBar>
          <View className="button-rounded button-primary flex-1" onClick={handleSubmit}>保存</View>
        </BottomBar>
      </View>
    </PageCustom>
  );
}
