import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";
import WidgetCard from "@/components/widgets/widget-card/index";
import WidgetContent from "@/components/widgets/widget-content/index";
import WidgetMap from "@/components/widgets/widget-map/index";
import PopupLinkCopyer from "@/components/popup-link-copyer";
import type {
  TEntityComponent,
  TSocialMediaItem,
} from "@/types/index";
import { SocialMediaType } from "@/consts/socialMedia";
import { useComponentStore } from "@/store/componentStore";
import NewCompButton from "./components/new-comp-button/index";
import SocialMedia from "./components/social-media";
import CardTitle from "./components/card-title/index";
import CardContacts from "./components/card-contacts/index";
import CardTel from "./components/card-tel/index";
import CardChannels from "./components/card-channels/index";
import CardMedia from "./components/card-media/index";
import CardMiniProgram from "./components/card-mini-program/index";
import CardLink from "./components/card-link/index";


import { TComponentItem } from "@/types/agent";

import { useAddress } from './components/address'
import { EComponentType } from "@/consts/enum";

interface Props {
  components: TComponentItem[];
  editMode?: boolean;
}
export default ({ components, editMode = false }: Props) => {
  const {
    delComponent,
    setCurrentComponent,
    setInsertIndex,
    swapTwoComponent,
    saveComponent,
  } = useComponentStore();

  const [show, setShow] = useState(true);


  const [currentMediaItem, setCurrentMediaItem] =
    useState<TSocialMediaItem | null>(null);
  const [currentLink, setCurrentLink] = useState("");

  const {handleChooseAddress, openNavigation} = useAddress()

  const handleMapClick = (editMode:boolean, c: TComponentItem)=> {
    if(editMode){
      handleChooseAddress(c.data, c)
    }else{
      openNavigation(c.data)
    }
  }

  const showMediaLink = (mediaItem: TSocialMediaItem, link: string, c: TEntityComponent) => {
    console.log(c,  SocialMediaType.shiping.value, link)
    // 微信公众号直接跳转
    if(c?.type === SocialMediaType.wechat.value){
      // 跳转的公众号需与小程序为同主体或关联主体
      //@ts-ignore
      // wx.openOfficialAccountProfile({
      //   username: c.data?.value,
      //   success: () => {},
      //   fail: (res) => {
      //     console.log(res)
      //     // 如果失败，则显示复制框
      //     setCurrentMediaItem(mediaItem);
      //     setCurrentLink(link);
      //     setShow(true);
      //   },
      // })
      return
    }
    // 视频号不显示复制框，直接跳转
    if(c?.type === SocialMediaType.shiping.value){
      Taro.openChannelsUserProfile({
        finderUserName: link
      })
      return
    }
    
    setCurrentMediaItem(mediaItem);
    setCurrentLink(link);
    setShow(true);
  };
  
  const handleDelete = (c: TComponentItem) => {
    
    delComponent(c);
  };
  const handleNavigate = (c: TComponentItem, url: string) => {
    setInsertIndex(-1);
    setCurrentComponent(c);
    let _url = url;
    if (_url.indexOf("?") > -1) {
      _url += `&id=${c.data.id}`;
    } else {
      _url += `?id=${c.data.id}`;
    }
    Taro.navigateTo({ url: _url });
  };

  

  

  const handleSort = async (c: TComponentItem, direction: number) => {
    console.log(c, direction)
    await swapTwoComponent(c, direction);
  };

  const handleSwitchChanged = (c: TComponentItem, checked: boolean) => {
    saveComponent({
      ...c,
      enabled: checked,
    });
  };
  const changeStyle = (c: TComponentItem) => {
    console.log(c)
    saveComponent({
      ...c,
    });
  };

  const handleCreateNew = (index: number) => {
    setInsertIndex(index);
    setCurrentComponent(null);
    Taro.navigateTo({
      url: "/pages/component-library/index",
    });
  };

  // 添加组件
  const renderNewCompButton = (index: number) => {
    return (
      <View onClick={() => handleCreateNew(index)}>
        <NewCompButton index={index}></NewCompButton>
      </View>
    );
  };


  
  // 渲染组件列表
  const renderComponents = () => {
    if (!components) {
      return <></>;
    }

    let componentsWithJSX = components
      .map((c: TComponentItem, index: number) => {
        if (!c.data) {
          return undefined;
        }
        // 视频号视频
        if(c.type === EComponentType.shipingVideo){
          return {
            component: c,
            renderer: (
              <CardChannels
                  index={index}
                  onSwitchChanged={handleSwitchChanged}
                  components={components}
                  component={c}
                  editMode={editMode}
                  onDelete={handleDelete}
                  onMove={handleSort}
                  onClick={handleNavigate}
              ></CardChannels>
            ),
          };
        }
        // 小程序链接
        if(c.type === 'miniProgram'){
          return {
            component: c,
            renderer: (
              <CardMiniProgram
                  index={index}
                  onSwitchChanged={handleSwitchChanged}
                  components={components}
                  component={c}
                  editMode={editMode}
                  onDelete={handleDelete}
                  onMove={handleSort}
                  onClick={handleNavigate}
              />
            ),
          };
        }
        
        // 联系人
        if(c.type === "bluebook"){
          return {
            component: c,
            renderer: (
              <CardContacts
                index={index}
                key={c.data.id}
                component={c}
                components={components}
                onSwitchChanged={handleSwitchChanged}
                editMode={editMode}
                onDelete={handleDelete}
                onMove={handleSort}
                onStyleChanged={changeStyle}
                onClick={() =>
                  editMode &&
                  handleNavigate(
                    c,
                    `/pages/editor-pages/editor-link-contact/index`
                  )
                }
              ></CardContacts>
            ),
          };
        }
        
        // 社交媒体组件
        if (c?.type && SocialMediaType[c?.type]) {
          
          const { value } = SocialMediaType[c.type];
          return {
            component: c,
            renderer: (
              <SocialMedia 
                  index={index}
                  mediaItem={SocialMediaType[c.type]}
                  onSwitchChanged={handleSwitchChanged}
                  component={c}
                  components={components}
                  editMode={editMode}
                  onDelete={handleDelete}
                  onClick={() =>
                    editMode &&
                    handleNavigate(
                      c,
                      `/pages/editor-pages/editor-link-social/index?mediaType=${value}`
                    )
                  }
                  onMove={handleSort}
                  showMediaLink={(mediaItem, link)=> showMediaLink(mediaItem, link, c)}
                  onStyleChanged={changeStyle}
              ></SocialMedia>
            ),
          };
        }
        // 标题组件
        if (c.data && c.type === "title") {
          return {
            component: c,
            renderer: (
              <CardTitle
                onSwitchChanged={handleSwitchChanged}
                index={index}
                component={c}
                components={components}
                editMode={editMode}
                onDelete={handleDelete}
                onMove={handleSort}
                onStyleChanged={changeStyle}
              >
              </CardTitle>
            ),
          };
        }
        // 文本组件
        if (c.type === "text") {
          return {
            component: c,
            renderer: (
              <>
                <WidgetCard
                  index={index}
                  enabled={c.enabled}
                  onSwitchChanged={(checked) => handleSwitchChanged(c, checked)}
                  components={components}
                  editMode={editMode}
                  onDelete={() => handleDelete(c)}
                  onMove={(direction) => handleSort(c, direction)}
                  onChanged={()=> {
                    if(c.data?.layout === 'center'){
                      changeStyle({...c, data: {...c.data, layout: 'left'}})
                    }else{
                      changeStyle({...c, data: {...c.data, layout: 'center'}})
                    }
                  }}
                >
                  <WidgetContent
                    editMode={editMode}
                    onClick={() =>
                      editMode &&
                      handleNavigate(
                        c,
                        `/pages/editor-pages/editor-textarea/index`
                      )
                    }
                    center={c.data.layout === "center"}
                    data={c}
                  >
                    {c.data.text.length <= 0 ?  c.data.placeholder : c.data.text}
                  </WidgetContent>
                </WidgetCard>
              </>
            ),
          };
        }

        
        // 普通链接及公众号文章
        if (c.type === 'link' || c.type === 'wechatArticle') {
          
          return {
            component: c,
            renderer: (
              <CardLink
                  index={index}
                  onSwitchChanged={handleSwitchChanged}
                  components={components}
                  component={c}
                  editMode={editMode}
                  onDelete={handleDelete}
                  onMove={handleSort}
                  onStyleChanged={changeStyle}
                  onClick={(c, link, mediaItem) =>{
                    if(editMode){
                      handleNavigate(
                        c,
                        `/pages/editor-pages/editor-link/index?linkType=${c.data.linkType}&title=${c.data.title}`,
                      )
                    }else{
                      
                      showMediaLink(mediaItem, link, c)
                    }
                  }}
              ></CardLink>
            ),
          };
        }

        

        
        // 电话
        if (c.type === "tel") {
          return {
            component: c,
            renderer: (
              <CardTel 
              index={index}
              onSwitchChanged={handleSwitchChanged}
              component={c}
              components={components}
              editMode={editMode}
              onDelete={handleDelete}
              onClick={() =>
                editMode &&
                handleNavigate(
                  c,
                  `/pages/editor-pages/editor-tel/index`
                )
              }
              onMove={handleSort}
              onStyleChanged={changeStyle}
              ></CardTel>
            ),
          };
        }

        // 图片/视频
        if (c.type === "media") {
          return {
            component: c,
            renderer: (
              <>
                <CardMedia
                  index={index}
                  component={c}
                  onSwitchChanged={handleSwitchChanged}
                  components={components}
                  editMode={editMode}
                  onDelete={() => handleDelete(c)}
                  onClick={() =>
                    editMode &&
                    handleNavigate(c, "/pages/editor-pages/editor-media/index")
                  }
                  onMove={handleSort}
                  onStyleChanged={changeStyle}
                >
                </CardMedia>
              </>
            ),
          };
        }

        if (c.type === "address") {
          return {
            component: c,
            renderer: (
              <>
                <WidgetCard
                  index={index}
                  enabled={c.enabled}
                  disableChangeStyle
                  onSwitchChanged={(checked) => handleSwitchChanged(c, checked)}
                  components={components}
                  editMode={editMode}
                  onDelete={() => handleDelete(c)}
                  onClick={() =>
                    handleMapClick(editMode, c)
                  }
                  onMove={(direction) => handleSort(c, direction)}
                >
                  <WidgetMap
                    latitude={c.data.latitude}
                    longitude={c.data.longitude}
                    name={c.data.name}
                    address={c.data.address}
                  >
                    {c.data.name}
                  </WidgetMap>
                  
                </WidgetCard>
              </>
            ),
          };
        }
      })
      .filter((item) => !!item);
    
    // 如果是编辑模式则显示 “添加组件” 按钮
    if (editMode) {
      const _components: JSX.Element[] = [renderNewCompButton(-1)];
      for (let i = 0; i < componentsWithJSX.length; i++) {
        _components.push(componentsWithJSX[i].renderer);
        const index = componentsWithJSX[i].component.data.index ?? 0;
        _components.push(renderNewCompButton(index));
      }
      return _components;
    }
    return componentsWithJSX.map((item) => item.renderer);
  };
  
  return (
    
    <>
      {currentMediaItem && (
        <PopupLinkCopyer
          mediaItem={currentMediaItem}
          show={show}
          setShow={setShow}
          link={currentLink}
        />
      )}
      {renderComponents()}
    </>
  );
};
