import React, { useRef, useState, useEffect } from 'react';
import { makeCommonDataServices, makeCommonTransformer } from '@pos/base/domain/factories';
import { IBaseTransformerRepository } from '@pos/base/domain/repositories';
import {
  ModuleProviderProps,
  SinglePageDetailConfigEntity,
  SinglePageFormConfigEntity,
  UseAppModuleHookEntity,
} from './app-module.entity';
import { BaseEntity } from '@pos/base/domain/entities';
// import { useNavigate } from 'react-router-dom';
import { useRecoilState } from 'recoil';

import { Form } from 'antd';
import { AgGridReact } from 'ag-grid-react';
import { RefreshServerSideParams } from 'ag-grid-community';
import { StoragePrivilege, StorageUserData } from '@pos/base/data/local-data-services';
import { capitalizeEachWord } from '@pos/base/infrastructure/helpers';
import { defaultAppPrivilege } from '@pos/base/infrastructure/constants';

const commonTransformer: IBaseTransformerRepository<any> = makeCommonTransformer<any>();
export const ModuleProviderContext = React.createContext<UseAppModuleHookEntity<any>>(null as any);

export function ModuleProvider<E extends BaseEntity = BaseEntity>(props: ModuleProviderProps) {
  const { configuration, children } = props;
  const {
    webUrl,
    moduleKey,
    tabTitle,
    dataServicesTransformer,
    dataServicesConfig,

    moduleCategory,
    moduleType,

    metaIndexDataAtomState,
    selectedIndexDataAtomState,
    filterIndexDataAtomState,

    privilegeAtomState,
    singlePageFormType,
    singlePageDetailType,
  } = configuration;

  //   const navigate = useNavigate();

  const [formControl] = Form.useForm();
  const [formControlDetail] = Form.useForm();
  const [formControlFilter] = Form.useForm();

  const [privilege, setPrivilege] = useRecoilState<any>(privilegeAtomState);

  const [metaData, setMetaData] = useRecoilState<any>(metaIndexDataAtomState);
  const [filterData, setFilterData] = useRecoilState<any>(filterIndexDataAtomState);
  const [selectedData, setSelectedData] = useRecoilState<any>(selectedIndexDataAtomState);

  const [createAnotherData, setCreateAnotherData] = useState<boolean>(false);
  const [loadingGetDataDetail, setLoadingGetDataDetail] = useState<boolean>(false);
  const [loadingGetDataForm, setLoadingGetDataForm] = useState<boolean>(false);

  const [gridConfiguration, setGridConfiguration] = useState<any>();

  const [singlePageDetailConfig, setSinglePageDetailConfig] = useState<SinglePageDetailConfigEntity>({
    open: false,
    dataId: undefined,
  });
  const [singlePageFormConfig, setSinglePageFormConfig] = useState<SinglePageFormConfigEntity>({
    open: false,
    dataId: undefined,
    type: 'create',
  });

  const dataServices = makeCommonDataServices({
    ...dataServicesConfig,
    moduleKey: 'ADMIN_PAGE.' + moduleKey,
  }); // use makeCommonDataServices at react-base
  const transformer: IBaseTransformerRepository<E> = (dataServicesTransformer as any) ?? commonTransformer;

  const indexGridRef = useRef<AgGridReact>(null);

  async function handleRefreshIndexTable({ route = [], purge = true }: RefreshServerSideParams = {}) {
    indexGridRef?.current?.api.refreshServerSide({ route, purge });
  }

  const ModuleProviderValue: UseAppModuleHookEntity = {
    webUrl: webUrl,
    moduleKey: 'ADMIN_PAGE.' + moduleKey,
    moduleType: moduleType,
    moduleCategory: moduleCategory,

    dataServices: dataServices,
    dataServicesConfig: dataServicesConfig,
    privilege: privilege,
    transformer: transformer,

    metaData: metaData,
    setMetaData: setMetaData,
    filterData: filterData,
    setFilterData: setFilterData,
    selectedData: selectedData,
    setSelectedData: setSelectedData,

    formControl: formControl,
    formControlDetail: formControlDetail,
    formControlFilter: formControlFilter,

    singlePageFormType: singlePageFormType,
    singlePageFormConfig: singlePageFormConfig,
    setSinglePageFormConfig: setSinglePageFormConfig,

    singlePageDetailType: singlePageDetailType,
    singlePageDetailConfig: singlePageDetailConfig,
    setSinglePageDetailConfig: setSinglePageDetailConfig,

    createAnotherData: createAnotherData,
    setCreateAnotherData: setCreateAnotherData,

    loadingGetDataDetail: loadingGetDataDetail,
    setLoadingGetDataDetail: setLoadingGetDataDetail,
    loadingGetDataForm: loadingGetDataForm,
    setLoadingGetDataForm: setLoadingGetDataForm,

    indexGridRef: indexGridRef,
    handleRefreshIndexTable,

    gridConfiguration,
    setGridConfiguration,
  };

  async function setupPrivilege() {
    const moduleKey = configuration.moduleKey;
    const storePrivilege = await StoragePrivilege.get();
    const user = await StorageUserData.get();
    let appPrivilege = storePrivilege?.[moduleKey?.split('.')?.[0]];
    if (user?.role === 'superadmin') appPrivilege = defaultAppPrivilege;
    setPrivilege(appPrivilege);
  }

  useEffect(() => {
    if (Object.keys(privilege ?? {}).length === 0) {
      setupPrivilege();
    } else {
      //   TODO => UNCOMMENT CODE BELLOW IF PRIVILEGE MODULE IS READY
      //   const allowView = privilege?.access_right?.view;
      //   if (!allowView) navigate('/403', { replace: true });
    }
  }, [privilege]);

  useEffect(() => {
    if (tabTitle) document.title = `POS - ${capitalizeEachWord(tabTitle)}`;
    return () => {
      document.title = 'POS';
    };
  }, [tabTitle]);

  return <ModuleProviderContext.Provider value={ModuleProviderValue}>{children}</ModuleProviderContext.Provider>;
}
