import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { Button, Col, Row } from "antd";
import DragDropContext from "components/DragDropContext";
import PortalComponent from "components/PortalComponent/PortalComponent";
import TikTokModal from "components/TikTokModal";
import TikTokVideoCardModule from "components/TikTokVideoCardModule";
import { Text } from "components/Typography";
import { useModules } from "hooks/useModules";
import reduce from "lodash/reduce";
import {
  TalentProfileModule,
  TikTokItem,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { useHistory } from "react-router-dom";
import { Icon } from "../../../components/Icon";
import { Paragraph } from "../../../components/Typography";
import { useWindowSize } from "../../../hooks";
import ModuleEditor from "../ModuleEditor";
import { routes, ShortVideoPage } from "../AddShortVideo/routes";

interface ModuleTikTokProps {
  module: TalentProfileModule<TikTokItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active: boolean;
}

const ModuleTikTok: React.FC<ModuleTikTokProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const profileContext = useModules();
  const [modalVisible, setModalVisible] = useState(false);
  const [modalItem, setModalItem] = useState<TikTokItem | undefined>(undefined);
  const isAutomationEnabled = useFeatureIsOn(FLAGS.SHORT_VIDEO_AUTOMATION);
  const navigate = useHistory();

  const { width } = useWindowSize();
  const isMobileStyleChangesEnabled = width && width <= 768;

  const tiktokList = useMemo(() => module.items, [module.items]);

  const onEditModuleCallback = useCallback(
    (moduleEdit: TalentProfileModule<TikTokItem>) => {
      profileContext.setModule?.(moduleEdit);
    },
    [profileContext]
  );

  const onDropEndTikTokVideos = useCallback(
    (list: TikTokItem[]) => {
      onEditModuleCallback({
        ...module,
        items: list.map((item, index) => ({ ...item, order: index })),
        isUpdate: true,
      });
    },
    [module, onEditModuleCallback]
  );

  const editModule = useCallback(() => {
    navigate.push(
      `/admin/modules/tiktok/${routes[ShortVideoPage.MANUAL_ENTRY]}?id=${module.id}`
    );
  }, [module.id, navigate]);

  const onAddVideoClicked = useCallback(() => {
    if (isAutomationEnabled) {
      editModule();
      return;
    }

    setModalItem(undefined);
    setModalVisible(true);
  }, []);

  const onEditVideoClicked = useCallback(
    (tiktok: TikTokItem) => {
      if (isAutomationEnabled) {
        editModule();
        return;
      }

      setModalItem(tiktok);
      setModalVisible(true);
    },
    [setModalVisible]
  );

  const onAddTikTokVideo = useCallback(
    (url: string) => {
      onEditModuleCallback({
        ...module,
        items: [{ url, order: module.items.length }, ...module.items],
        isUpdate: true,
      });

      setModalVisible(false);
    },
    [module, onEditModuleCallback]
  );

  const onEditTikTokVideo = useCallback(
    (existingItem: TikTokItem, url: string) => {
      const items = module.items.map((item) => {
        if (item.order === existingItem.order) {
          return { ...item, url };
        }
        return item;
      });

      onEditModuleCallback({
        ...module,
        items,
        isUpdate: true,
      });

      setModalVisible(false);
      setModalItem(undefined);
    },
    [module, onEditModuleCallback]
  );

  const onDeleteTikTokVideo = useCallback(
    (tiktok: TikTokItem) => {
      const items = reduce(
        module.items,
        (results: any, item: any) => {
          if (item.order !== tiktok.order) {
            return [...results, { ...item, order: results.length }];
          }
          return results;
        },
        []
      );

      onEditModuleCallback({
        ...module,
        items,
        isUpdate: true,
      });
    },
    [module, profileContext.setModule]
  );

  const renderContent = () => {
    if (!module.items.length) {
      return (
        <React.Fragment>
          <Row justify="center">
            <Col span={24} className="text__align--center">
              <Icon name="empty-module" />
            </Col>
            <Col span={24} className="text__align--center max-w-393">
              <Paragraph preset="semibold18" className="d--block m__b--4">
                Nothing Here Yet
              </Paragraph>
              <Paragraph preset="regular14" className="d--block text--grey4">
                Click the button below to get started
              </Paragraph>
            </Col>
            <Col span={24} className="height--32 m__t--20">
              <Row justify="center">
                <Button
                  className="add-item-btn p--0"
                  type="link"
                  onClick={onAddVideoClicked}
                >
                  <div className="d--flex justify__content--center align__items--center">
                    <Icon name="add-blue" />
                    <Text preset="semibold18" className="text--blue m__l--4">
                      Add New Video
                    </Text>
                  </div>
                </Button>
              </Row>
            </Col>
          </Row>
        </React.Fragment>
      );
    }

    return (
      <React.Fragment>
        <Row
          align="middle"
          justify="space-between"
          className={isMobileStyleChangesEnabled ? "m__b--8" : "m__b--24"}
        >
          <Col className="height--32">
            <Button
              className="add-item-btn p--0"
              type="link"
              onClick={onAddVideoClicked}
            >
              <div className="d--flex justify__content--center align__items--center">
                <Icon name="add-blue" />
                <Text preset="semibold18" className="text--blue m__l--4">
                  Add New Video
                </Text>
              </div>
            </Button>
          </Col>
          <Col>
            <Text preset="medium14" className="text--default opacity-6">
              {tiktokList.length}&nbsp;
              {tiktokList.length > 1 ? "videos added" : "video added"}
            </Text>
          </Col>
        </Row>
        <DragDropContext
          droppableId="tiktok-child-drop"
          listClassName="product-list"
          itemIdPrefix="tiktok"
          direction="vertical"
          list={tiktokList}
          onDropEndCallback={onDropEndTikTokVideos}
        >
          {(dragProvided, snapshot, item, tiktokIndex) => {
            const isRender = active ? active : tiktokIndex < 2;

            return isRender ? (
              <PortalComponent
                innerRef={dragProvided.innerRef}
                key={tiktokIndex}
                namespaceClass="product-list"
                provided={dragProvided}
                snapshot={snapshot}
                single={tiktokList?.length === 1}
              >
                <TikTokVideoCardModule
                  titleShortcut
                  disableDrag={tiktokList?.length === 1}
                  item={item}
                  onEdit={onEditVideoClicked}
                  onDelete={onDeleteTikTokVideo}
                  dragHandleProps={dragProvided.dragHandleProps || undefined}
                  module={module}
                />
              </PortalComponent>
            ) : (
              <></>
            );
          }}
        </DragDropContext>
        {!active && tiktokList.length > 2 && (
          <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
            <Text preset="medium14" className="opacity-6">
              +{tiktokList.length - 2} More
            </Text>
          </div>
        )}
      </React.Fragment>
    );
  };

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <TikTokModal
          visible={modalVisible}
          existingItem={modalItem}
          onChangeVisible={setModalVisible}
          onVideoAdded={onAddTikTokVideo}
          onVideoEdited={onEditTikTokVideo}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  );
};

export default React.memo(ModuleTikTok);
