import {
  AvailableNumbers,
  DropdownItem,
  Semantic,
  ToastProps,
  TollFreeSearchPage,
  useModal,
} from "@komi-app/creator-ui";
import { getSMSService } from "services";
import { useHistory } from "react-router-dom";

import { countriesOptions, filterOptions } from "./TollFreeConfig";
import { useState } from "react";

import { ToastContainer } from "../Toasts/ToastContainer";
import { CountryCodeFilter, PhoneNumberFilter } from "@komi-app/messaging-sdk";
import { countries } from "pages/AudienceAndCampaigns/Pages/Segments/SegmentQueryBuilderPage/BuilderPage/constants/countries";
import { parsePhoneNumber } from "libphonenumber-js";
import { dcaSettingsUrl, dcaTollFreeRegisterUrl } from "constants/dca";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

type SearchParams = {
  country: CountryCodeFilter;
  filterType: PhoneNumberFilter;
  searchValue: string;
};

const TollFreeSearch: React.FC = () => {
  const [selectedNumber, setSelectedNumber] = useState<AvailableNumbers>();
  const [isTableLoading, setIsTableLoading] = useState(false);
  const [assignDisabled, setAssignDisabled] = useState(false);
  const [toastConfig, setToastConfig] = useState<ToastProps | null>(null);
  const [isTableVisible, setIsTableVisible] = useState(false);
  const [availableNumbers, setAvailableNumbers] = useState<AvailableNumbers[]>(
    [],
  );
  const [searchParams, setSearchParams] = useState<SearchParams>({
    country: CountryCodeFilter.US,
    filterType: PhoneNumberFilter.EndsWith,
    searchValue: "",
  });
  const { Modal: ConfirmationModal, openModal, closeModal } = useModal();
  const isTollFreeRegistrationAllowed = useFeatureIsOn(
    FLAGS.FEAT_CRM_1244_TOLL_FREE_REGISTRATION,
  );
  const history = useHistory();

  const onCountrySelect = (selected: DropdownItem[]) => {
    const firstItem = selected[0];
    const value = typeof firstItem === "object" ? firstItem.value : firstItem;
    setSearchParams({ ...searchParams, country: value });
  };
  const onFilterSelect = (selected: DropdownItem[]) => {
    const firstItem = selected[0];
    const value = typeof firstItem === "object" ? firstItem.value : firstItem;
    setSearchParams({ ...searchParams, filterType: value });
  };

  const onSearchType = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      //If enter is pressed, perform search
      onSearchClick();
    } else {
      //if character is typed, updated search field.
      const target = e.target as HTMLInputElement;
      setSearchParams({ ...searchParams, searchValue: target.value });
    }
  };

  const onSearchClick = async () => {
    try {
      setIsTableLoading(true);
      setIsTableVisible(true);
      //Fetch data
      const searchResponse = await getSMSService().searchAvailableNumbers({
        countryCodeFilter: searchParams.country,
        phoneNumberFilter: searchParams.filterType,
        phoneNumberValue: searchParams.searchValue,
      });
      //Format data.

      searchResponse.data.map((value) => {
        //Get phone number in international format
        value.phoneNumber = parsePhoneNumber(
          value.phoneNumber,
        ).formatInternational();
        //Get full name from country code.
        value.countryCode = countries[value.countryCode].fullName;
      });

      //Set List
      setAvailableNumbers(searchResponse.data);
      setIsTableLoading(false);
    } catch (error) {
      setToastConfig({
        text: "Something went wrong. Please try again.",
        semantic: "error",
        showIcon: true,
        dismissible: true,
      });
      setIsTableLoading(false);
    }
  };

  const onNumberSelect = async (selectedNumber: AvailableNumbers) => {
    setSelectedNumber(selectedNumber);
    openModal();
  };

  const assignSelectedNumber = async () => {
    try {
      if (!selectedNumber) return;
      setAssignDisabled(true);
      const assignRequest = {
        countryCode: searchParams.country,
        phoneNumber: selectedNumber.phoneNumber.replaceAll(" ", ""),
      };
      await getSMSService().assignTollFreeNumber(assignRequest);
      setAssignDisabled(false);
      closeModal();

      isTollFreeRegistrationAllowed
        ? history.push(dcaTollFreeRegisterUrl)
        : history.push(dcaSettingsUrl, { hasProcuredNumber: true });
    } catch (error) {
      setAssignDisabled(false);
      closeModal();
      setToastConfig({
        text: "Something went wrong. Please try again.",
        semantic: "error",
        showIcon: true,
        dismissible: true,
      });
    }
  };
  return (
    <>
      <TollFreeSearchPage
        previousPageURL={dcaSettingsUrl}
        filterHasError={false}
        filterHelperText={""}
        availableNumbers={availableNumbers}
        isTableLoading={isTableLoading}
        countriesOptions={countriesOptions}
        filterOptions={filterOptions}
        selectedCountry={searchParams.country}
        selectedFilter={PhoneNumberFilter.EndsWith}
        onCountrySelect={onCountrySelect}
        onFilterChange={onFilterSelect}
        onNumberInput={onSearchType}
        onSearchClick={onSearchClick}
        onNumberSelect={onNumberSelect}
        isTableVisible={isTableVisible}
      />
      {toastConfig && (
        <ToastContainer {...toastConfig} setProps={setToastConfig} />
      )}
      <ConfirmationModal
        heading="Confirm your number selection"
        body={`The number you’ve selected is ${selectedNumber?.phoneNumber}.`}
        buttons={[
          {
            label: "Cancel",
            semantic: Semantic.SECONDARY,
            onClick: closeModal,
          },
          {
            label: "Confirm",
            semantic: Semantic.PRIMARY,
            onClick: assignSelectedNumber,
            disabled: assignDisabled,
          },
        ]}
        dismissible={false}
      />
    </>
  );
};

export default TollFreeSearch;
