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

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import { useComponentStore } from "@/store/componentStore";
import WemetaTextarea from "@/components/wemeta-textarea/index";
import WemetaButton from "@/components/buttons/WemetaButton";
import BottomBar from "@/components/BottomBar";
import { EComponentType } from "@/consts/enum";
import Taro from "@tarojs/taro";
export default function Index() {

  let currentComponent = useComponentStore((state) => state.currentComponent);
  const { saveComponent } = useComponentStore();
  const loading = useComponentStore((state) => state.loading);
  const [value, setValue] = useState(currentComponent?.data?.text ?? "");


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

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

    await saveComponent(c);
    Taro.navigateBack();
  };



  return (
    <PageCustom>
      <NavBarNormal>电话</NavBarNormal>
      <View className="flex flex-col items-center w-full">
        <View className="w-full p-16">
          <WemetaTextarea
              value={value}
              onInput={(value: string) => onChange(value)}
              placeholder={currentComponent?.data.placeholder}
              maxlength={14}
            />
        </View>
        <BottomBar>
          <WemetaButton disabled={!value.length} className="flex-1" onClick={handleSubmit}>保存</WemetaButton>
        </BottomBar>
      </View>
    </PageCustom>
  );
}
