import {
  CustomTagsReviewPage as ReviewPage,
  Page,
  useToast,
} from "@komi-app/creator-ui";
import { CustomTag } from "@komi-app/creator-ui/dist/src/screens/custom-tags/review-page/types";
import { FAN_TAG_COUNT_LIMIT } from "@komi-app/fans-sdk";
import { useEffect, useState } from "react";
import { useLocation, useHistory } from "react-router-dom";
import { getCustomTagsSDK } from "services";
import { useCustomTagQuery } from "./Utils";

/**
 * TODO
 * 4. Button do not stick to the bottom
 * @returns
 */

const CustomTagsReviewPage: React.FC = () => {
  const [tagList, setTagList] = useState<CustomTag[]>([]);
  const [totalTagCount, setTotalTagCount] = useState<number>(0);
  const [deletedTags, setDeletedTags] = useState<CustomTag[]>([]);
  const [isSaveButtonLoading, setSaveButtonLoading] = useState<boolean>(false);
  const { isLoading, ...query } = useCustomTagQuery();

  const history = useHistory();
  const location = useLocation<{ prevPath: string }>();
  const { createToast } = useToast();

  /**
   * prevPath - passed from the Link tag which caused the redirect.
   * If redirection wasn't from Link tag, user should go to contacts listing page.
   */
  const previousPageURL: string =
    location.state?.prevPath || "/admin/audience-campaigns/contacts";

  /**
   * Store Deleted tags locally.
   * They are deleted when save is pressed.
   * @param deletedTag Tag
   */
  function onDeleteTagClick(deletedTag: CustomTag) {
    const filteredTagsList = tagList.filter((tag) => tag.id !== deletedTag.id);
    const updatedDeletedTagsList = [...deletedTags, deletedTag];

    //Add tag to deleted tag list
    setDeletedTags(updatedDeletedTagsList);
    //Update tag list without the removed tag
    setTagList(filteredTagsList);
    //Total tag count reduced by 1
    setTotalTagCount(totalTagCount - 1);
  }

  /**
   * On cancel click, take user back to previous URL
   */
  function onCancelClick() {
    history.push(previousPageURL);
  }

  /**
   * Call API to delete all tag.
   */
  async function onSaveClick() {
    try {
      setSaveButtonLoading(true);

      const tagsToDelete = deletedTags.map((tag) => tag.id);

      const tagsToUpdate = tagList.map((tag) => {
        return { id: tag.id, isActive: true };
      });

      if (tagsToDelete.length)
        await getCustomTagsSDK().deleteMany({ tagIds: tagsToDelete });

      if (tagsToUpdate.length) await getCustomTagsSDK().updateMany(tagsToUpdate);

      history.push(previousPageURL, { wasReviewSuccessful: true });
    } catch (error) {
      createToast({
        text: "We couldn’t save your tags. Try again later.",
        semantic: "error",
        showIcon: true,
        dismissible: true,
        durationMs: 3000,
      });
    }
  }

  useEffect(() => {
    if (query.isSuccess && query.data) {
      const { inactiveTagsWithCount, totalTagCount } = query.data;
      setTagList(inactiveTagsWithCount);
      setTotalTagCount(totalTagCount);
    } else if (query.isError) {
      createToast({
        text: "We couldn’t load your tags. Try again later.",
        semantic: "error",
        showIcon: true,
        dismissible: true,
        durationMs: 3000,
      });
    }
  }, [query.data]);

  return (
    <Page isLoading={isLoading}>
      <ReviewPage
        totalTagCount={totalTagCount}
        isSaveLoading={isSaveButtonLoading}
        userTags={tagList}
        maximumAllowedTagsCount={FAN_TAG_COUNT_LIMIT}
        previousPageURL={previousPageURL}
        onCustomTagDeleteClick={onDeleteTagClick}
        onCancelClick={onCancelClick}
        onSaveClick={onSaveClick}
      />
    </Page>
  );
};

export default CustomTagsReviewPage;
