import React from "react";
import {
  InlineMessage,
  Input,
  InputGroupItem,
  TalentButton,
  ToastProvider,
} from "@komi-app/components";
import { useEffect, useState } from "react";
import "./Contacts.scss";
import { Link, useHistory, useLocation } from "react-router-dom";
import { services } from "services";
import ImportModule from "./ContactsImport/ImportModule";
import ContactsWithCursorTable from "./ContactsTable";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { MarketingPermission } from "@komi-app/fans-sdk";
import CustomTagsLimitError from "../Common/CustomTagLimitError";
import { useIsCustomTagsLimitCrossed } from "utils/dca/custom-tags";
import notification from "utils/notification";
import { ReviewSuccessfulState } from "pages/AudienceAndCampaigns/typesUtils";

const Contacts = ({}) => {
  const useTiers = useFeatureIsOn(FLAGS.USE_TIERS_TALENT)
  const isImportContactButtonVisible = useFeatureIsOn(
    FLAGS.FEAT_DCA_CONTACTS_IMPORT_BUTTON,
  ) || useTiers;

  const isCustomTagsEnabled = useFeatureIsOn(FLAGS.FEAT_CRM_CUSTOM_TAGS_IMPORT);

  const hasCrossedTagLimit = isCustomTagsEnabled
    ? useIsCustomTagsLimitCrossed()
    : false;

  const location = useLocation<ReviewSuccessfulState>();
  const history = useHistory();
  const [searchTerm, setSearchTerm] = useState("");
  const [searchFilter, setSearchFilter] = useState(MarketingPermission.Any);
  const [isHistoricSubmissionPresent, setHistoricSubmissionPresent] =
    useState<boolean>(false);

  /**
   * State to control the visibility of the import contact modal.
   */
  const [isImportContactModalVisible, setImportContactModalVisible] =
    useState<boolean>(false);

  /**
   * State to show the inline message when a fan import is in progress.
   * This is to prevent the user from importing contacts while an existing import is in progress.
   */
  const [isContactImportButtonDisabled, setIsContactImportButtonDisabled] =
    useState<boolean>(false);

  const handleOnKeyUpCapture = (key: any) => {
    if (key.code === "Enter") {
      setSearchTerm(key.target.value);
    }
  };

  //Handles the case when the search box is cleared.
  const onValueChange = (value: string) => {
    if (value === "") {
      setSearchTerm("");
    }
  };

  useEffect(() => {
    //If custom tags aren't enabled, we do not show a message
    if (!isCustomTagsEnabled) return;

    /**
     * wasReviewSuccessful - Coming from custom tags review page,
     * if the value of wasReviewSuccessful is true, we need to show
     * the user a success message;
     */
    const wasReviewSuccessful = Boolean(location.state?.wasReviewSuccessful);

    if (wasReviewSuccessful) {
      //Show success message to user
      notification.success({
        message: `Your tags have been saved and added to the imported contacts.`,
      });
      // Clear the state
      history.replace({
        ...location,
        state: undefined,
      });
    }
  }, []);

  /**
   * Check if there is a fan import already in progress in the database.
   */
  const hasFansImportInProgress = async () => {
    const fansImportInProgress = await services
      .fans()
      .getFansImportInProgress();
    if (fansImportInProgress.response) setIsContactImportButtonDisabled(true);
  };

  /**
   * Each time the contact-import modal is closed, check if
   * there is a fan import in progress in the database.
   */
  useEffect(() => {
    hasFansImportInProgress();
  }, [isImportContactModalVisible]);

  function startContactsImport() {
    setIsContactImportButtonDisabled(true);
    setImportContactModalVisible(true);
  }

  const hasDCMorPresavesSubmissions = async () => {
    const presaveSubmissions = await services
      .fans()
      .getDCMorPresavesSubmissions();
    const isSubmissionPresent = Boolean(presaveSubmissions);
    setHistoricSubmissionPresent(isSubmissionPresent);
  };

  useEffect(() => {
    hasDCMorPresavesSubmissions();
  }, []);

  return (
    <div className="contacts-page">
      <CustomTagsLimitError
        errorEnabled={isCustomTagsEnabled}
        hasCrossedTagLimit={hasCrossedTagLimit}
      />
      <div className="contacts-content">
        <div className="header">
          <div className="header-input search">
            <Input
              data-testid="table-filter"
              onKeyUpCapture={handleOnKeyUpCapture}
              prefixIcon="search"
              canClear={!!searchTerm}
              placeholder="Search contacts"
              onValueChange={onValueChange}
            />
          </div>

          {isImportContactButtonVisible && (
            <div className="header-input import-contacts">
              <TalentButton
                variant="primary"
                onClick={startContactsImport}
                /**
                 * Disable contact import if
                 *  contact import is in progress
                 *  OR if tags limit has been crossed
                 */
                disabled={
                  isContactImportButtonDisabled ||
                  (isCustomTagsEnabled && hasCrossedTagLimit)
                }
              >
                Import Contacts
              </TalentButton>
            </div>
          )}
        </div>
        {isHistoricSubmissionPresent && (
          <InlineMessage
            type="info"
            message={
              <>
                Data collected from pre-save campaigns and / or historical data
                capture forms can be accessed and exported{" "}
                <Link
                  data-testid="access-presaves-data-tile-message-view-records-button"
                  to={"/admin/data-export"}
                  type="inline"
                >
                  here.
                </Link>
              </>
            }
          />
        )}

        {isContactImportButtonDisabled && (
          <InlineMessage
            type="info"
            message={
              <>
                You have a contact import in progress. Refresh the page to see
                the new contacts
              </>
            }
          />
        )}
        <ToastProvider>
          {isImportContactModalVisible && (
            <ImportModule
              setModuleOpen={setImportContactModalVisible}
              setIsContactImportButtonDisabled={
                setIsContactImportButtonDisabled
              }
            />
          )}
          <ContactsWithCursorTable
            searchTerm={searchTerm}
            searchFilter={searchFilter}
          />
        </ToastProvider>
      </div>
    </div>
  );
};

export default Contacts;
