import { Col, Row } from "antd";
import Checkbox from "antd/lib/checkbox/Checkbox";
import Select from "antd/lib/select";
import React, { useMemo } from "react";
import { useCallback } from "react";
import { Icon } from "../../components/Icon";
import { countryFlags, FlagIconName } from "../../components/Icon/CountryFlag";
import { Paragraph } from "../../components/Typography";
import { CountriesCurrency } from "../../constants/countries-currency";
import { selectLocalizations } from "redux/User/selector";
import { useTypedSelector } from "redux/rootReducer";
import { LocalizationItem as LocalizationItemType } from "redux/User/types";
import classNames from "classnames";
import "./CountriesLocalizationSelect.scss";
import { getCircleFlagByCode } from "utils/image";
const { Option } = Select;

interface CountriesLocalizationSelectProps {
  values?: string[];
  disabled?: boolean;
  onChange?: (items: string[]) => void;
  withFilter?: boolean;
  className?: string;
}
const CountriesLocalizationSelect = ({
  values,
  onChange,
  disabled,
  withFilter,
  className = "",
}: CountriesLocalizationSelectProps) => {
  const localizations = useTypedSelector(selectLocalizations);
  const countriesLocalizations = useMemo(() => {
    return [
      ...new Set(
        (
          localizations?.map(
            (locale: LocalizationItemType) => locale.countries
          ) || []
        ).flat(1)
      ),
    ];
  }, [localizations]);
  const countriesLocalizationSelected = useMemo(
    () => countriesLocalizations.filter((el) => !values?.includes(el)),
    [countriesLocalizations, values]
  );
  const renderCountries = useCallback(() => {
    return Object.keys(CountriesCurrency)
      .filter(
        (key) => !countriesLocalizationSelected.includes(key.toLowerCase())
      )
      .map((key) => {
        const value = key.toLowerCase();
        const isFlag = key in countryFlags;
        const isSelected = values?.includes(value);
        const flagUrl = getCircleFlagByCode(key.toLowerCase());

        return (
          <Option label={CountriesCurrency[key]} value={value} key={value}>
            <Row wrap={false} align="middle">
              <Col className="m__r--10">
                <Checkbox checked={isSelected} />
              </Col>
              <Col className="m__r--8 height--24" role="img">
                {isFlag ? (
                  <Icon width={24} height={24} name={key as FlagIconName} />
                ) : (
                  <Row
                    className="width--24 height--24 border-box "
                    align="middle"
                    justify="center"
                  >
                    <img src={flagUrl} width={24} height={24} />
                  </Row>
                )}
              </Col>
              <Col>
                <Paragraph ellipsis={{ rows: 1 }} preset="medium14">
                  {CountriesCurrency[key]}
                </Paragraph>
              </Col>
            </Row>
          </Option>
        );
      });
  }, [values]);
  const renderSelectedCountries = useCallback(() => {
    return countriesLocalizationSelected.map((item: string, index: number) => {
      const key = item.toUpperCase();
      const value = item;
      const isFlag = key in countryFlags;
      const isDisabled = true;
      const isFirst = index === 0;
      const flagUrl = getCircleFlagByCode(key);

      return (
        <Option
          label={CountriesCurrency[key]}
          value={value}
          key={value}
          className={classNames("", {
            "disabled-option": !isFirst && isDisabled,
            "selected-first p__x--0 p__b--0 pointer-none": isFirst,
          })}
        >
          <>
            {isFirst && (
              <Paragraph className="m__b--16 p__x--16" preset="semibold14">
                Countries Added to Localized Pages
              </Paragraph>
            )}
            <Row
              className={classNames({
                "disabled-option": isFirst && isDisabled,
                "p__x--16 p__b--16 border__bottom": isFirst,
              })}
              wrap={false}
              align="middle"
            >
              <Col className="m__r--8 height--24" role="img">
                {isFlag ? (
                  <Icon width={24} height={24} name={key as FlagIconName} />
                ) : (
                  <Row
                    className="width--24 height--24 border-box "
                    align="middle"
                    justify="center"
                  >
                    <img src={flagUrl} width={24} height={24} />
                  </Row>
                )}
              </Col>
              <Col>
                <Paragraph ellipsis={{ rows: 1 }} preset="medium14">
                  {CountriesCurrency[key]}
                </Paragraph>
              </Col>
            </Row>
          </>
        </Option>
      );
    });
  }, [values]);

  return (
    <Select
      showArrow
      disabled={disabled}
      value={values}
      mode="multiple"
      allowClear={false}
      style={{ width: "100%" }}
      placeholder="Search country"
      placement={withFilter ? "topLeft" : "bottomLeft"}
      onChange={onChange}
      optionLabelProp="label"
      className={classNames("contries-localization-select", className)}
      dropdownClassName="contries-localization-select-dropdown"
      suffixIcon={
        <Icon
          width={22}
          height={22}
          name={!disabled ? "search-active" : "search-disabled"}
        />
      }
      filterOption={(input, option) => {
        return (
          countriesLocalizationSelected.includes(option?.value) ||
          option?.value.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
          (option?.label as string)
            .toLowerCase()
            .indexOf(input.toLowerCase()) >= 0
        );
      }}
    >
      {renderCountries()}
      {renderSelectedCountries()}
    </Select>
  );
};

export default CountriesLocalizationSelect;
