import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Col, Row } from "antd";

import DragDropContext from "components/DragDropContext";
import PortalComponent from "components/PortalComponent/PortalComponent";
import { Text } from "components/Typography";
import { useModules } from "hooks/useModules";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { Icon } from "../../../components/Icon";
import { Paragraph } from "../../../components/Typography";
import reduce from "lodash/reduce";
import ModuleEditor from "../ModuleEditor";
import { useWindowSize } from "../../../hooks";
import {
  TalentProfileModule,
  TextItem,
} from "../../../models/talent/talent-profile-module.model";
import TextModal from "components/TextModal";
import TextCardModule from "components/TextCardModule";

interface ModuleTextProps {
  module: TalentProfileModule<TextItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
  active: boolean;
}

const ModuleText: React.FC<ModuleTextProps> = ({
  module,
  dragHandleProps,
  active,
}) => {
  const profileContext = useModules();

  const [modalVisible, setModalVisible] = useState(false);
  const [modalItem, setModalItem] = useState<TextItem | undefined>(undefined);

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

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

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

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

  const onAddItemClicked = useCallback(() => {
    setModalItem(undefined);
    setModalVisible(true);
  }, []);

  const onEditItemClicked = useCallback((textItem: TextItem) => {
    setModalItem(textItem);
    setModalVisible(true);
  }, []);

  const onAddTextItem = useCallback(
    (textItem: TextItem) => {
      onEditModuleCallback({
        ...module,
        items: [textItem, ...module.items].map((item, index) => ({
          ...item,
          order: index,
        })),
        isUpdate: true,
      });

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

  const onEditTextItem = useCallback(
    (existingItem: TextItem, newItem: TextItem) => {
      const items = module.items.map((item) => {
        if (item.order === existingItem.order) {
          return { ...item, ...newItem };
        }
        return item;
      });

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

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

  const onDeleteTextItem = useCallback(
    (textItem: TextItem) => {
      const items = reduce(
        module.items,
        (results: any, item: any) => {
          if (item.order !== textItem.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={onAddItemClicked}
                >
                  <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 Item
                    </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={onAddItemClicked}
            >
              <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 Item
                </Text>
              </div>
            </Button>
          </Col>
          <Col>
            <Text preset="medium14" className="text--default opacity-6">
              {itemList.length}&nbsp;
              {itemList.length > 1 ? "item added" : "items added"}
            </Text>
          </Col>
        </Row>
        <DragDropContext
          droppableId="text-child-drop"
          listClassName="product-list"
          itemIdPrefix="text"
          direction="vertical"
          list={itemList}
          onDropEndCallback={onDropEnd}
        >
          {(dragProvided, snapshot, item, textIndex) => {
            const isRender = active ? active : textIndex < 2;

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <TextModal
          visible={modalVisible}
          existingItem={modalItem}
          onChangeVisible={setModalVisible}
          onItemAdded={onAddTextItem}
          onItemEdited={onEditTextItem}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  );
};

export default React.memo(ModuleText);
