import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './App';

// font families
import '@fontsource/inter/200.css';
import '@fontsource/inter/300.css';
import '@fontsource/inter/400.css';
import '@fontsource/inter/500.css';
import '@fontsource/inter/600.css';
import '@fontsource/inter/700.css';
import '@fontsource/inter/800.css';

// utils
import { CustomCSSProperties } from './utils/customStyles';
import { setEnv, setIsSandbox, setPublicApiKey } from './utils/helper';
import { AddOnTypes, TemplateTypes } from './utils/types';
import { SDK_VERSION } from '../version';

// Function to dynamically load stylesheets based on sandbox mode
const loadStylesheet = (currentTheme: string) => {
  if (currentTheme === 'v2') {
    import('./v2Theme.scss');
  } else {
    import('./index.scss');
  }
};

interface TemplateBuilderProps {
  container: HTMLElement | null;
  secretKey: string;
  publicApiKey: string;
  platformName?: string | null;
  templateGalleryModal?: boolean;
  createTemplateRoute?: string | null;
  templateBuilderRoute?: string | null;
  olcTemplate?: Record<string, any>;
  designerTemplateQuery?: Record<string, any> | null;
  sandbox?: boolean;
  allowSenderFields?: boolean;
  allowPropertyFields?: boolean;
  excludedFields?: string[] | null;
  designerQueryAmount?: string | number;
  allowedAddOns?: AddOnTypes[] | string[] | null | undefined;
  allowedTemplateSections?: TemplateTypes[] | string[] | null | undefined;
  env?: string;
  restrictedProducts?: number[] | null | undefined;
  disallowedProducts?: string[] | null | undefined;
  propertyOfferCost?: number;
  customPropertyOfferCost?: number;
  gsvCost?: number;
  allowAdditionalPage?: boolean;
  showTemplateTypesPage?: boolean;
  currentTheme?: string | null | undefined;
  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>;
  styles?: {
    root?: CustomCSSProperties;
  };
}

const TemplateBuilder = ({
  container,
  secretKey,
  publicApiKey,
  platformName,
  templateGalleryModal = true,
  createTemplateRoute,
  templateBuilderRoute,
  olcTemplate,
  designerTemplateQuery,
  sandbox,
  allowSenderFields,
  allowPropertyFields,
  allowAdditionalPage,
  excludedFields,
  designerQueryAmount,
  allowedAddOns,
  allowedTemplateSections,
  env,
  restrictedProducts,
  disallowedProducts,
  propertyOfferCost,
  customPropertyOfferCost,
  gsvCost,
  showTemplateTypesPage,
  currentTheme,
  onReturnAndNavigate,
  onCreateCustomTemplateQuery,
  onGetOneTemplate,
  onGetTemplates,
  onGetCustomFields,
  onDuplicateTemplate,
  onGetBrandingImages,
  onDeleteBrandingImage,
  onUploadBrandingImage,
  onGetQRCodes,
  onDeleteQRCodes,
  onUploadQRCode,
  onEditQRCode,
  onSubmit,
  styles,
}: TemplateBuilderProps): void => {
  if (!container) {
    throw new Error('Root element not found');
  }
  if (!secretKey) {
    throw new Error('secretKey not found');
  }
  if (!publicApiKey) {
    throw new Error('publicApiKey not found');
  }
  
  // Load appropriate stylesheet based on sandbox mode
  loadStylesheet(currentTheme || 'default');
  
  if (sandbox) {
    setIsSandbox(sandbox);
  }
  if (env && SDK_VERSION.includes('beta')) {
    setEnv(env);
  }
  setPublicApiKey(publicApiKey);
  const root = ReactDOM.createRoot(container);
  root.render(
    <>
      <Provider store={store}>
        <Router>
          <App
            secretKey={secretKey}
            styles={styles}
            olcTemplate={olcTemplate}
            designerTemplateQuery={designerTemplateQuery}
            platformName={platformName}
            templateGalleryModal={templateGalleryModal}
            createTemplateRoute={createTemplateRoute}
            templateBuilderRoute={templateBuilderRoute}
            allowSenderFields={allowSenderFields}
            allowPropertyFields={allowPropertyFields}
            allowAdditionalPage={allowAdditionalPage}
            excludedFields={excludedFields}
            designerQueryAmount={designerQueryAmount}
            allowedAddOns={allowedAddOns}
            allowedTemplateSections={allowedTemplateSections}
            restrictedProducts={restrictedProducts}
            disallowedProducts={disallowedProducts}
            propertyOfferCost={propertyOfferCost}
            customPropertyOfferCost={customPropertyOfferCost}
            gsvCost={gsvCost}
            showTemplateTypesPage={showTemplateTypesPage}
            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}
          />
        </Router>
      </Provider>
    </>
  );

  //@ts-ignore
  return {
    destroy() {
      console.log("React template builder destroyed");
      root.unmount();
    }
  }
};

// Example to run the project locally for development. Comment out these lines when building the application
// const rootElement = document.getElementById('root');
// if (rootElement) {
//   console.log("React SDK Loaded");
//   TemplateBuilder({
//     container: rootElement,
//     secretKey: import.meta.env.VITE_APP_PLOTNO_API_KEY,
//     publicApiKey: import.meta.env.VITE_APP_PUBLIC_API_KEY,
//     sandbox: true,
//     allowSenderFields: true,
//     allowPropertyFields: true,
//     templateGalleryModal: true,
//     designerQueryAmount: 175,
//     allowedAddOns: ['property_offer','gsv', 'custom_property_offer'],
//     propertyOfferCost: 2.03,
//     customPropertyOfferCost: 33,
//     gsvCost: 10.5,
//     excludedFields: ['{{C.FIRST_NAME}}', '{{C.ADDRESS_1}}', '{{SPF.FIRST_NAME}}'],
//     showTemplateTypesPage: true,
//     currentTheme: 'v2',
//     env: 'staging',
//     // onGetBrandingImages: getAllBrandingImages,
//     // onDeleteBrandingImage: deleteBrandingImage,
//     // onUploadBrandingImage: uploadBrandingImaage,
//     // onGetQRCodes: getAllQRCodes,
//     // onDeleteQRCodes: deleteQRCode,
//     // onUploadQRCode: uploadQRCode,
//     // onEditQRCode: updateQRCode,
//     // allowedTemplateSections: ['my_templates'],
//     // onGetCustomFields: getAllCustomFields,
//      restrictedProducts: [38 ],
//     // disallowedProducts: ['real_penned_letter', 'postcards'],
//     // olcTemplate: olcTemplateData,
//     // onGetOneTemplate: getOneTemplate,
//     onGetTemplates: async () => {},
//     // onSubmit: createTemplate,
//     styles: {}
//   });
// } else {
//   console.error("Root element '#root' not found in the document.");
// }

export default TemplateBuilder;
