import React from 'react';

// Utils
import {
  TemplateCategory,
  TemplateRecord,
  TemplateType,
} from '../../customTemplateSection';
import {hexToRgba, removeSThroughOne} from '../../../../../utils/helper';
import {Products} from '../../../../../utils/products';

// Components
import TempCard from '../../TemplatesCard/V2';
import GeneralSelect from '../../../../GenericUIBlocks/GeneralSelect';
import Input from '../../../../GenericUIBlocks/Input';
import Dialog from '../../../../GenericUIBlocks/Dialog/V2';

// styles
import './styles.scss';

const galleryDialogStyles = {
  maxWidth: '1025px',
  minHeight: 'calc(100% - 50px)',
  backgroundColor: '#fff',
  padding: '40px 0 40px 40px',
};

type CustomTemplateSectionProps = {
  product: any;
  openGalleryModal: boolean;
  selectedCategory: TemplateCategory | null;
  templateCategories: TemplateCategory[];
  currentTemplateType: TemplateType | undefined;
  templateTypes: TemplateType[] | null | undefined;
  designerQueryAmount?: string | number;
  search: any;
  searchApplied: boolean;
  loader: boolean;
  platformName: any;
  myTemplates: TemplateRecord[];
  teamTemplates: TemplateRecord[];
  olcTemplates: TemplateRecord[];
  pagination: any;
  setSearch: any;
  handleSearch: any;
  removeSearchInput: any;
  searchKeyDown: any;
  currentTemplateTypeRef: any;
  setCurrentTemplateType: any;
  setSelectedCategory: any;
  handleLoadTemplateModel: any;
  handleTabChange: any;
  handleDialogChange: any;
  closeGalleryModal: any;
  setOpenGalleryModal: any;
  setHireDesignerModal: any;
  currentTheme?: string | null | undefined;
};

const ModalGalleryV2 = (props: CustomTemplateSectionProps) => {
  const {
    product,
    openGalleryModal,
    selectedCategory,
    templateCategories,
    currentTemplateType,
    templateTypes,
    designerQueryAmount,
    search,
    searchApplied,
    loader,
    platformName,
    myTemplates,
    teamTemplates,
    olcTemplates,
    pagination,
    setSearch,
    handleSearch,
    removeSearchInput,
    searchKeyDown,
    currentTemplateTypeRef,
    setCurrentTemplateType,
    setSelectedCategory,
    handleLoadTemplateModel,
    handleTabChange,
    handleDialogChange,
    closeGalleryModal,
    setOpenGalleryModal,
    setHireDesignerModal,
    currentTheme,
  } = props;

  const primaryColorExtract = getComputedStyle(document.documentElement)
    .getPropertyValue('--primary-color')
    .trim();

  const primaryColorRGBA = hexToRgba(primaryColorExtract, 0.5);

  const currentTemplates =
    currentTemplateType?.id === '1'
      ? myTemplates
      : currentTemplateType?.id === '2'
        ? teamTemplates
        : currentTemplateType?.id === '3'
          ? olcTemplates
          : [];

  const uniqueCurrentTemplates = Array.from(
    new Map(currentTemplates.map((item) => [item.id, item])).values()
  );

  const ModalTitle = ({title}: {title: string}) => {
    return (
      <>
        {`${title}`}
        <span
          style={{
            fontSize: '16px',
            fontWeight: '400',
            color: '#00000099',
            marginLeft: '12px',
            fontFamily: 'var(--font-family)',
          }}
        >{`(${removeSThroughOne(`${currentTemplates.length > 0 ? pagination.total : 0} templates`)})`}</span>
      </>
    );
  };

  return (
    <>
      <Dialog
        customStyles={galleryDialogStyles}
        open={openGalleryModal}
        handleClose={closeGalleryModal}
        isGallery={true}
        currentTheme="v2"
        title={
          <ModalTitle
            title={
              product?.productType === 'Postcards'
                ? `${product?.productType} (${product?.selectedSize || product?.paperSize}) `
                : product?.productType === 'Real Penned Letter'
                  ? 'Real Penned ' +
                    product?.size.find(
                      (item: {id: any}) => item?.id === product?.id
                    )?.title
                  : Products?.find((item) => item?.id === product?.id)?.title ||
                    product?.productType
            }
          />
        }
      >
        <div className="topBar-v2">
          <div className="filters-container">
            {currentTemplateType?.id === '3' &&
              templateCategories?.length > 1 && (
                <div className="filter-select" style={{minWidth: '200px'}}>
                  <>
                    <GeneralSelect
                      placeholder="Industry/Theme"
                      options={templateCategories as any}
                      setSelectedValue={setSelectedCategory as any}
                      selectedValue={selectedCategory as any}
                      builderSelect={false}
                      gallerySelect={true}
                      clearField={true}
                      search={false}
                      isError={false}
                      currentTheme="v2"
                    />
                  </>
                </div>
              )}
            <div className="filter-select" style={{minWidth: '180px'}}>
              <GeneralSelect
                placeholder="All Templates"
                options={templateTypes || []}
                setSelectedValue={setCurrentTemplateType as any}
                selectedValue={currentTemplateType as any}
                builderSelect={false}
                gallerySelect={true}
                clearField={false}
                search={false}
                isError={false}
                currentTheme="v2"
              />
            </div>
          </div>
          <Input
            type="text"
            value={search}
            // @ts-ignore
            onKeyDown={searchKeyDown}
            onChange={(e: any) => setSearch(e.target.value.trimStart())}
            placeholder="Search templates"
            onClick={handleSearch}
            searchApplied={searchApplied}
            removeSearchInput={removeSearchInput}
            inputIcon={true}
            gellerySearch={true}
            currentTheme="v2"
            className="searchInput-v2"
          />
        </div>
        <div
          className={`templatesContent-v2 ${currentTemplateType?.id === '3' && 'heightOLC-v2'}`}
          style={{
            justifyContent: 'flex-start',
            alignItems: 'center',
            overflowY:
              product?.productType === 'Personal Letters' &&
              currentTemplates.length === 0
                ? 'hidden'
                : 'scroll',
          }}
        >
          <TempCard
            templates={uniqueCurrentTemplates}
            handleLoadTemplateModel={handleLoadTemplateModel}
            loading={loader}
            platformName={platformName}
            currentTemplateType={currentTemplateType}
            product={product}
            searchApplied={searchApplied}
            primaryColorRGBA={primaryColorRGBA}
            designerQueryAmount={designerQueryAmount}
            currentTheme="v2"
          />
        </div>
      </Dialog>
    </>
  );
};

export default ModalGalleryV2;
