import { Image, View } from "@tarojs/components";
import { useAppStore } from "@/store/appStore";
import Popup from "@/components/popup/popup";
import { useState } from "react";
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";
import { TAgentDetail } from "@/types/agent";

interface IProps {
  show: boolean;
  setShow: (show: boolean) => void;
  isVisitor?: boolean
  agent: TAgentDetail
}
export default ({ show, setShow, agent, isVisitor }: IProps) => {
  const isMine = (!isVisitor)
  const { setValue, submit } = useEditContactCard(
    "qrCodeUrl",
    agent?.qrCodeUrl
  );
  const handleClick = async () => {
    Taro.showLoading();
    try{
      const result = await pickAndUploadImageWithCrop(["album"]);
      Taro.hideLoading()
      if (!result?.url) {
        return;
      }
      setValue(result.url);

      submit(result.url);

    }catch(e:any){
      Taro.hideLoading()
    }
  };

  const handleClear = () => {
    setValue('');

    submit('');
  }

  const renderQrcode = () => {
    if (agent?.qrCodeUrl) {
      return <Image src={agent?.qrCodeUrl} showMenuByLongpress mode="widthFix"></Image>;
    }

    if(isMine){
      return (
        <View onClick={handleClick}>
          <QrcodeUploadTips />
        </View>
      );
    }
    return <></>;
  };

  return (
    <View className="relative">
      <Popup setShow={setShow} show={show} title="二维码">
        <View className={style.container}>
          <View className={style.card}>
            {renderQrcode()}
          </View>

          {isMine && <View className={style.bottomButtons}>
            <View className="pr-16" onClick={handleClick}>替换</View>
            <View className="text-gray-3">|</View>
            <View className="pl-16" onClick={handleClear}>清空</View>
          </View>}
        </View>
      </Popup>
    </View>
  );
};
