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

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import style from "./index.module.less";

import QrcodeUploadTips from "@/components/qrcode-upload-tips";
import useEditContactCard from "@/hooks/useEditContactCard";
import { useAgentStore } from "@/store/agentStore";
import { pickAndUploadImageWithCrop } from "@/utils/upload";
import Taro from "@tarojs/taro";

export default function Index() {
  const agentContactCard = useAgentStore((state) => state.agentContactCard);
  const { value, setValue, handleSubmit } = useEditContactCard(
    "qrCodeUrl",
    agentContactCard?.qrCodeUrl
  );
  const handleClick = async () => {
    Taro.showLoading();
    try{
      const result = await pickAndUploadImageWithCrop(["album"]);
      
      Taro.hideLoading();
      if (!result?.url) {
        return;
      }
      setValue(result.url);
    }catch(e:any){
      Taro.hideLoading();
    }
  };

  const handleClear = () => {
    setValue("");
  };

  const renderQrcode = ()=> {
    if(value.length){
      return <Image showMenuByLongpress style={{maxWidth: '344px'}} src={value} mode="widthFix"></Image>
    }
    return <View>
      <QrcodeUploadTips />
    </View>      
  }

  return (
    <PageCustom>
      <NavBarNormal backText="我的二维码"></NavBarNormal>
      <View className="px-16 pt-4">
        <View className={style.card} onClick={handleClick}>
          {renderQrcode()}
        </View>
        <View className="flex flex-col gap-12">
          <View className="button-rounded-big" onClick={handleSubmit}>
            保存
            {/* {!!value.length ? "更新" : "保存"} */}
          </View>
          {!!value.length && <View
            className="button-rounded-big button-plain button-warn"
            onClick={handleClear}
          >
            清除
          </View>}
        </View>
      </View>
    </PageCustom>
  );
}
