import { useMemo, useState, memo } from "react";
import { View, Image,Text } from "@tarojs/components";
import Taro from '@tarojs/taro'
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import WemetaInput from "@/components/wemeta-input/index";
import Popup from "@/components/popup/popup";
import style from './index.module.less'
import editorStyle from "../editor.module.less";
import BottomBar from "@/components/BottomBar";

import { useComponentStore } from "@/store/componentStore";
import { uploadImage } from "@/utils/http";
import { EComponentType } from "@/consts/enum";
export default function Index() {
  
  let currentComponent = useComponentStore((state)=>  state.currentComponent);
  if(!currentComponent){
    return <></>
  }
  
  const { saveComponent } = useComponentStore();
  const loading = useComponentStore((state)=> state.loading);
  const data = currentComponent.data;
  const [linkValue, setLinkValue] = useState<{
    name: string;
    shortLink: string;
    poster: string;
  }>(data.value);
  const [show, setShow] = useState(false);
  
  const setValueByKey = (key: string, v: string) => {
    setLinkValue((prev)=> {
      prev[key] = v;
      return {...prev};
    });
  };

  const handleSubmit = async () => {    
    
    if(!data?.id){
      return
    }
    if(loading){
      return;
    }
    const c = {
      data: {
        value: linkValue,
        layout: 'full',
        id: data.id,
        index: data.index,
      },
      enabled: currentComponent?.enabled ?? true,
      type: EComponentType.miniProgram,
    };
    
    const result = await saveComponent(c)
    if(result){
      Taro.navigateBack()
    }
  };


  

  
  

  const RenderPoster =  memo(({src}:{src: string})=> {
    if(src){
      console.log('render image')
      return (
        <View className="overflow-hidden">
          <Image
            className="w-160 h-160"
            mode="widthFix"
            style="height:auto"
            src={src}
          ></Image>
        </View>
      )
    }
    return (
      <>
        <View>
          <Image src='https://cdn.wehome.cn/cmn/png/100/META-H8UKVHWU-KIGP3BIL7M5AYC6XHNUA2-VDZCWI2M-O91.png' className={style.iconAdd}></Image>
        </View>
        <View className="text-gray-45 text-12 leading-20 text-center">建议上传1:1标准尺寸图</View>
      </>
    )
  })

  // useMemo 麻烦...
  const RenderPosterCached = useMemo(()=> {
    return <RenderPoster src={linkValue.poster}></RenderPoster>
  }, [linkValue.poster])
  
  const handleAddPoster = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      async success (chooseImageRes) {
        const tempFilePaths = chooseImageRes.tempFilePaths
        Taro.cropImage({
          src: tempFilePaths[0],
          cropScale: "1:1",
          success: async (cropRes) => {
            const path = cropRes.tempFilePath;
            const res = await uploadImage(path);
            if (res?.publicUrl) {
              setValueByKey('poster', res.publicUrl)
            }
          },
        });
      }
    })
  };

  const renderTips = () => {
    return (
      <>
        <View>
          🌟 <Text className="font-medium">小蓝本提示：</Text>
          <Text>打开小程序主页 - 顶部更多操作/评分入口 - 复制链接</Text>
        </View>
        <Image
          className="w-full"
          mode="widthFix"
          src="https://cdn.wehome.cn/cmn/png/102/META-H8UKWHWU-KIWQFXN9CWIKI7PA148U3-N5Z1UG4M-H7.png"
        ></Image>
      </>
    );
  };

  return (
    <PageCustom>
      <NavBarNormal>小程序链接</NavBarNormal>
      <View className="flex flex-col items-center w-full">
        <View className="px-16 pt-12 pb-120 w-full">
        <View className={editorStyle.formContainer}>
            <View className={editorStyle.formItem}>
              <View className={editorStyle.formItemLabel}>
                <View className="flex-1">小程序名称</View>
              </View>
              <WemetaInput
                value={linkValue.name}
                onInput={(value: string) => setValueByKey("name", value)}
                placeholder="请输入小程序名字..."
              />
            </View>
            <View className={editorStyle.formItem}>
              <View className={editorStyle.formItemLabel}>
                <View className="flex-1">小程序链接</View>
                <View className="text-green" onClick={()=> setShow(true)}>
                  如何获取？
                </View>
              </View>
              <WemetaInput
                value={linkValue.shortLink}
                onInput={(value: string) => setValueByKey("shortLink", value)}
                placeholder="长按粘贴小程序链接..."
              />
            </View>

            <View className={editorStyle.formItem}>
              <View className={editorStyle.formItemLabel}>
                <View className="flex-1">封面图 <Text className="text-gray-45">(选填)</Text></View>
              </View>
              <View className={`${style.coverContainer}`} onClick={handleAddPoster}>
                {RenderPosterCached}
              </View>
            </View>
            
          </View>
        </View>
      </View>

      <BottomBar>
          <View className="button-rounded button-primary flex-1" onClick={handleSubmit}>保存</View>
        </BottomBar>

      <Popup
        title='获取小程序链接'
        show={show}
        setShow={setShow}
      >
        <View className="flex flex-col gap-16 mb-88" onClick={handleAddPoster}>
          <View
            className={`flex flex-col p-12 gap-10 text-14 rounded-20 leading-22 text-gray-65 bg-gray-f8 overflow-hidden`}
          >
            {renderTips()}
          </View>
        </View>
      </Popup>
    </PageCustom>
  );
}
