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 WidgetTypeRow from "@/components/widgets/widget-type-row/index";
import WidgetTitleRow from "@/components/widgets/widget-title-row/index";
import PopupLinkCopyer from "@/components/popup-link-copyer";
import type {
  IEntityDocument,
  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 IconMail from '@/components/icon/icon-email'
import IconBag from '@/components/icon/icon-bag'
import IconGroup from '@/components/icon/icon-group'
import IconBuilding from '@/components/icon/icon-building'
import { TComponentItem } from "@/types/agent";
import { editAgentWebsite } from "@/service/agent";

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

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

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

  

  const showMediaLink = (mediaItem: TSocialMediaItem, link: string, c: TEntityComponent) => {
    console.log(c.type,  SocialMediaType.shiping.value)
    // 视频号不显示复制框，直接跳转
    if(c?.type === SocialMediaType.shiping.value && link){
      Taro.openChannelsUserProfile({
        finderUserName: link
      })
      return
    }
    setCurrentMediaItem(mediaItem);
    setCurrentLink(link);
    setShow(true);
  };
  
  const handleDelete = (c: TComponentItem) => {
    
    delComponent(c);
  };
  const handleNavigate = (c: TEntityComponent, url: string) => {
    setInsertIndex(-1);
    setCurrentComponent(c);
    let _url = url;
    if (_url.indexOf("?") > -1) {
      _url += `&id=${c.id}`;
    } else {
      _url += `?id=${c.id}`;
    }
    Taro.navigateTo({ url: _url });
  };

  const saveAddress = async (value, component:TEntityComponent) => {
    if(!value.address.length){
      return
    }
    
    const c = {
      data: {
        address: value.address, 
        name: value.name,
        latitude: value.latitude,
        longitude: value.longitude,
      },
      enabled: component?.enabled ?? true,
      id: component?.id,
      name: component?.name ?? "地址",
      characterProfileId: component?.characterProfileId,
      type: "address",
    };

    
    await saveComponent(c)
  };

  const handleChooseAddress = async (value, c:TEntityComponent) => {
    // setInsertIndex(-1);
    // setCurrentComponent(c);
    // setMapVisible(true)

    // const option = {
    //   address:  value.address,
    //   latitude: value.latitude,
    //   longitude: value.longitude,
    //   success(result:Taro.chooseLocation.SuccessCallbackResult) {
    //       console.log(result)
    //       value = {
    //         address: result.address, 
    //         name: result.name,
    //         latitude: result.latitude,
    //         longitude: result.longitude
    //       }
    //       saveAddress(value, c)
    //   }
    // }
    // Taro.chooseLocation(option)

  };

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

  const handleSwitchChanged = (c: TEntityComponent, checked: boolean) => {
    // saveComponent({
    //   ...c,
    //   enabled: checked,
    // });
  };
  const changeStyle = (c: TEntityComponent) => {
    // 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 === 'channels'){
          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.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]) {
          console.log(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}
                  </WidgetContent>
                </WidgetCard>
              </>
            ),
          };
        }

        

        if (c.type === 'link') {
          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`,
                      )
                    }else{
                      showMediaLink(mediaItem, link, c)
                    }
                  }}
              ></CardLink>
            ),
          };
        }

        

        if (c.type === "email") {
          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'}})
                    }
                  }}
                >
                  <WidgetTypeRow
                    editMode={editMode}
                    onClick={() =>
                      editMode &&
                      handleNavigate(
                        c,
                        "/pages/editor-pages/editor-email/index"
                      )
                    }
                    type={IconMail()}
                    layout={c.data.layout}
                  >
                    {c.data.text}
                  </WidgetTypeRow>
                </WidgetCard>
              </>
            ),
          };
        }

        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={() =>
                    editMode && handleChooseAddress(c.data, 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()}
    </>
  );
};
