import _ from "lodash";
import React, { useEffect, useState } from "react";
import { IconRefresh } from "../../../general/assets/images/common-icons";
import ActionsButtons from "../../../general/components/elements/ActionsButtons";
import DateNavigationBar from "../../../general/components/elements/DateNavigationBar";
import { Switch } from "../../../general/components/inputs";
import SelectGroup from "../../../general/components/inputs/SelectGroup";
import { CALL_LOGS_FILTER } from "../../../redux-toolkit/call-logs";
import { CALL_LOG_FILTER_OPTIONS } from "../../common/constants";
import useValidateCallLog from "../../hooks/useValidateCallLog";
import "./styles.scss";
// import SearchBar from "../../general/components/SearchBar";
import { useSelector } from "react-redux";
import SearchBar from "../../../general/components/SearchBar";
import { CALL_LOG_FILTER_OPTIONS_DROPDOWN } from "../../common/constants";
import { getExtensionNumber } from "../../common/utils/helper";
import { get } from "lodash";
const getCallTypeValue = (filter) => {
  if (filter[CALL_LOGS_FILTER.INCOMING].value) {
    return CALL_LOG_FILTER_OPTIONS.INCOMING.value;
  } else if (filter[CALL_LOGS_FILTER.OUTGOING].value) {
    return CALL_LOG_FILTER_OPTIONS.OUTGOING.value;
  } else {
    return CALL_LOG_FILTER_OPTIONS.SHOW_ALL.value;
  }
};
const ActionsBar = ({
  onSearch = () => {},
  filter = {},
  isSuperUser = false,
  onRefresh = () => {},
  handleChangeTextSearch = () => {},
  searchTerm = "",
  handleExtensionHandler = () => {},
  selectedExtension = null,
}) => {
  const [selectedCallOption, setSelectedCallOption] = useState(
    CALL_LOG_FILTER_OPTIONS.SHOW_ALL.value
  );
  const { isCurrentUserApiCalled } = useSelector((state) => state.user);

  const { extensions } = useSelector((state) => state.callLogs);

  const {
    formikCallLog,
    startDate,
    endDate,
    setStartDate,
    setEndDate,
  } = useValidateCallLog({
    startDate: filter[CALL_LOGS_FILTER.FROM].value,
    endDate: filter[CALL_LOGS_FILTER.TO].value,
  });

  const onSearchHandler = (params) => {
    const updatedParams = {
      ...params,
    };
    if (
      _.get(window, "user_is_super_admin", false) &&
      !params[CALL_LOGS_FILTER.EXTENSION_NUMBER]
    ) {
      updatedParams[CALL_LOGS_FILTER.EXTENSION_NUMBER] = {
        filterName: CALL_LOGS_FILTER.EXTENSION_NUMBER,
        value: selectedExtension,
      };
    }
    onSearch(updatedParams);
  };

  const handleSearchUnknownOnly = (e) => {
    const value = e.target.checked;
    onSearchHandler({
      [CALL_LOGS_FILTER.UNKNOWN]: {
        filterName: CALL_LOGS_FILTER.UNKNOWN,
        value,
      },
    });
  };

  const handleSearchFromDate = (val) => {
    setStartDate(val);
    formikCallLog.setFieldValue("startDate", val);
    formikCallLog.validateField("startDate");
  };

  const handleSearchToDate = (val) => {
    setEndDate(val);
    formikCallLog.setFieldValue("endDate", val);
    formikCallLog.validateField("endDate");
  };

  const handleDropdownChange = (option) => {
    const value = option.value;
    if (value === CALL_LOG_FILTER_OPTIONS.OUTGOING.value) {
      onSearchHandler({
        [CALL_LOGS_FILTER.OUTGOING]: {
          filterName: CALL_LOGS_FILTER.OUTGOING,
          value: true,
        },
        [CALL_LOGS_FILTER.INCOMING]: {
          filterName: CALL_LOGS_FILTER.OUTGOING,
          value: null,
        },
      });
    } else if (value === CALL_LOG_FILTER_OPTIONS.INCOMING.value) {
      onSearchHandler({
        [CALL_LOGS_FILTER.INCOMING]: {
          filterName: CALL_LOGS_FILTER.INCOMING,
          value: true,
        },
        [CALL_LOGS_FILTER.OUTGOING]: {
          filterName: CALL_LOGS_FILTER.OUTGOING,
          value: null,
        },
      });
    } else if (value === CALL_LOG_FILTER_OPTIONS.SHOW_ALL.value) {
      onSearchHandler({
        [CALL_LOGS_FILTER.INCOMING]: {
          filterName: CALL_LOGS_FILTER.INCOMING,
          value: null,
        },
        [CALL_LOGS_FILTER.OUTGOING]: {
          filterName: CALL_LOGS_FILTER.OUTGOING,
          value: null,
        },
      });
    }
  };

  const handleExtensionChange = (option) => {
    const value = option.value;
    onSearchHandler({
      [CALL_LOGS_FILTER.EXTENSION_NUMBER]: {
        filterName: CALL_LOGS_FILTER.EXTENSION_NUMBER,
        value: value,
      },
    });
    handleExtensionHandler(value);
  };

  useEffect(() => {
    if (_.isEmpty(formikCallLog.errors) && selectedExtension) {
      onSearchHandler({
        [CALL_LOGS_FILTER.FROM]: {
          filterName: CALL_LOGS_FILTER.FROM,
          value: startDate,
        },
        [CALL_LOGS_FILTER.TO]: {
          filterName: CALL_LOGS_FILTER.TO,
          value: endDate,
        },
      });
    }
  }, [
    formikCallLog.errors?.startDate,
    formikCallLog.errors?.endDate,
    selectedExtension,
  ]);

  useEffect(() => {
    if (
      (extensions?.length || extensions?.content?.length) &&
      (_.get(window, "user_is_super_admin", false) ||
        get(
          window,
          "voip_current_user_permission.view_call_logs_for_all_extensions",
          false
        )) &&
      !selectedExtension
    ) {
      const extension_number =
        extensions?.content?.length > 0
          ? extensions.content[0].basic_settings.extension_number
          : extensions[0].basic_settings.extension_number;
      handleExtensionHandler(extension_number);
    }
  }, [extensions?.length || extensions?.content?.length]);

  const onRefreshHandler = () => {
    let params = {};
    if (_.get(window, "user_is_super_admin", false)) {
      params.extension_number = selectedExtension;
    }
    onRefresh(params, isCurrentUserApiCalled);
  };

  return (
    <div className="actions-bar-container">
      <div className="actions-bar-item1 ">
        <div className="mr-10 mt--4 extension-dropdown">
          {isSuperUser ? (
            <SelectGroup
              options={getExtensionNumber(extensions || [])}
              data={selectedExtension}
              onChange={(option) => handleExtensionChange(option)}
              selectLabel="Select an extension"
              classes={{
                box: "actions-bar--extension-dropdown",
              }}
              selectGroupClass="actions-bar--extension-dropdown-select-group"
              hideDone={true}
              displayLableWithCharacterLimit={true}
              optionCustomStyle={{
                fontSize: "12px",
              }}
            />
          ) : (
            <SearchBar
              value={searchTerm}
              onChange={handleChangeTextSearch}
              customStyle={{
                minWidth: "0px",
                margin: "0px",
                lineHeight: "15px",
                marginTop: "6px",
                paddingTop: "1px",
                paddingBottom: "1px",
                fontSize: "12px",
                fontWeight: "400",
              }}
              iconClassName="icon--xs"
            />
          )}
        </div>
        <div className="date-selector-container">
          <DateNavigationBar
            fromDate={startDate}
            toDate={endDate}
            handleSearchFromDate={handleSearchFromDate}
            handleSearchToDate={handleSearchToDate}
            onLoad
          />
        </div>
      </div>

      <div className="actions-bar-item2 ">
        <div className="mr-10 mt--4 actions-bar--option-dropdown">
          <SelectGroup
            options={CALL_LOG_FILTER_OPTIONS_DROPDOWN}
            data={selectedCallOption}
            onChange={handleDropdownChange}
            selectLabel="Select Call Type"
            classes={{
              box: "actions-bar--extension-dropdown",
            }}
            selectGroupClass="actions-bar--extension-dropdown-select-group"
            hideSearch={true}
            hideDone={true}
            customOptionContainerStyle={{ height: "unset" }}
            optionCustomStyle={{
              fontSize: "12px",
            }}
          />
        </div>
        <div className="ml-10 mt-5">
          <Switch
            label="Unknown Only"
            classes={{
              label: "text--nowrap mt-10 input--call-logs-switch ",
              container: " mr-10 align-h-start",
            }}
            data={filter[CALL_LOGS_FILTER.UNKNOWN].value}
            onChange={handleSearchUnknownOnly}
            switchCustomCss={{ marginRight: "10px" }}
          />
        </div>

        <ActionsButtons
          actions={[
            {
              icon: IconRefresh,
              onClick: () => {
                onRefreshHandler();
              },
              data: null,
              tooltip: "Refresh call logs",
            },
          ]}
          classes={{
            container: "mt-4",
            icon: `${
              false
                ? "input__actions__icon-disabled input__actions__icon"
                : "input__actions__icon input--call-logs-refresh-icon"
            } icon--medium-w`,
          }}
        />
      </div>
      {/* </div> */}
    </div>
  );
};

export default ActionsBar;
