import { Button, Col, Dropdown, List, Menu, Popover, Row, Tooltip } from "antd";
import classNames from "classnames";
import ConfirmDeleteModal from "components/ConfirmDeleteModal";
import { Icon } from "components/Icon";
import { Paragraph, Text } from "components/Typography";
import * as React from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import LocalizationCreateModal from "components/Localization/CreateModal";
import { useHistory } from "react-router-dom";
import { LocalizationItem } from "redux/User/types";
import {
  selectLocalizationActive,
  selectLocalizations,
  selectLocalizationUnpublishIds,
  selectUserData,
  selectUserState,
} from "redux/User/selector";
import { useTypedSelector } from "redux/rootReducer";
import { useDispatch } from "react-redux";
import { Alert } from "antd";
import { updateTalentProfileActions } from "redux/User/actions";
import isArray from "lodash/isArray";
import "./LocalizationSelect.scss";
import sortBy from "lodash/sortBy";
import { useAutoSave } from "hooks/useAutoSave";
const KOMI_CLOSE_WARNING_IDS = "KOMI_CLOSE_WARNING_IDS";

interface LocalizationSelectProps {
  isAnalytic?: boolean;
  className?: string;
  dropdownClassName?: string;
  value?: LocalizationItem;
  setValue?: (item: LocalizationItem) => void;
  onChange?: (item: LocalizationItem) => void;
  // onEdit?: () => void;
  onDelete?: () => void;
  onManage?: () => void;
  hideMoreOptions?: boolean;
}

const initialFormValues: LocalizationItem = {
  id: null,
  name: "",
  currency: "USD",
  countries: [],
  active: false,
  copyFrom: null,
};
const ALL_PAGES = {
  id: null,
  name: "All Pages",
  currency: "USD",
  active: true,
  countries: [],
  copyFrom: null,
  isFirstTimePublished: true,
  isPublished: false,
};
const LocalizationSelect = ({
  className,
  dropdownClassName,
  value,
  onChange,
  // onEdit,
  onDelete,
  hideMoreOptions,
  setValue,
  isAnalytic,
}: LocalizationSelectProps) => {
  const router = useHistory();
  const dispatch = useDispatch();
  const [formData, setFormData] = useState<LocalizationItem>(initialFormValues);
  const [visibleMenu, setVisibleMenu] = useState(false);
  const [visibleDelete, setVisibleDelete] = useState(false);
  const [visibleCreate, setVisibleCreate] = useState(false);
  const [edit, setEdit] = useState(false);
  const [visibleTooltip, setVisibleTooltip] = useState(false);
  const [visibleWarning, setVisibleWarning] = useState(false);
  const { onDeleteLocalization } = useAutoSave();
  const userState = useTypedSelector(selectUserState);
  const localizationUnpublishedIds = useTypedSelector(
    selectLocalizationUnpublishIds
  );
  const [visibleInfo, setVisibleInfo] = useState(false);

  // When loading the page the modules need to be filtered for the default locale
  // At this point in the code we know localization is active
  // So we send the end change method the default locale
  // This fixes a bug where all modules were being shown on profile load
  useEffect(() => {
    if (value?.id === null) {
      onChange?.(activePages[0]);
    }
  }, []);

  const localizationActive = useTypedSelector(selectLocalizationActive);
  const localizationsData = useTypedSelector(selectLocalizations);
  const user = useTypedSelector(selectUserData);

  const localizations = useMemo(() => {
    return localizationsData?.map((item) => {
      return {
        ...item,
        isPublished:
          item.isPublished &&
          isArray(localizationUnpublishedIds) &&
          !localizationUnpublishedIds?.includes(item.id),
      };
    });
  }, [localizationsData, localizationUnpublishedIds]);

  const defaultPage = useMemo(() => {
    const isUnPublished =
      !!user?.talentProfile?.versions?.length ||
      localizationUnpublishedIds?.includes(null);

    return {
      id: isAnalytic ? "default" : null,
      name: "Default",
      currency: "USD",
      active: true,
      countries: [],
      copyFrom: null,
      isFirstTimePublished: true,
      isPublished: !isUnPublished,
    };
  }, [
    localizationUnpublishedIds,
    user?.talentProfile?.versions?.length,
    isAnalytic,
  ]);

  const activePages = useMemo(() => {
    if (!localizationActive) {
      return [defaultPage];
    }
    const pages =
      sortBy(
        localizations?.filter((locale) => locale.active),
        ["name"]
      ) || [];
    return [defaultPage, ...pages];
  }, [localizations, defaultPage, localizationActive]);

  const inActivePages = useMemo(() => {
    if (!localizationActive) {
      return (
        sortBy(
          localizations?.filter((locale) => {
            return locale.isFirstTimePublished;
          }),
          ["name"]
        ) || []
      );
    }
    return (
      sortBy(
        localizations?.filter((locale) => {
          if (isAnalytic) {
            return !locale.active && locale.isFirstTimePublished;
          }
          return !locale.active;
        }),
        ["name"]
      ) || []
    );
  }, [localizations, isAnalytic, localizationActive]);

  useEffect(() => {
    if (isAnalytic) {
      return;
    }
    if (!value?.id) {
      setValue?.(defaultPage);
      return;
    }
    const isExistActive = activePages.some((el) => el.id === value?.id);

    if (isExistActive) {
      setValue?.(activePages.find((el) => el.id === value?.id) || defaultPage);
      return;
    }
    const isExistInActive = inActivePages.some((el) => el.id === value?.id);

    if (isExistInActive) {
      setValue?.(
        inActivePages.find((el) => el.id === value?.id) || defaultPage
      );
      return;
    }
    if (!isExistActive && !isExistInActive) {
      setValue?.(defaultPage);
    }
  }, [defaultPage, activePages, inActivePages]);

  const handleClickItem = useCallback(
    (item: LocalizationItem) => () => {
      onChange?.(item);
      setVisibleTooltip(false);
    },
    [onChange]
  );
  useEffect(() => {
    if (value && !value?.active && !value?.isFirstTimePublished) {
      const data = localStorage.getItem(KOMI_CLOSE_WARNING_IDS);
      const ids = data ? JSON.parse(data)?.ids : [];
      if (ids.includes(value?.id)) {
        setVisibleWarning(false);
        return;
      }
      setVisibleWarning(true);
      return;
    } else {
      setVisibleWarning(false);
    }
  }, [value]);
  const handleCloseWarning = useCallback(() => {
    if (!value?.id) {
      return;
    }
    const data = localStorage.getItem(KOMI_CLOSE_WARNING_IDS);
    const ids = data ? JSON.parse(data)?.ids : [];
    localStorage.setItem(
      KOMI_CLOSE_WARNING_IDS,
      JSON.stringify({
        ids: [...ids, value?.id],
      })
    );
    setVisibleWarning(false);
  }, [value]);

  const menu = useMemo(() => {
    return (
      <Menu className="localization-select__menu">
        {isAnalytic && (
          <Menu.Item
            className={value?.id === ALL_PAGES.id ? "selected" : ""}
            onClick={handleClickItem(ALL_PAGES)}
            key="all"
          >
            <Row align="middle">
              <Col flex="1">
                <Text
                  className={classNames("localization-select__menu--title")}
                  ellipsis={true}
                  preset="semibold16"
                >
                  {ALL_PAGES.name}
                </Text>
              </Col>
            </Row>
          </Menu.Item>
        )}
        {activePages.length ? (
          <Menu.Item disabled={true} className="title">
            <Paragraph
              className="opacity--60 p__x--20 p__t--16 p__b--8"
              preset="semibold14"
            >
              Active Pages
            </Paragraph>
          </Menu.Item>
        ) : null}
        {activePages?.map((item: LocalizationItem) => {
          const isActive = value?.id === item.id;
          return (
            <Menu.Item
              className={isActive ? "selected" : ""}
              onClick={handleClickItem(item)}
              key={item.id ? item.id?.toLocaleLowerCase() : "default"}
            >
              <Row align="middle">
                <Col flex="1">
                  <Text
                    className={classNames("localization-select__menu--title", {
                      unpublish: !item.isPublished,
                    })}
                    ellipsis={true}
                    preset="semibold16"
                  >
                    {item.name}
                  </Text>
                </Col>
                {!item.isPublished && !hideMoreOptions && (
                  <Col className="relative">
                    <div className="localization-select__unpublished" />
                    <Text className="opacity--50 p__l--8" preset="regular12">
                      Unpublished Changes
                    </Text>
                  </Col>
                )}
              </Row>
            </Menu.Item>
          );
        })}
        {inActivePages.length ? (
          <Menu.Item disabled={true} className="title">
            <Paragraph
              className="opacity--60 p__x--20 p__t--16 p__b--8"
              preset="semibold14"
            >
              Inactive Pages
            </Paragraph>
          </Menu.Item>
        ) : null}
        {inActivePages?.map((item: LocalizationItem) => {
          const isActive = value?.id === item.id;
          return (
            <Menu.Item
              className={isActive ? "selected" : ""}
              onClick={handleClickItem(item)}
              key={item.id?.toLowerCase()}
            >
              <Row align="middle">
                <Col flex="1">
                  <Text
                    className={classNames("localization-select__menu--title", {
                      unpublish: !item.isPublished,
                    })}
                    ellipsis={true}
                    preset="semibold16"
                  >
                    {item.name}
                  </Text>
                </Col>
                {!item.isPublished && !hideMoreOptions && (
                  <Col className="relative">
                    <div className="localization-select__unpublished" />
                    <Text className="opacity--50 p__l--8" preset="regular12">
                      Unpublished Changes
                    </Text>
                  </Col>
                )}
              </Row>
            </Menu.Item>
          );
        })}
      </Menu>
    );
  }, [activePages, inActivePages, value, handleClickItem]);

  const handleClickEdit = useCallback(() => {
    setVisibleMenu(false);
    // onEdit?.();
    value && setFormData(value);
    setEdit(true);
    setVisibleCreate(true);
  }, [value, setEdit, setVisibleMenu]);

  const handleCloseCreateModal = useCallback(() => {
    setVisibleCreate(false);
  }, [initialFormValues]);

  const handleEditLocalization = useCallback(() => {
    const newList = localizations?.map((item) => {
      if (formData.id === item.id) {
        item.name = formData.name;
        item.countries = formData.countries;
        item.currency = formData.currency;
      }
      return item;
    });
    dispatch(
      updateTalentProfileActions.REQUEST({
        localizations: newList,
        userState: userState,
        onSuccess: () => {
          handleCloseCreateModal();
        },
      })
    );
  }, [formData, handleCloseCreateModal, dispatch, localizations]);

  const handleDelete = useCallback(() => {
    setVisibleMenu(false);
    setVisibleDelete(true);
  }, []);

  const handleShowInfo = useCallback(() => {
    setTimeout(() => {
      setVisibleInfo(true);
    }, 200);
  }, []);

  const handleConfirmDelete = useCallback(() => {
    setVisibleDelete(false);
    if (value?.id) {
      onDeleteLocalization(value.id, defaultPage);
    }
    onDelete?.();
  }, [onDelete, value, onDeleteLocalization, defaultPage]);

  const handleManage = useCallback(() => {
    setVisibleMenu(false);
    router.push("/admin/settings");
  }, [setVisibleMenu, router]);

  const handleOpenCreateModal = useCallback(() => {
    setVisibleCreate(true);
    setFormData(initialFormValues);
    setEdit(false);
  }, [initialFormValues, setFormData]);

  return (
    <div>
      <div
        className={classNames("localization-select", className, {
          "m__b--20": !className,
          "localization-select__analytics": isAnalytic,
        })}
      >
        <LocalizationCreateModal
          show={visibleCreate}
          onClose={handleCloseCreateModal}
          formData={formData}
          onChangeForm={setFormData}
          edit={edit}
          onEdit={handleEditLocalization}
          onChangePage={onChange}
          onShowInfo={handleShowInfo}
        />
        <Row gutter={24} align="middle">
          <Col>
            <Paragraph preset="semibold16">Your Pages</Paragraph>
          </Col>
          {!hideMoreOptions && (
            <Col>
              <Row className="cursor-pointer" gutter={3} align="middle">
                <Col className="height--20">
                  <Icon name="plus" />
                </Col>
                <Col onClick={handleOpenCreateModal}>
                  <Paragraph preset="semibold16" className="text--blue">
                    New Page
                  </Paragraph>
                </Col>
              </Row>
            </Col>
          )}
        </Row>
        <Row align="middle" className="m__t--8" gutter={20}>
          <Col flex="1">
            <Dropdown
              className={classNames("localization-select", dropdownClassName)}
              overlay={menu}
              trigger={["click"]}
              overlayClassName="localization-select__dropdown"
              overlayStyle={{ maxHeight: 320 }}
            >
              <Row
                align="middle"
                className="p__y--8 p__x--12 border-box bo__radius--8 cursor-pointer"
                wrap={false}
              >
                <Col className="localization-select__label m__r--10" flex="1">
                  <Tooltip
                    style={{ zIndex: 9999999 }}
                    visible={!isAnalytic && !value?.id ? visibleTooltip : false}
                    onVisibleChange={setVisibleTooltip}
                    overlayClassName="localization-select-tooltip"
                    placement="top"
                    title={`Visitors from countries you don’t have a local page for will see the Default version of your profile.`}
                  >
                    <Paragraph
                      className={!isAnalytic && !value?.id ? "width--56" : ""}
                      ellipsis={{ rows: 1 }}
                      preset="semibold16"
                    >
                      {value?.name}
                    </Paragraph>
                  </Tooltip>
                </Col>
                {!(value || defaultPage)?.isPublished && !hideMoreOptions && (
                  <Col className="relative m__r--16">
                    <div className="localization-select__unpublished" />
                    <Text className="opacity--50 p__l--8" preset="regular12">
                      Unpublished Changes
                    </Text>
                  </Col>
                )}
                <Icon name="arrow-down" />
              </Row>
            </Dropdown>
          </Col>
          {!hideMoreOptions && (
            <Col className="height--24 width--44">
              {value?.id !== null && (
                <Popover
                  placement="bottomRight"
                  overlayClassName="data-capture-form-card-overlay"
                  arrowContent={null}
                  visible={visibleMenu}
                  onVisibleChange={setVisibleMenu}
                  content={
                    <List className="data-capture-form-card__actions">
                      <List.Item onClick={handleClickEdit}>
                        <Paragraph preset="semibold14">
                          Edit Page Settings
                        </Paragraph>
                      </List.Item>
                      <List.Item onClick={handleManage}>
                        <Paragraph preset="semibold14">
                          Manage Localized Pages
                        </Paragraph>
                      </List.Item>
                      <List.Item onClick={handleDelete}>
                        <Paragraph preset="semibold14" className="text--red">
                          Delete
                        </Paragraph>
                      </List.Item>
                    </List>
                  }
                  trigger={["click"]}
                >
                  <Button
                    className="p--0 d--flex align__items--center height--24"
                    type="link"
                  >
                    <Icon name="more" />
                  </Button>
                </Popover>
              )}
            </Col>
          )}
        </Row>
        {visibleInfo && (
          <Alert
            className="localization-info m__t--20 align__items--start"
            message="This localized page is currently inactive and will not be displayed in the countries selected until you publish it."
            type="info"
            icon={<Icon name="info" />}
            closeText={<Icon width={24} height={24} name="close-outline" />}
            showIcon
            closable
          />
        )}
        <ConfirmDeleteModal
          show={visibleDelete}
          reverse={true}
          toggleModal={() => setVisibleDelete(false)}
          width={522}
          className="localization-confirmation"
          classNameAction="m__t--24"
          cancelLabel="CANCEL"
          confirmLabel={"DELETE"}
          title={"Are you sure you want to turn this localized page off?"}
          description={
            "If you choose to proceed, your localized page will be unpublished and replaced with the default version. You will be still be able to access this localized page in the future by turning it back on. "
          }
          handleConfirm={handleConfirmDelete}
        />
      </div>
      {!isAnalytic && !!value?.id && !value?.active && visibleWarning && (
        <div className="p__x--20 p__b--20">
          <Row className="localization-select__warning" gutter={12}>
            <Col>
              <Icon name="info" />
            </Col>
            <Col flex="1">
              <Paragraph preset="regular16" className="opacity--80">
                This localized page is currently inactive and will not be
                displayed in the countries selected until you publish it.
              </Paragraph>
            </Col>
            <Col onClick={handleCloseWarning} className="cursor-pointer">
              <Icon name="close-outline" />
            </Col>
          </Row>
        </div>
      )}
    </div>
  );
};

export default LocalizationSelect;
