import React, { useEffect, useState } from "react";
import { TalentButton, Input } from "@komi-app/components";

import { SegmentMode } from "@komi-app/fans-sdk";

import { useHistory, useLocation } from "react-router-dom";
import { createSegmentUrl } from "utils/dca/segments";

import "./SegmentsPage.scss";
import SegmentsTable from "./SegmentsTable";
import CustomTagsLimitError from "../../Common/CustomTagLimitError";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useIsCustomTagsLimitCrossed } from "utils/dca/custom-tags";
import notification from "utils/notification";
import { ReviewSuccessfulState } from "pages/AudienceAndCampaigns/typesUtils";

const SegmentsWithCursorPage = () => {
  const location = useLocation<ReviewSuccessfulState>();
  const router = useHistory();
  const [searchTerm, setSearchTerm] = useState("");

  const isCustomTagsEnabled = useFeatureIsOn(FLAGS.FEAT_CRM_CUSTOM_TAGS_IMPORT);
  const hasCrossedTagLimit = isCustomTagsEnabled
    ? useIsCustomTagsLimitCrossed()
    : false;

  const createSegment = () => {
    router.push(createSegmentUrl({ mode: SegmentMode.Create }));
  };

  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
      router.replace({
        ...location,
        state: undefined,
      });
    }
  }, []);

  return (
    <div className="segments-page">
      <div className="segments-content">
        <CustomTagsLimitError
          errorEnabled={isCustomTagsEnabled}
          hasCrossedTagLimit={hasCrossedTagLimit}
        />
        <div className="header">
          <div className="header-input">
            <Input
              data-testid="segments-filter"
              value={searchTerm}
              onValueChange={setSearchTerm}
              prefixIcon="search"
              placeholder="Search segments"
              canClear={!!searchTerm}
            />
          </div>
          <TalentButton onClick={createSegment} variant="primary">
            NEW SEGMENT
          </TalentButton>
        </div>
        <div className="segment-list">
          <SegmentsTable
            searchTerm={searchTerm}
            onSegmentCreateClick={createSegment}
          />
        </div>
      </div>
    </div>
  );
};

export default SegmentsWithCursorPage;
