import React, { FC, ReactType, ReactNode, useState, useEffect } from 'react';
import * as R from 'ramda';
import Layout from '../../components/Layout';
import Content from '../../components/Content';
import { PartnerListProps } from '../../components/PartnerList';
import Banner, { BannerProps } from '../../components/Banner';
import css from './index.module.css';
import {
  PackageListItem,
  PackageListProps,
} from '../../components/PackageList';
import { MilaGridColumn, MilaGridVoid } from '../../index';
import DropdownList from '../../blocks/DropdownList';
import BackToPage, { BackToProps } from '../../components/BackToPage';

export interface EnterprisePartnerPageProps {
  title?: string;
  subtitle?: string;
  isAustria: boolean;
  isUk: boolean;
  BannerProps?: BannerProps;
  PackageList?: ReactType;
  PackageListProps?: PackageListProps;
  Search: ReactType;
  SearchProps: unknown;
  FeaturedPartnersList: ReactType;
  FeaturedPartnersListProps: PartnerListProps;
  EnterprisePartnerList: ReactType;
  SectionHowToProps?: {
    items: {
      title: string;
      image: unknown;
    }[];
    Image: ReactType;
  };
  SectionServicesProps?: {
    title: string;
    items: {
      title: string;
      image: unknown;
    }[];
    Image: ReactType;
  };
  recommendedPrice?: string;
  SectionAboutMila?: ReactNode;
  children?: ReactNode;
  hasCustomBanner?: boolean;
  CustomBanner?: ReactType;
  Alerts?: ReactNode;
  CategoryTab?: ReactType;
  packages: any;
  defaultPackages: any;
  subcategory: any;
  onSubcategorySelect: (sub) => void;
  showTabInBanner: boolean;
  BackToProps: BackToProps;
  Translations: {
    common: string;
    offerings: string;
    items: string;
    all: string;
    category: string;
  };
  Campaign?: ReactNode;
}

const EnterprisePartnerPage: FC<EnterprisePartnerPageProps> = ({
  BannerProps,
  Search,
  SearchProps,
  recommendedPrice,
  children,
  SectionAboutMila,
  Alerts,
  CategoryTab,
  packages,
  subcategory,
  onSubcategorySelect,
  defaultPackages,
  showTabInBanner = true,
  BackToProps,
  Translations,
  Campaign,
}) => {
  const [selectedSubcat, setSelectedSubcat] = useState(null);
  const [resultsCount, setResultsCount] = useState(null);
  const [options, setOptions] = useState(null);

  const countItems = (
    packages: any,
    subcategory: string,
  ): number | undefined => {
    if (!packages || !packages.items) {
      return;
    }
    if (subcategory === 'all') {
      setResultsCount(packages.items.length);
      return;
    }
    const subCats = packages.items.map(i => i.subCategories);
    let totalItems;
    if (subCats) {
      const hasThatSubcat = subCats.map(scs =>
        scs.map(sc => sc.slug).includes(subcategory),
      );
      totalItems = hasThatSubcat.filter(Boolean).length;
    }
    totalItems += packages.items.filter(i => !!i.type && i.type === 'Brand Box')
      .length;
    setResultsCount(totalItems);
  };

  const sortSubCategoriesByScore = (a, b): number => {
    if (!!a.promotionScore && !!b.promotionScore) {
      return a.promotionScore > b.promotionScore ? -1 : 1;
    }
    if (!a.promotionScore && !b.promotionScore) {
      return 0;
    }
    if (!a.promotionScore) {
      return b.promotionScore > 0 ? 1 : -1;
    }
    if (!b.promotionScore) {
      return a.promotionScore > 0 ? -1 : 1;
    }
    return 0;
  };

  useEffect(() => {
    if (packages) {
      const initalOptions = Object.assign(
        {},
        ...packages.subCategories.sort(sortSubCategoriesByScore).map(item => {
          return {
            [item.slug]: {
              value: item.slug,
              name: item.name,
              url: '',
            },
          };
        }),
        {
          ['all']: {
            value: 'all',
            name: Translations.all || 'All',
            url: '',
          },
        },
      );
      setOptions(initalOptions);
    } else {
      setOptions({});
    }
  }, [packages]);

  useEffect(() => {
    countItems(packages, subcategory);
    setSelectedSubcat(subcategory);
  }, [subcategory, packages]);
  return (
    <Layout>
      <Banner
        {...BannerProps}
        {...{
          ...(showTabInBanner &&
            CategoryTab && {
              CategoryTab: CategoryTab,
            }),
        }}
      />
      {Alerts && Alerts}
      {!showTabInBanner &&
        defaultPackages?.length >= 4 &&
        CategoryTab &&
        CategoryTab}
      {Campaign && Campaign}
      {BackToProps && BackToProps.show && <BackToPage {...BackToProps} />}
      <div className={css.package__container}>
        <Content>
          <MilaGridVoid>
            <MilaGridColumn
              columns={['sm-12', 'lg-10', 'xl-8', 'xxl-6']}
              offset={['lg-1', 'xl-2', 'xxl-3']}
            >
              {Search && (
                <div className={css.searchbar__wrapper}>
                  <Search {...SearchProps} />
                </div>
              )}

              {packages ? (
                <>
                  <h2>{packages?.name}</h2>
                  {!BackToProps?.show && Object.keys(options || {}).length > 2 && (
                    <div className={css.package__dropdown}>
                      <DropdownList
                        type="category"
                        value={selectedSubcat}
                        options={options || {}}
                        onChange={(val: string): void => {
                          countItems(packages, val);
                          onSubcategorySelect(val);
                          setSelectedSubcat(val);
                        }}
                        category={Translations.category}
                      />
                    </div>
                  )}
                </>
              ) : (
                <h2>
                  {!CategoryTab || defaultPackages?.length < 4
                    ? Translations.offerings
                    : Translations.common}
                </h2>
              )}
            </MilaGridColumn>

            <MilaGridColumn
              columns={['sm-12', 'lg-10', 'xl-8', 'xxl-6']}
              offset={['lg-1', 'xl-2', 'xxl-3']}
              className={css.results}
            >
              {packages && packages.items && (
                <div>
                  {resultsCount || packages.items.length} {Translations.items}
                </div>
              )}
            </MilaGridColumn>

            <MilaGridColumn
              columns={['sm-12', 'lg-10', 'xxl-8']}
              offset={['lg-1', 'xxl-2']}
            >
              <div
                className={css.package__items}
                style={{ marginBottom: '50px' }}
              >
                {packages &&
                  packages.items.map(item => {
                    if (
                      item?.type === 'Brand Box' ||
                      selectedSubcat === 'all' ||
                      R.filter(
                        R.propEq('slug', selectedSubcat),
                        item.subCategories,
                      ).length > 0
                    ) {
                      return (
                        <PackageListItem
                          item={item}
                          isSelected={true}
                          key={
                            item.id +
                            (item?.type === 'Brand Box' ? 'brand' : 'package')
                          }
                        />
                      );
                    }
                  })}
                {!packages &&
                  defaultPackages &&
                  defaultPackages.map(item => {
                    return (
                      <PackageListItem
                        item={item}
                        isSelected={true}
                        key={item.id}
                      />
                    );
                  })}
              </div>
            </MilaGridColumn>
            {recommendedPrice && (
              <MilaGridColumn
                columns={['sm-12', 'lg-10', 'xl-8', 'xxl-6']}
                offset={['lg-1', 'xl-2', 'xxl-3']}
                className={css.recommendedPrice}
              >
                {'* ' + recommendedPrice}
              </MilaGridColumn>
            )}
          </MilaGridVoid>
        </Content>
      </div>

      {children}

      {SectionAboutMila && SectionAboutMila}
    </Layout>
  );
};

export default EnterprisePartnerPage;
