import React, { useState, useEffect } from 'react';

// Libraries/Packages
import { Routes, Route } from 'react-router-dom';
import { createStore, StoreType } from 'polotno/model/store';

// components
import TemplateTypes from './components/TemplateTypes';
import CreateTemplate from './components/CreateTemplate';
import CreateTemplateV2 from './components/CreateTemplate/V2';
import TemplateBuilder from './components/TemplateBuilder';
import { createGlobalStyle } from 'styled-components';
import GenericSnackbar from './components/GenericUIBlocks/GenericSnackbar/Toast';

// Initialize Plotno Store
const initializeStore = (secretKey: string) => {
  return createStore({
    key: secretKey,
    // you can hide back-link on a paid license
    // but it will be good if you can keep it for Polotno project support
    showCredit: false,
  });
};

interface AppProps {
  secretKey: string;
  platformName?: string | null;
  templateGalleryModal?: boolean;
  createTemplateRoute?: string | null;
  templateBuilderRoute?: string | null;
  olcTemplate?: Record<string, any>;
  designerTemplateQuery?: Record<string, any> | null;
  allowSenderFields?: boolean;
  excludedFields?: string[] | null;
  designerQueryAmount?: string | number;
  allowPropertyFields?: boolean;
  allowedAddOns?: any;
  allowedTemplateSections?: any;
  allowAdditionalPage?: boolean;
  restrictedProducts?: any;
  disallowedProducts?: string[] | null | undefined;
  propertyOfferCost?: number;
  customPropertyOfferCost?: number;
  gsvCost?: number;
  showTemplateTypesPage?: boolean;
  currentTheme?: string | null | undefined;
  styles?: any;
  onReturnAndNavigate?: () => void;
  onCreateCustomTemplateQuery?: (payload: any) => Promise<any>;
  onGetOneTemplate?: (payload: any) => Promise<any>;
  onGetTemplates?: (payload: any) => Promise<any>;
  onGetCustomFields?: () => Promise<any>;
  onDuplicateTemplate?: (payload: any) => Promise<any>;
  onGetBrandingImages?: (payload: any) => Promise<any>;
  onDeleteBrandingImage?: (id: string | number) => Promise<void>;
  onUploadBrandingImage?: (payload: any) => Promise<any>;
  onGetQRCodes?: (payload: any) => Promise<any>;
  onDeleteQRCodes?: (id: string | number) => Promise<void>;
  onUploadQRCode?: (payload: any) => Promise<any>;
  onEditQRCode?: (payload: any) => Promise<any>;
  onSubmit?: (payload: any) => Promise<any>;
}

const App: React.FC<AppProps> = ({
  secretKey,
  platformName,
  templateGalleryModal,
  createTemplateRoute,
  templateBuilderRoute,
  olcTemplate,
  designerTemplateQuery,
  allowSenderFields,
  excludedFields,
  designerQueryAmount,
  allowPropertyFields,
  allowedAddOns,
  allowedTemplateSections,
  allowAdditionalPage,
  restrictedProducts,
  disallowedProducts,
  propertyOfferCost,
  customPropertyOfferCost,
  showTemplateTypesPage,
  gsvCost,
  currentTheme,
  styles,
  onReturnAndNavigate,
  onCreateCustomTemplateQuery,
  onGetOneTemplate,
  onGetCustomFields,
  onDuplicateTemplate,
  onGetTemplates,
  onGetBrandingImages,
  onDeleteBrandingImage,
  onUploadBrandingImage,
  onGetQRCodes,
  onDeleteQRCodes,
  onUploadQRCode,
  onEditQRCode,
  onSubmit,
}) => {
  const [store, setStore] = useState<StoreType>(initializeStore(secretKey));
  const [selectedTemplateType, setSelectedTemplateType] = useState<string | null>(null);
  const [templateTypeSelected, setTemplateTypeSelected] = useState(false);

  const currentPath = window?.location?.pathname;

  useEffect(() => {
    if (
      currentPath === createTemplateRoute ||
      currentPath === '/create-template' || designerTemplateQuery
    ) {
      const newStore = initializeStore(secretKey);
      setStore(newStore);
    }
  }, [currentPath]);

  const GlobalStyle =
    styles && Object.keys(styles).length
      ? createGlobalStyle`
        :root {
        ${styles
          ? Object.entries(styles.root)
            .map(([key, value]) => `${key}: ${value} !important;`)
            .join(' ')
          : ''
        }
          }
        `
      : createGlobalStyle`<></>`;

  return (
    <div className="builder-wrapper">
      <GenericSnackbar />
      <GlobalStyle />
      <Routes>
        <Route
          path={createTemplateRoute || '/create-template'}
          element={showTemplateTypesPage && !templateTypeSelected ?
            <TemplateTypes
              createTemplateRoute={createTemplateRoute}
              onReturnAndNavigate={onReturnAndNavigate}
              selectedTemplateType={selectedTemplateType}
              setSelectedTemplateType={setSelectedTemplateType}
              setTemplateTypeSelected={setTemplateTypeSelected}
            /> : currentTheme === 'v2' ?
              <CreateTemplateV2
                createTemplateRoute={createTemplateRoute}
                templateBuilderRoute={templateBuilderRoute}
                restrictedProducts={restrictedProducts}
                onReturnAndNavigate={onReturnAndNavigate}
                disallowedProducts={disallowedProducts}
                currentTheme={currentTheme}
              /> :
              <CreateTemplate
                createTemplateRoute={createTemplateRoute}
                templateBuilderRoute={templateBuilderRoute}
                restrictedProducts={restrictedProducts}
                onReturnAndNavigate={onReturnAndNavigate}
                disallowedProducts={disallowedProducts}
                currentTheme={currentTheme}
              />
          }
        />
        <Route
          path={templateBuilderRoute || '/template-builder/:id?'}
          element={
            <TemplateBuilder
              store={store}
              olcTemplate={olcTemplate}
              designerTemplateQuery={designerTemplateQuery}
              platformName={platformName}
              templateGalleryModal={templateGalleryModal}
              allowSenderFields={allowSenderFields}
              excludedFields={excludedFields}
              designerQueryAmount={designerQueryAmount}
              allowPropertyFields={allowPropertyFields}
              createTemplateRoute={createTemplateRoute}
              allowedAddOns={allowedAddOns}
              allowedTemplateSections={allowedTemplateSections}
              allowAdditionalPage={allowAdditionalPage}
              propertyOfferCost={propertyOfferCost}
              customPropertyOfferCost={customPropertyOfferCost}
              gsvCost={gsvCost}
              selectedTemplateType={selectedTemplateType}
              currentTheme={currentTheme}
              onReturnAndNavigate={onReturnAndNavigate}
              onCreateCustomTemplateQuery={onCreateCustomTemplateQuery}
              onGetOneTemplate={onGetOneTemplate}
              onGetTemplates={onGetTemplates}
              onGetCustomFields={onGetCustomFields}
              onDuplicateTemplate={onDuplicateTemplate}
              onGetBrandingImages={onGetBrandingImages}
              onDeleteBrandingImage={onDeleteBrandingImage}
              onUploadBrandingImage={onUploadBrandingImage}
              onGetQRCodes={onGetQRCodes}
              onDeleteQRCodes={onDeleteQRCodes}
              onUploadQRCode={onUploadQRCode}
              onEditQRCode={onEditQRCode}
              onSubmit={onSubmit}
            />
          }
        />
      </Routes>
    </div>
  );
};

export default App;
