import { useState } from "react";
import { View, Text, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import WemetaTextarea from "@/components/wemeta-textarea/index";
import WemetaInput from "@/components/wemeta-input/index";

import editorStyle from "../editor.module.less";
import style from "./index.module.less";

import BottomBar from "@/components/BottomBar";
import KnowledgePicker from '@/components/KnowledgePicker'
import { useComponentStore } from "@/store/componentStore";
import { uploadImage } from "@/utils/http";
import { EComponentType, EKnowlegeTypes } from "@/consts/enum";
import { TKnowledgeItem } from "@/types/knowledge";
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 { link, text, layout, poster } = data;

  const [linkValue, setLinkValue] = useState(link ?? "");
  const [linkText, setLinkText] = useState(text ?? "");
  const [linkPoster, setLinkPoster] = useState(poster ?? "");

  const [showPopup, setShowPopup] = useState(false);
  

  

  const handleAddPoster = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      async success(chooseImageRes) {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        const res = await uploadImage(tempFilePaths[0]);
        if (res?.publicUrl) {
          setLinkPoster(res.publicUrl);
        }
      },
    });
  };

  // 选择知识库导入
  const onPicked = (pickedArr?: TKnowledgeItem[]) => {
    const picked = pickedArr?.[0]
    if(picked){
      setLinkValue(picked.linkUrl)
      setLinkText(picked.title)
      if(picked.picUrl){
        setLinkPoster(picked.picUrl)
      }
    }
  }

  // 显示知识库导入弹层
  const showKnowlegePopup = ()=> {
    setShowPopup(true)
  }

  const handleSubmit = async () => {
    if(!data?.id){
      return;
    }
    if (loading) {
      return;
    }
    const c = {
      data: {
        link: linkValue,
        text: linkText,
        layout: layout ?? 'center',
        poster: linkPoster,
        linkType: data.linkType,
        id: currentComponent?.data.id,
        index: currentComponent?.data?.index,
      },
      enabled: currentComponent?.enabled ?? true,
      type: EComponentType.link,
    };

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

  // 渲染封面
  const renderPoster = (src?: string) => {
    if (src) {
      return (
        <View className="w-full overflow-hidden">
          <Image className={style.cover} mode="widthFix" 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">
          上传展示图
        </View>
      </>
    );
  };


  

  return (
    <PageCustom>
      <NavBarNormal>链接</NavBarNormal>
      <View className="flex flex-col items-center w-full">
        <View className="px-16 w-full pb-120">
          

          <View className={editorStyle.formContainer}>
            <View className={editorStyle.formItem}>
              <View className={editorStyle.formItemLabel}>
                <View className="flex flex-1 items-center">
                  <View className={editorStyle.formLabel}>链接地址</View>
                  <View className={editorStyle.formLabelRequired}>*</View>
                </View>
                <View className="text-primary" onClick={showKnowlegePopup}>知识库导入</View>
              </View>
              <WemetaTextarea
                value={linkValue}
                onInput={(value: string) => setLinkValue(value)}
                placeholder="请输入URL..."
              ></WemetaTextarea>
            </View>
            <View className={editorStyle.formItem}>
              <View className={editorStyle.formItemLabel}>
                <View>链接描述<Text className="text-gray-45">(选填)</Text></View>
              </View>
              <WemetaInput
                value={linkText}
                onInput={(value: string) => setLinkText(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}
              >
                {renderPoster(linkPoster)}
              </View>
            </View>
          </View>
        </View>
        <BottomBar>
          <View className="button-rounded button-primary flex-1" onClick={handleSubmit}>保存</View>
        </BottomBar>
      </View>
      
      <KnowledgePicker types={[EKnowlegeTypes.web]} onPicked={onPicked} setShow={setShowPopup} show={showPopup}></KnowledgePicker>
      
    </PageCustom>
  );
}
