import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Spin, Checkbox, Button, notification } from 'antd';

import { API_URL } from 'containers/App/urls';
import { MenuPlaceHolderIcon } from 'styles/icon-components';
import { MenuModel } from '../Menu/MenuList/menuListMenuModels';
import { MENUS_MENU_ITEMS_MERCHANT_URL, PUBLIC_API } from 'containers/App/urls';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import { fetchAPI, replaceUrl } from '../../utils/fetchAPI';
import { MENUS_MENU_ITEM_RESTAURANT_BY_ID } from '../App/urls';
import { useParams } from 'react-router-dom';
import { MOBILE_BREAK_POINT } from 'styles/constants';
import { useHistory } from 'react-router-dom';
import _ from 'lodash';
import { RoutePaths } from '../App/routes';
import { makeCombo, makeMenu, makeService } from './Store';
import { createStructuredSelector } from 'reselect';
import { FormattedMessage } from 'react-intl';
import messages from 'translations/messages';

const selectors = createStructuredSelector({
  service: makeService(),
  menu: makeMenu(),
  combo: makeCombo(),
});

const RestaurantAddMenuWrapper = styled.div`
  background: #fff;
  padding: 10px;
  .menu-tab {
    width: calc(100% + 50px);
    @media only screen and (max-width: 736px) {
      width: calc(100% + 15px);
    }
    @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 1) {
      width: calc(100% + 15px);
    }
    &__section {
      display: block;
    }
    .section {
      &__select-all {
        margin: 30px 0 40px 0;
        button {
          margin-left: 30px;
          color: white;
          background: #dc5454;
        }
        button:hover {
          color: #dc5454;
          border-color: #dc5454;
          background: white;
        }
        button:focus {
          border-color: #dc5454;
        }
      }

      &__title {
        font-size: 13px;
        font-weight: 600;
        color: #333333;
        border-bottom: 2px solid #f1f1f1;
        padding-bottom: 10px;
        margin: 20px 0;
        text-transform: uppercase;
        &__checkbox {
          padding-right: 10px;
        }
      }

      &__content {
        display: flex;
        flex-wrap: wrap;
      }
    }

    .item {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      width: 33%;
      min-height: 90px;
      padding-right: 49px;
      padding-bottom: 20px;
      position: relative;
      @media only screen and (max-width: 736px) {
        width: 100%;
        padding-right: 15px;
      }
      @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 1) {
        width: 50%;
      }
      &__checkbox {
        padding-right: 10px;
      }
      &__image {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        min-height: 62px;
        min-width: 70px;
        margin-right: 20px;
        background-color: #ececec;

        img {
          width: 70px;
          height: 62px;
        }
      }

     &__title {
        font-size: 16px;
        font-weight: bold;
        font-stretch: normal;
        color: #333333;
        padding-bottom: 10px;
      }

      &__description {
        font-size: 13px;
        color: #9c9696;
      }

      &__actions {
        position: absolute;
        right: 50px;
        cursor: pointer;
        @media only screen and (max-width: 736px) {
          right: 0px;
        }

        @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 1) {
          right: 5px;
        }
      }
    }
  }
  @media only screen and (max-width: ${MOBILE_BREAK_POINT}px) {
    .menu-tab {
      &__add-button {
        position: relative;
        left: -30px;
        margin-top: 10px;
      }
    }
  }
`;

let isArrayContainTarget = (arr: Array<number>, target: Array<number>) =>
  target.every(v => arr.includes(v));

export function RestaurantAddMenu(props) {
  // @ts-ignore
  const { id } = useParams();
  const [loading, setLoading] = useState(true);
  const [menuList, setMenuList] = useState<MenuModel[]>([]);
  const [checkedMenuItemIds, setCheckedMenuItemIds] = useState<Array<number>>(
    [],
  );
  const urlParams = new URLSearchParams(window.location.search);
  const typeParams = urlParams.get('type');
  let type = 1;
  if (typeParams === 'service') {
    type = 2;
  }
  let numberOfMenuItem = 0;
  let allMenuItemIds: Array<number> = [];
  const history = useHistory();
  menuList.map(menu => {
    const { menuItems } = menu;
    if (menuItems) {
      numberOfMenuItem += menuItems.length;
      const allMenuItemIdInCategory: Array<number> = menuItems?.map(o => o.id);
      allMenuItemIds = [...allMenuItemIds, ...allMenuItemIdInCategory];
    }
  });
  const isCheckAll = numberOfMenuItem === checkedMenuItemIds.length;
  const handleOnChangeCheckAll = (e: CheckboxChangeEvent) => {
    if (e.target.checked) {
      setCheckedMenuItemIds(allMenuItemIds);
    } else {
      setCheckedMenuItemIds([]);
    }
  };
  const getMenuList = async () => {
    const response = await fetchAPI({
      method: 'GET',
      url: `${MENUS_MENU_ITEMS_MERCHANT_URL}?type=${type}`,
    });
    if (response) {
      let listItems = [] as any;
      if (typeParams === 'combo') {
        const combo = response.reduce(
          (accumulate, category) =>
            accumulate.concat(
              _.filter(
                category.menuItems,
                (menuItem: any) =>
                  menuItem.products.length > 1 ||
                  menuItem.products[0].quantity > 1,
              ),
            ),
          [],
        );
        listItems.push({
          categoryName: 'Combo',
          menuItems: combo,
          categoryId: 0,
          kitchenAliasName: '',
        });
      } else if (typeParams === 'menu') {
        const isMenu = (menuItem: any) =>
          menuItem.products.length < 2 || menuItem.products[0].quantity < 2;
        const menu = response.map(category => {
          return {
            ...category,
            menuItems: _.filter(category.menuItems, isMenu),
          };
        });
        listItems = menu;
      } else {
        listItems = response;
      }
      setMenuList([...listItems]);
      setLoading(false);
    }
  };

  const getMenus = async () => {
    let url = `${API_URL}/menus/menu-items?restaurantId=${id}`;
    const response = await fetchAPI({
      method: 'GET',
      url,
    });
    if (response) {
      let ids;
      if (typeParams === 'combo') {
        ids = response.reduce(
          (accumulate, category) =>
            accumulate.concat(
              _.filter(
                category.menuItems,
                (menuItem: any) => menuItem.products.length > 1,
              ),
            ),
          [],
        );
      } else if (typeParams === 'menu') {
        const isMenu = (menuItem: any) =>
          menuItem.products[0].type === 1 && menuItem.products.length < 2;
        ids = response.reduce(
          (accumulate, category) =>
            accumulate.concat(_.filter(category.menuItems, isMenu)),
          [],
        );
      } else {
        const isService = (menuItem: any) => menuItem.products[0].type === 2;
        ids = response.reduce(
          (accumulate, category) =>
            accumulate.concat(_.filter(category.menuItems, isService)),
          [],
        );
      }
      ids = ids.map(menuItem => menuItem.id);
      setCheckedMenuItemIds(ids);
    }
  };

  const handleAddMenuToRestaurant = async () => {
    try {
      setLoading(true);
      const response = await fetchAPI({
        method: 'POST',
        url: replaceUrl(MENUS_MENU_ITEM_RESTAURANT_BY_ID, { id }),
        data: {
          menuItems: checkedMenuItemIds,
        },
      });
      if (response) {
        let activeTab = 1;
        if (typeParams === 'menu') {
          activeTab = 2;
        } else if (typeParams === 'combo') {
          activeTab = 3;
        }
        history.push(
          `${RoutePaths.restaurantDetail}/${id}?activeTab=${activeTab}`,
        );
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getMenuList();
    getMenus();
  }, []);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', top: '20px', position: 'relative' }}>
        <Spin />
      </div>
    );
  }

  const titleList = {
    service: {
      headerTitle: <FormattedMessage {...messages.serviceList} />,
      checkboxTitle: <FormattedMessage {...messages.checkboxServiceResTitle} />,
      addTitle: <FormattedMessage {...messages.addServiceResTitle} />,
      warningTitle: <FormattedMessage {...messages.emptyServiceResList} />,
    },
    menu: {
      headerTitle: <FormattedMessage {...messages.productList} />,
      checkboxTitle: <FormattedMessage {...messages.checkboxProductResTitle} />,
      addTitle: <FormattedMessage {...messages.addProductResTitle} />,
      warningTitle: <FormattedMessage {...messages.emptyProductResList} />,
    },
    combo: {
      headerTitle: <FormattedMessage {...messages.comboList} />,
      checkboxTitle: <FormattedMessage {...messages.checkboxComboResTitle} />,
      addTitle: <FormattedMessage {...messages.addComboResTitle} />,
      warningTitle: <FormattedMessage {...messages.emptyComboResList} />,
    },
  };
  const typeChoose = typeParams ? typeParams : 'menu';
  return (
    <RestaurantAddMenuWrapper>
      <div className="menu-tab">
        <h3 style={{ fontSize: 19, fontWeight: 600 }}>
          {' '}
          {titleList[typeChoose].headerTitle}
        </h3>
        <div className="section__select-all">
          <Checkbox
            className="section__title__checkbox"
            checked={isCheckAll}
            onChange={handleOnChangeCheckAll}
          />
          {titleList[typeChoose].checkboxTitle}
          {checkedMenuItemIds.length > 0 && (
            <Button
              onClick={handleAddMenuToRestaurant}
              disabled={checkedMenuItemIds.length === 0}
              loading={loading}
              className="menu-tab__add-button"
            >
              {titleList[typeChoose].addTitle}
            </Button>
          )}
        </div>
        {menuList &&
          menuList.map(menu => {
            const { menuItems } = menu;
            if (!menuItems?.length) {
              return <div>{titleList[typeChoose].warningTitleTitle}</div>;
            }
            const allMenuItemIdInCategory = menuItems?.map(o => o.id);
            const isCheckedCategory = isArrayContainTarget(
              checkedMenuItemIds,
              allMenuItemIdInCategory,
            );
            const handleChangeCheckCategory = (e: CheckboxChangeEvent) => {
              let newCheckedMenuItemIds;
              if (e.target.checked) {
                const union = [
                  ...checkedMenuItemIds,
                  ...allMenuItemIdInCategory,
                ];
                newCheckedMenuItemIds = union.filter(
                  (index, pos) => union.indexOf(index) === pos,
                );
                setCheckedMenuItemIds(newCheckedMenuItemIds);
              } else {
                newCheckedMenuItemIds = checkedMenuItemIds.filter(
                  checkedId => !allMenuItemIdInCategory.includes(checkedId),
                );
              }
              setCheckedMenuItemIds(newCheckedMenuItemIds);
            };
            return (
              <div
                className="menu-tab__section"
                key={'section_' + menu.categoryId}
              >
                <div className="section__title">
                  <Checkbox
                    className="section__title__checkbox"
                    checked={isCheckedCategory}
                    onChange={handleChangeCheckCategory}
                  />
                  {menu.categoryName}
                </div>
                <div className="section__content">
                  {menuItems &&
                    menuItems.length > 0 &&
                    menuItems.map(menuItem => {
                      const { id, photo, name, description } = menuItem;
                      const isCheckedMenuItem = checkedMenuItemIds.includes(id);
                      const handleOnChangeCheckItem = (
                        e: CheckboxChangeEvent,
                      ) => {
                        if (e.target.checked) {
                          setCheckedMenuItemIds([...checkedMenuItemIds, id]);
                        } else {
                          const newCheckedMenuItemIds = checkedMenuItemIds.filter(
                            checkedId => checkedId !== id,
                          );
                          setCheckedMenuItemIds(newCheckedMenuItemIds);
                        }
                      };
                      return (
                        <div className="item" key={'menuItem_' + id}>
                          <Checkbox
                            className="item__checkbox"
                            checked={isCheckedMenuItem}
                            onChange={handleOnChangeCheckItem}
                          />
                          <div className="item__image">
                            {photo ? (
                              <img
                                src={`${PUBLIC_API}/${photo}`}
                                style={{ objectFit: 'cover' }}
                              />
                            ) : (
                              <MenuPlaceHolderIcon />
                            )}
                          </div>
                          <div className="item__content">
                            <div className="item__title">{name}</div>
                            <div className="item__description">
                              {description}
                            </div>
                          </div>
                        </div>
                      );
                    })}
                </div>
              </div>
            );
          })}
      </div>
    </RestaurantAddMenuWrapper>
  );
}
