import { useState } from "react";
import { View } from "@tarojs/components";

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import WemetaButton from "@/components/buttons/WemetaButton";
import { useComponentStore } from '@/store/componentStore'
import BottomBar from "@/components/BottomBar";
import WemetaTextarea from "@/components/wemeta-textarea/index";
import Taro, {useRouter, useUnload} from "@tarojs/taro";
import { EComponentType } from "@/consts/enum";
export default function Index() {
  let currentComponent = useComponentStore((state)=>  state.currentComponent);
  const { saveComponent } = useComponentStore();
  const [value, setValue] = useState(currentComponent?.data?.text ?? '');


  const handleSubmit = async () => {
    if(!currentComponent?.data.id){
      return
    }
    if(value.length <= 0){
      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.title,
    };


    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}
              onBlur={(value: string) => onChange(value)}
              onInput={(value: string) => onChange(value)}
              placeholder={currentComponent?.data?.placeholder ?? ''}
              autoFocus
              maxlength={50}
            />
          </View>

        <BottomBar>
          <WemetaButton className="flex-1" disabled={!value.length} onClick={handleSubmit}>保存</WemetaButton>
        </BottomBar>
      </View>
    </PageCustom>
  );
}
