import React, { useState, useEffect, useMemo, useRef } from 'react';
import moment from 'moment';
import {
  Select,
  components,
  InputField,
  LoadingBar,
  Icon,
  Tooltip,
  hooks,
  NotificationTypeWrapper, IconNames, Button, Switch, utils
} from '@spglobal/ca-mfe-package-utils';
import styles from './CompanyInformation.scss';
import WithValidation from '@root/hoc/WithValidation';
import { progressTracker } from '@store/progressTracker/progressTracker.selector';
import { removeStandaloneScore } from '@root/store/generateScore/generateScore.reducer';
import { companyDataSettingSelector } from '@root/store/companyDataSettings/companyDataSettings.selector';
import { companyInformation } from '@root/store/companyInformation/companyInformation.selector';
import { scoringSelectionSelector } from '@store/scoringSelection/scoringSelection.selector';
import {
  formatDate,
  isFutureDate,
  sortFinancialStatement,
  sortSelectPeriod,
  checkPrivateCompanyType,
  checkPrivateCorporateOnly
} from '@utils/common';
import {
  getPrivateorPublicPeriodType,
  getCurrencyObject,
  getPeriodTypeConstants,
  selectValue,
  getFinancialStatementOptions,
  getSelectPeriodOptions,
  getDataSourceOptions,
  getDataSourceText,
  checkExtractedStmt,
  companyDatesPayload,
  getExtractedStatements
} from './companyInformation';
import {
  updateData,
  setFinancialStatementList,
  setSelectPeriodList,
  resetCompanyDataSettings,
  setScoreDate,
  trigCompanyInfoValidation,
  setNewSelectPeriodList
} from '@root/store/companyDataSettings/companyDataSettings.reducer';
import {
  stepSelection,
  setEnableNext,
  triggerValidationStatus,
  setActiveStep,
  setValidationStatus
} from '@root/store/progressTracker/progressTracker.reducer';
import {
  setEPDState,
  setCompanyData,
  setCompanyMetaData,
  updateModels,
  isValid,
  setLoadButtonStatus
} from '@root/store/companyInformation/companyInformation.reducer';
import {
  useGetCompanyDatesMutation
} from '@root/apis/financialStatementApi';
import {
  useGetCompanyDataMutation,
  useGetEpdStateMutation,
  useGetFinancialStatementDateMutation,
  useRiskGaugeValidateMutation,
  useGetCompanyDetailMetaDataMutation
} from '@root/apis/companyInformationApi';
import { useDispatch, useSelector, batch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import AddStatement from './AddStatement';
import SelectionChangedBanner from '@components/Common/SelectionChangedBanner';
import {
  LoaderOverlay,
  LoaderPosition,
  LoaderType
} from '@spglobal/react-components';
import {
  periodTypeConstants,
  dataSourceConstants,
  compInfoType,
  financialsType,
  financialQuarter,
  stepIds,
  trackerStatus,
  restatementType,
  dateFormat,
  stepValidationStatus,
  platforms,
  extractedDataFromPage
} from '@root/constants';
import classNames from 'classnames';
import { isRgPlusUser } from '@root/store/userInformation/userInformation.reducer';

const { DatePicker, Checkbox } = components;
const { useToastNotification, addNotificationWrapper } = hooks;

let isEpdInitialLoad = true;
let prevPeriodType = '';
let prevScoreYear = new Date().getFullYear();
let isSelectPeriodInitialLoad = true;

const CompanyInformation = props => {
  const dispatch = useDispatch();
  const { addNotification } = useToastNotification();
  const [getCompanyDates] = useGetCompanyDatesMutation();
  const [getCompanyData] = useGetCompanyDataMutation();
  const [getEpdState] = useGetEpdStateMutation();
  const [getFinancialStatementDate] = useGetFinancialStatementDateMutation();
  const [getCompanyMetaData] = useGetCompanyDetailMetaDataMutation();
  const { companySelectedData, companyMetaData, epdState, companyData, extractedData } = useSelector(companyInformation);
  const { companyId, csCompanyId, isPropCompany,
    latestStmtDate, isUnlinkCompany, isUnlinkPropCompany } = companyData;
  const cdFromStore = useSelector(companyDataSettingSelector);
  const { financialStatementList, selectPeriodList, selectedValues, companyInfoValidation,
    validateCompanyInfo, newSelectPeriodList } =
    cdFromStore;
  const isExtractedData = Boolean(Object.keys(extractedData).length);
  const isCurrencyEnabled = extractedData?.instances?.length;
  const isExtractedReportViewerPage = extractedData?.fromPage === extractedDataFromPage;
  const isExtractedCurrencyExist = (()=> isExtractedReportViewerPage && extractedData?.currencyName)();
  const isRVLinkedCompany = isExtractedReportViewerPage && extractedData?.isLinkedCompany;
  const isRVunLinkedCompany = isExtractedReportViewerPage && !extractedData?.isLinkedCompany;
  const unlinkedSource = extractedData?.unlinkedSource;
  const companyTypeId = companySelectedData?.type?.value;
  const countryCode = companySelectedData?.country?.value;
  const industry = companySelectedData?.industry?.value;
  const isPrivateCompany = checkPrivateCompanyType(companyTypeId);
  const isPrivateCorporateOnly = checkPrivateCorporateOnly(companyTypeId);
  const isPrivateorPublicPeriodType = getPrivateorPublicPeriodType(selectedValues, isPrivateCompany);
  const defaultItem = { label: 'Select an Option', value: '' };
  const cdFromStorePeriodType = selectedValues.periodType;
  const isLTMperiodType =
    cdFromStorePeriodType.label === periodTypeConstants[1].label;
  const [currentDate, setCurrentDate] = useState(selectedValues.asOfDate);
  const { activeStep, activeStepId, steppers } = useSelector(progressTracker);
  const [defaultCurrencylist, setDefaultCurrencylist] = useState([]);
  const withoutFinancialsError = epdState?.scoreWithoutFinancialsError;
  const invalidCountriesList = companyMetaData?.invalidCountriesForGScoring;
  const invalidIndustriesList = companyMetaData?.invalidIndustriesForGScoring;
  const invalidCountryIndustryGov = invalidCountriesList?.includes(countryCode)
    || invalidIndustriesList?.includes(String(industry));
  const [getRiskGaugeValidate] = useRiskGaugeValidateMutation();
  const [optionChanged, setOptionChanged] = useState(0);
  const [loadInputsBtn, setLoadInputsBtn] = useState(false);
  const isCompanyInfoAvailable = useMemo(
    ()=> Boolean(companyTypeId && countryCode && industry), [companyTypeId, countryCode, industry]
  );
  const { isOpenOnDefaultLoad: isScoringModalOpen, editedPreferences } = useSelector(scoringSelectionSelector);
  const isParentEnable = useMemo(()=> editedPreferences.includes(stepIds.PARENT_ADJUSTMENTS), [editedPreferences]);
  const isGovtEnable = useMemo(()=> editedPreferences.includes(stepIds.GOVERNMENT_SUPPORT), [editedPreferences]);
  const [loadingInputs, setLoadingInputs] = useState(false);
  const scrollRef = useRef(0);
  const [isDatepickerOpen, setDatePickerOpen] = useState(false);
  const { accessibilityOnUI: { handleAccessibilityKeys } } = utils;

  const [propCurrency, setPropCurrency] = useState(
    selectedValues?.propCurrency ? selectedValues.propCurrency : null
  );
  const [propSelectPeriod, setPropSelectPeriod] = useState(
    selectedValues?.propSelectPeriod ? selectedValues.propSelectPeriod : null
  );
  const [propFinancialStatement, setPropFinancialStatement] = useState(
    selectedValues?.propFinancialStatement
      ? selectedValues.propFinancialStatement
      : null
  );
  const [selectedCurrency, setSelectedCurrency] = useState(
    selectValue(selectedValues?.currency, defaultItem)
  );

  const [selectPeriod, setSelectPeriod] = useState(
    selectValue(selectedValues?.selectPeriod, defaultItem)
  );

  const url = new URLSearchParams(window.location.search.toLowerCase());
  const sourceValue = url.get('source');

  const setDataSourceValue = () => ((isPropCompany && !isExtractedData) || (sourceValue && sourceValue === 'p'))
    ? dataSourceConstants[1]
    : (isExtractedData ? (isRVLinkedCompany ? dataSourceConstants[0] : dataSourceConstants[2]) : dataSourceConstants[0]);

  const [selectedDataSource, setSelectedDataSource] = useState(
    selectValue(selectedValues?.dataSource, setDataSourceValue())
  );

  const [selectedPeriodType, setSelectedPeriodType] = useState(
    selectValue(cdFromStorePeriodType, isPrivateorPublicPeriodType)
  );
  const [selectedFinancialStatement, setSelectedFinancialStatement] = useState(
    selectValue(selectedValues?.financialStatement, defaultItem)
  );
  const [isFinStateLoad, setIsFinStateLoad] = useState(false);

  const [isShowLoader, setShowLoader] = useState(false);
  const [isFinancialTypeLoader, setFinancialTypeLoader] = useState(false);
  const { t } = useTranslation();

  const [disableLoadInputsBtn, setDisableLaodInputsBtn] = useState(true);

  const convertToString = val => val && val.toString() || null;

  const isRgPlus = useSelector(isRgPlusUser);

  useEffect(()=>{
    if(companySelectedData?.type?.value) {
      const isPrivate = checkPrivateCompanyType(companySelectedData.type.value);
      const periodTypeCheck = getPeriodTypeConstants(isPrivate, extractedData);
      setSelectedPeriodType(periodTypeCheck);

      dispatch(
        updateData({
          ...periodTypeCheck,
          fieldType: 'periodType'
        })
      );
    }
  }, [companySelectedData?.type?.value]);

  useEffect(()=>{
    if(optionChanged === 0) {
      setOptionChanged(optionChanged + 1);
    } else {
      setOptionChanged(optionChanged + 1);
      if(activeStepId !== stepIds.COMPANY_DATA_INPUTS) {
        batch(()=>{
          dispatch(setActiveStep({stepId: stepIds.COMPANY_DATA_INPUTS, parentStepId: ''}));
          dispatch(setValidationStatus({
            stepId: stepIds.COMPANY_DATA_INPUTS,
            validationStatus: stepValidationStatus.NOT_VALIDATED,
            parentStepId: ''}));
        });
      }
      props.setDisableInputs(true);
      setDisableLaodInputsBtn(false);
    }
  }, [selectedCurrency,
       selectPeriod,
       selectedDataSource,
       selectedPeriodType,
       selectedFinancialStatement,
       selectedValues.useFinancialStmtDateConsent,
       selectedValues.financialType,
       currentDate]);

  const getCompDataOnRestatementChange = (currentRestatementType, prevRestatementType) => {
    if (currentRestatementType && prevRestatementType && prevRestatementType !== currentRestatementType) {
      getCompData(currentRestatementType === 'LP', currentDate, isPropCompany, isUnlinkCompany);
    }
  };

  const fetchSelectPeriodData = async (isPropDataSource = false) => {
    let response = selectPeriodList;
    if (!selectPeriodList.length) {
      const asOfDate = formatDate(currentDate, dateFormat);
      const payload = companyDatesPayload({
        periodType: periodTypeConstants[0].label, asOfDate, countryCode, industryCode: convertToString(industry),
        withoutFin: true, csCompanyId, isPropDataSource, isUnlinkCompany, isUnlinkPropCompany, companyId,
        latestStmtDate
      });
      const resp: any = await getCompanyDates(payload);
      response = resp?.data?.dateValue;

      if ((!response && !resp?.data?.noData) || resp?.data?.error) {
        addNotificationWrapper(
          t('scoringui:errorNotificationMsg'),
          NotificationTypeWrapper.ERROR,
          addNotification
        );
      } else if (response?.length) {
        const [latestDate] = response;
        const checkSelectedDate = response.some(r => r.periodDate === selectPeriod?.periodDate);
        const checkNewStatements = newSelectPeriodList.some(r => r.periodDate === selectPeriod?.periodDate);
        newSelectPeriodList.forEach(n => {
          const isStatementExist = response.some(r => r.fiscalYear === n.fiscalYear);
          if(!isStatementExist){
            response = sortSelectPeriod([...response, n]);
          }
        });
        const defaultFsOption = (checkSelectedDate || checkNewStatements) ? {...selectPeriod} : {
          label: `FY ${latestDate.fiscalYear}`,
          value: latestDate.fiscalYear,
          isProp: latestDate?.restatementType === restatementType.LP,
          periodDate: latestDate?.periodDate,
          restatementType: latestDate?.restatementType
        };
        setSelectPeriod(defaultFsOption);
        if(defaultFsOption?.restatementType === restatementType.LP)
        {
          isSelectPeriodInitialLoad && getCompData(true, currentDate, isPropCompany, isUnlinkCompany);
          setPropSelectPeriod(selectPeriod);
        dispatch(
          updateData({
            ...defaultFsOption,
            fieldType: 'selectPeriod'
          })
        );
        }
        else{
          setPropSelectPeriod(null);
          dispatch(
            updateData({ value: null, fieldType: 'propSelectPeriod' })
          );
        }
        dispatch(
          updateData({
            ...defaultFsOption,
            fieldType: 'selectPeriod'
          })
        );
      }
    } else {
      getCompDataOnRestatementChange(selectedValues?.selectPeriod?.restatementType,
        selectedValues?.financialStatement?.restatementType);
    }
    setShowLoader(false);
    dispatch(setEnableNext(true));
    if (response) {
      dispatch(setSelectPeriodList(response));
    }
  };

  const fetchFinancialStatement = async (reloadFinancial, dataSource) => {
    const isPropDataSource = dataSource === dataSourceConstants[1].value;
    let response = financialStatementList;
    const periodType = selectedPeriodType?.label || periodTypeConstants[0].label;
    if (!financialStatementList.length || reloadFinancial) {
      const isExtractedStmt = checkExtractedStmt(dataSource, extractedData);
      if (isExtractedStmt) {
        response = getExtractedStatements({extractedData, selectedValues, isLTMperiodType});
      } else {
        setShowLoader(true);
        const asOfDate = formatDate(currentDate, dateFormat);
        const payload = companyDatesPayload({
          periodType, asOfDate, countryCode, industryCode: convertToString(industry),
          withoutFin: false, csCompanyId, isPropDataSource, isUnlinkCompany, isUnlinkPropCompany, companyId
        });
        const resp: any = await getCompanyDates(payload);
        response = resp?.data?.dateValue;
        if ((!response && !resp?.data?.noData) || resp?.data?.error) {
          addNotificationWrapper(
            t('scoringui:errorNotificationMsg'),
            NotificationTypeWrapper.ERROR,
            addNotification
          );
        }
      }

      if (response?.length) {
        const [latestItem] = response;
        const updatedItem = {
          ...latestItem,
          currencyIso: isExtractedCurrencyExist ? extractedData?.currencyName : latestItem.currencyIso
      };
        const updatedDate = periodType === 'FY' ? updatedItem.fiscalYear : updatedItem.periodDate;
        const checkDateExists = response.some(r => (r.periodDate === selectedFinancialStatement?.periodDate) &&
        (r.periodType === selectedFinancialStatement?.periodType) &&
         ((r.restatementType === 'LP') === selectedFinancialStatement?.isProp));
        const defaultFsOption = checkDateExists ? {...selectedFinancialStatement} : {
          label: updatedDate,
          value: isExtractedStmt ? updatedItem.newDate : updatedDate,
          fiscalQuarter: updatedItem.fiscalQuarter,
          fiscalYear: updatedItem.fiscalYear,
          isProp: updatedItem.restatementType === restatementType.LP,
          currencyCode: updatedItem.currencyIso,
          periodDate: isExtractedStmt ? updatedItem.newDate : updatedItem.periodDate,
          restatementType: updatedItem.restatementType
        };
        setSelectedFinancialStatement(defaultFsOption);
        if (updatedItem.currencyIso) {
          const currencyOption = getCurrencyObject(updatedItem.currencyIso, companyMetaData);
          if (currencyOption) {
            setSelectedCurrency(currencyOption);
            if (updatedItem.restatementType === restatementType.LP) {
              setPropCurrency(currencyOption.value);
              setPropFinancialStatement(selectedFinancialStatement);
              batch(() => {
                dispatch(
                  updateData({
                    value: currencyOption.value,
                    fieldType: 'propCurrency'
                  })
                );
                dispatch(
                  updateData({ ...currencyOption, fieldType: 'currency' })
                );
              });
            } else {
              setPropCurrency(null);
              setPropFinancialStatement(null);
              batch(() => {
                dispatch(
                  updateData({ value: null, fieldType: 'propCurrency' })
                );
                dispatch(
                  updateData({ ...currencyOption, fieldType: 'currency' })
                );
              });
            }
          }
        } else {
          if(selectedCurrency?.value) {
            dispatch(updateData({ ...selectedCurrency, fieldType: 'currency' }));
          }
        }
        dispatch(
          updateData({ ...defaultFsOption, periodType, fieldType: 'financialStatement' })
        );
        companyInfoValidation && setIsFinStateLoad(true);
      } else {
        setSelectedFinancialStatement(defaultItem);
        setSelectedCurrency(defaultItem);
      }
    }
    if (!reloadFinancial && response?.length) {
      getCompDataOnRestatementChange(selectedValues?.financialStatement?.restatementType,
        selectedValues?.selectPeriod?.restatementType);
    }

    setShowLoader(false);
    dispatch(() => {
      dispatch(setEnableNext(true));
      dispatch(setFinancialStatementList(response || []));
    });
  };

  const enableEPDStep = epdData => {
    if (Boolean(Object.keys(epdData).length)) {
      if (
        typeof epdData.scoreWithFinancials === 'boolean' && (selectedValues?.financialType === '1')
      ) {
        const selections = [
          { showStep: false, stepId: stepIds.SCORING_INPUTS, financialType: financialsType.WithoutFinancials },
          {
            isDisabled: true,
            stepId: stepIds.ADJUSTMENTS,
            nestedStepId: stepIds.PARENT_ADJUSTMENTS
          },
          {
            isDisabled: true,
            stepId: stepIds.ADJUSTMENTS,
            nestedStepId: stepIds.GOVERNMENT_SUPPORT
          }
        ];
        if(isEpdInitialLoad){
          const sizeAdjObj = steppers?.find(p => p.stepId === stepIds.ADJUSTMENTS)
          ?.nestedSteps?.find(c => c.stepId === stepIds.SIZE_ADJUSTMENTS) || {showStep: true};
          const obj = {
            showStep: sizeAdjObj?.isDisabled ? true : sizeAdjObj?.showStep,
            stepId: stepIds.ADJUSTMENTS,
            nestedStepId: stepIds.SIZE_ADJUSTMENTS
          };
          selections.push({...obj});
          isEpdInitialLoad=false;
        }
        dispatch(
          stepSelection(selections)
        );
      } else {
        dispatch(
          stepSelection([{
            showStep: true,
            stepId: stepIds.SCORING_INPUTS,
            financialType: financialsType.WithFinancials
          },
          {
            showStep: false,
            isDisabled: true,
            stepId: stepIds.ADJUSTMENTS,
            nestedStepId: stepIds.SIZE_ADJUSTMENTS
          },
          {
            showStep: isParentEnable,
            isDisabled: false,
            stepId: stepIds.ADJUSTMENTS,
            nestedStepId: stepIds.PARENT_ADJUSTMENTS
          }
          ])
        );
      }
      batch(() => {
        dispatch(setEPDState(epdData));
        dispatch(
          updateData({
            fieldType: 'financialType',
            value: epdData?.scoreWithFinancials || selectedValues?.financialType === '0' ?
             financialsType.WithFinancials : financialsType.WithoutFinancials
          })
        );
      });
    }
  };

  const fetchEPDState = async (isProp = false, isUnlink = false) => {
    isEpdInitialLoad=true;
    setFinancialTypeLoader(true);
    const asOfDate = formatDate(currentDate, dateFormat);

    const resp: any = await getEpdState({
      asOfDate,
      countryCode,
      industry: convertToString(industry),
      ...(csCompanyId && { csCompanyId }),
      ...(isProp ? { datasource: platforms.CIQPROP, companyId }
        : (isUnlink ? { datasource: platforms.CIQUNLINK, pdfnStartDate: latestStmtDate }
          : { datasource: platforms.CIQ, companyId }))
    });
    const epdData = resp?.data?.response;

    if (!epdData || resp?.data?.error) {
      addNotificationWrapper(
        t('scoringui:errorNotificationMsg'),
        NotificationTypeWrapper.ERROR,
        addNotification
      );
    }
    setFinancialTypeLoader(false);
    /**
     * Special case - bydefault set "scoreWithFinancials" true despite of scoreWithFinancials response/value
     */
    enableEPDStep({
      ...epdData,
      scoreWithFinancials: epdData?.scoreWithoutFinancialsError ?
       true : selectedValues?.financialType !== '1'
    });
  };

  useEffect(() => {
    const periodTypeValue = Object.keys(cdFromStorePeriodType).length
      ? selectedValues.periodType
      : getPeriodTypeConstants(isPrivateCompany, extractedData);
    setSelectedPeriodType(periodTypeValue);

    batch(() => {
      dispatch(updateData({ ...periodTypeValue, fieldType: 'periodType' }));
      dispatch(updateData({ ...selectedDataSource, fieldType: 'dataSource' }));
    });
  }, []);

  useEffect(() => {
    if (isCompanyInfoAvailable && !isScoringModalOpen && activeStepId === stepIds.COMPANY_DATA_INPUTS) {
      if (isPrivateCorporateOnly) {
        if (!Boolean(Object.keys(epdState).length)) {
          fetchEPDState(isPropCompany, isUnlinkCompany);
        } else {
          enableEPDStep(epdState);
        }
      } else {
        dispatch(
          updateData({
            fieldType: 'financialType',
            value: financialsType.WithFinancials
          })
        );
        dispatch(stepSelection({showStep: true,
           stepId: stepIds.SCORING_INPUTS,
           compType: companySelectedData?.type?.value}));
      }
    }
  }, [companyTypeId, countryCode, industry, isScoringModalOpen, currentDate, activeStepId]);

  const fetchDates = () => {
    if (selectedValues.financialType === financialsType.WithFinancials) {
      const currStepInputs = stepIds.COMPANY_DATA_INPUTS === activeStep.stepId &&
      prevPeriodType !== selectedPeriodType?.label;
      prevPeriodType !== selectedPeriodType?.label && (prevPeriodType = selectedPeriodType?.label);
      fetchFinancialStatement(
        currStepInputs,
        selectedValues?.dataSource?.value
      );
    } else if (
      selectedValues.financialType === financialsType.WithoutFinancials
    ) {
      setShowLoader(true);
      fetchSelectPeriodData(selectedValues?.dataSource?.value === '0');
    }
  };

  useEffect(() => {
    dispatch(setEnableNext(false));
    fetchDates();
  }, [selectedValues.financialType, selectedPeriodType, currentDate, countryCode, industry]);

  useEffect(()=>{
    if(isExtractedData && isPrivateCompany) {
      fetchDates();
    }
  }, [disableLoadInputsBtn, companyTypeId]);

  const selectPeriodSaveHandler = async selected => {
    let addedOption = {};
    const addedLabel = selected.addedyear;
    const availableIndex = selectPeriodList.findIndex(
      item => item?.fiscalYear === parseInt(selected.addedyear)
    );

    if (availableIndex < 0) {
      const [ latestDate={} ] = selectPeriodList;
      const payload = {
        ...(csCompanyId ? { csCompanyId } : { companyId }),
        newQtr: 4,
        periodTp: 'FY',
        latestAvlDate: latestDate?.periodDate ? moment(latestDate.periodDate).format('YYYY-MM-DD'): null,
        newYr: selected?.addedyear || null
      };
      const { data } = await getFinancialStatementDate(payload);
      addedOption = {
        label: `FY ${addedLabel}`,
        value: addedLabel,
        periodDate: data.newStmtDate,
        restatementType: 'LC'
      };
      const newStatement = {
        periodDate: data.newStmtDate,
        fiscalYear: parseInt(selected.addedyear),
        restatementType: 'LC'
      };
      const updatedList = [
        newStatement,
        ...selectPeriodList
      ];
      dispatch(setSelectPeriodList(sortSelectPeriod(updatedList)));
      dispatch(setNewSelectPeriodList(sortSelectPeriod([newStatement, ...newSelectPeriodList] || [])));
    } else {
      addedOption = {
        label: `FY ${selectPeriodList[availableIndex].fiscalYear}`,
        value: selectPeriodList[availableIndex].fiscalYear,
        restatementType: selectPeriodList[availableIndex].restatementType
      };
    }
    handleSelectPeriodChange('selectPeriod')([addedOption]);
  };

  const addStatementSaveHandler = async selected => {
    let addedOption = {};
    let addedLabel = selected.addedyear;
    const availableIndex = financialStatementList.findIndex(item => {
      const isQuarterAvailable =
        item?.fiscalQuarter === parseInt(selected.addedQuarter);
      const isYearAvailable = item?.fiscalYear === parseInt(selected.addedyear);
      return isLTMperiodType
        ? isQuarterAvailable && isYearAvailable
        : isYearAvailable;
    });

    if (isLTMperiodType) {
      const addedQuarter = financialQuarter.find(
        item => item.value === selected.addedQuarter
      );
      addedLabel = `${addedQuarter.label} ${selected.addedyear}`;
    }

    if (availableIndex < 0) {
      batch(() => {
        setShowLoader(true);
        dispatch(setEnableNext(false));
      });
      const [ latestFinStnDate={} ] = financialStatementList;
      const {
        fiscalYear=null,
        fiscalQuarter=null,
        periodDate=null
      } = latestFinStnDate;
      const isPeriodTypeFY = (selectedValues?.periodType?.label===periodTypeConstants[0]?.label);
      const isLatestAlDateValid = periodDate && !periodDate.includes('FQ');
      const payload = {
        ...(csCompanyId ? { csCompanyId } : { companyId }),
        latestAvlYr: isPeriodTypeFY ? null: fiscalYear,
        newQtr: isPeriodTypeFY ? 4: (Number(selected?.addedQuarter) || null),
        periodTp: selectedValues.periodType.label,
        latestAvlDate: isLatestAlDateValid ? moment(periodDate).format('YYYY-MM-DD'): null,
        newYr: Number(selected?.addedyear) || null,
        latestAvlQtr: isPeriodTypeFY ? null : fiscalQuarter
      };
      const { data } = await getFinancialStatementDate(payload);
      const newStmtDate = data?.newStmtDate;
      if(newStmtDate){
        addedOption = {
          label: addedLabel,
          value: newStmtDate,
          fiscalQuarter: selected.addedQuarter
            ? Number(selected.addedQuarter)
            : selected.addedQuarter,
          fiscalYear: Number(selected.addedyear),
          periodDate: newStmtDate
        };
        const updatedList = [
          {
            periodDate: addedLabel,
            fiscalYear: parseInt(selected.addedyear),
            fiscalQuarter: parseInt(selected.addedQuarter),
            newDate: newStmtDate
          },
          ...financialStatementList
        ];
        dispatch(setFinancialStatementList(sortFinancialStatement(updatedList)));
      } else {
        addNotificationWrapper(
          t('scoringui:errorNotificationMsg'),
          NotificationTypeWrapper.ERROR,
          addNotification
        );
      }
      batch(() => {
        setShowLoader(false);
        dispatch(setEnableNext(true));
      });
    } else {
      const periodDate = financialStatementList[availableIndex].periodDate;
      const checkPeriodType = isLTMperiodType
        ? periodDate
        : financialStatementList[availableIndex].fiscalYear;
      addedOption = {
        label: checkPeriodType,
        value: checkPeriodType,
        currencyCode: financialStatementList[availableIndex].currencyIso,
        fiscalQuarter: financialStatementList[availableIndex].fiscalQuarter,
        fiscalYear: financialStatementList[availableIndex].fiscalYear,
        periodDate: isLTMperiodType
          ? periodDate
          : periodDate.length > 4
          ? periodDate
          : `FY ${periodDate}`
      };
    }

    handleFinancialStatementChange('financialStatement')([addedOption]);
  };

  const setProps = (
    propType,
    isDisabled,
    isInvalid,
    inFieldLabelReq = true
  ) => {
    const prop = {
      inFieldLabel:
        propType === compInfoType.PeriodType
          ? t('scoringui:companyInput:periodType')
          : propType === compInfoType.FinancialStatement
          ? t('scoringui:companyInput:financialStatement')
          : propType === compInfoType.DataSource
          ? t('scoringui:companyInput:dataSource')
          : propType === compInfoType.Currency
          ? t('scoringui:companyInput:currency')
          : propType === compInfoType.SelectPeriod
          ? t('scoringui:companyInput:selectPeriod')
          : t('scoringui:companyInput:asOfDate') + ':',
      inFieldLabelRequired: inFieldLabelReq,
      disabled: isDisabled,
      invalid: isInvalid,
      componentSize: 'small',
      requiredFeedbackText: t('scoringui:companyInput:feedBacktext')
    };
    return prop;
  };

  const [periodTypeProps, setPeriodTypeProps] = useState(
    setProps(compInfoType.PeriodType, false, false)
  );
  const [financialStatementProps, setFinancialStatementProps] = useState(
    setProps(compInfoType.FinancialStatement, false, false)
  );
  const [dataSourceProps, setDataSourceProps] = useState(
    setProps(compInfoType.DataSource, false, false)
  );
  const [currencyProps, setCurrencyProps] = useState(
    setProps(compInfoType.Currency, false, false)
  );
  const [selectPeriodProps, setSelectPeriodProps] = useState(
    setProps(compInfoType.SelectPeriod, false, false)
  );

  const asOfDateProps = setProps(compInfoType.AsOfDate, false, false);

  const getData = companyMetaData => {
    if (companyMetaData && !companyMetaData?.error) {
      const currencyData = companyMetaData.currencies;
      setDefaultCurrencylist(
        currencyData?.map(c => ({
          value: c.code,
          label: c.name + '[' + c.code + ']'
        }))
      );
    }
  };

  useEffect(() => {
    if (companyMetaData && !companyMetaData?.error) {
      getData(companyMetaData);
    }
  }, [companyMetaData]);

  const modalLookUpApi = async () => {
    setLoadingInputs(true);
    const payload = {
      countryCode: companySelectedData?.country?.value,
      industryCode: companySelectedData?.industry?.value,
      companyType: companySelectedData?.type?.label?.split(' ')[0].toUpperCase(),
      asOfDate: formatDate(
        selectedValues?.asOfDate,
        'YYYY-MM-DD'
      )
    };
    if(companyId && companyId !== '0'){
       payload.ciqCompanyId = companyId;
    }
    const resp = await getRiskGaugeValidate(payload);
    if (resp?.data?.models?.isValid) {
        dispatch(updateData({
          label: 'asOfDate',
          value: currentDate
        }));
        dispatch(updateModels(resp?.data?.models));
        dispatch(isValid(true));
        props.setLoadInputsData(true);
        props.setDisableInputs(false);
        dispatch(triggerValidationStatus(false));
        setLoadingInputs(false);
        setDisableLaodInputsBtn(true);
    } else {
      dispatch(updateModels(true));
      setLoadingInputs(false);
    }
  };

  const companyMetaDataApi = () => {
    const scoreYear = new Date(selectedValues?.scoreDate).getFullYear();
    if (prevScoreYear !== scoreYear) {
      getCompanyMetaData(scoreYear).then(metaData => {
        if (!metaData?.data?.error) {
          prevScoreYear = scoreYear;
          dispatch(setCompanyMetaData(metaData?.data?.data));
        }
      });
    }
  };

  useEffect(() => {
    if (loadInputsBtn &&
      activeStep.validationStatus === stepValidationStatus.VALID && activeStep.stepId === stepIds.COMPANY_DATA_INPUTS) {
      props.setLoadInputsData(false);
      modalLookUpApi();
      companyMetaDataApi();
      setLoadInputsBtn(false);
    }
  }, [activeStep.validationStatus, loadInputsBtn]);

  const getCompData = async (isProp, selectedAsOfDate,isPropCompany, isUnlink = false) => {
    const asOfDate = formatDate(selectedAsOfDate ? selectedAsOfDate : currentDate, dateFormat);
    const companyDataRequest = {
      period: {
        periodType: selectedPeriodType?.label,
        quarter: selectedFinancialStatement?.fiscalQuarter,
        year: selectedFinancialStatement?.fiscalYear
      },
      asOfDate,
      isPropCompany,
      isUnlinkPropCompany,
      ...(csCompanyId && { csCompanyId }),
      ...(isProp ? { datasource: platforms.CIQPROP, companyId }
        : (isUnlink ? { datasource: platforms.CIQUNLINK }
          : { datasource: platforms.CIQ, companyId })),
      version: isRgPlus ? 'V3' : 'V2'
    };

    const resp: any = await getCompanyData(companyDataRequest);

    if (resp?.data && !resp?.data?.error) {
      dispatch(setCompanyData(resp?.data?.data));
    }
    isSelectPeriodInitialLoad = false;
  };

  const handleOnclick = fieldType => value => {
    const compTypeObj = { fieldType, value: value.target.checked };
    batch(() => {
    dispatch(updateData(compTypeObj));
    dispatch(setScoreDate({'checked':value.target.checked}));
    });

    window.scrollTo(0, scrollRef.current);
  };

  const handleOptionClick = fieldType => event => {
    const currToggleValue = event.target.value;
    let sizeAdjustmentObj = {
      showStep: false,
      isDisabled: true,
      stepId: stepIds.ADJUSTMENTS,
      nestedStepId: stepIds.SIZE_ADJUSTMENTS,
      financialType: currToggleValue,
      status: trackerStatus.NOT_SELECTED
    };
    let parentAdjustment = {
      showStep: isParentEnable,
      isDisabled: false,
      stepId: stepIds.ADJUSTMENTS,
      nestedStepId: stepIds.PARENT_ADJUSTMENTS
    };
    let govtSupport = {
      showStep: isGovtEnable,
      isDisabled: false,
      stepId: stepIds.ADJUSTMENTS,
      nestedStepId: stepIds.GOVERNMENT_SUPPORT
    };
    if (currToggleValue === financialsType.WithoutFinancials) {
      setSelectPeriod(
        selectedValues.selectPeriod &&
          Object.keys(selectedValues.selectPeriod).length > 0
          ? selectedValues.selectPeriod
          : defaultItem
      );
      sizeAdjustmentObj = {
        ...sizeAdjustmentObj,
        showStep: true,
        isDisabled: false,
        status: trackerStatus.SELECTED
      };
      parentAdjustment = {
        ...parentAdjustment,
        isDisabled: true,
        showStep: false
      };
      govtSupport = { ...govtSupport, isDisabled: true, showStep: false };
      if (isParentEnable || isGovtEnable) {
        addNotificationWrapper(
          <SelectionChangedBanner
            disableAdjStepsNotes={[
              t('scoringui:stepTracker:pAndGDisabledNote1'),
              '',
              t('scoringui:stepTracker:pAndGDisabledNote2')
            ]}
            disableAdjSteps={[
              t('scoringui:stepTracker:parentCompanyAdjustments'),
              t('scoringui:stepTracker:governmentSupport')
            ]} />,
          NotificationTypeWrapper.WARNING,
          addNotification,
          10000
        );
      }
    } else {
      setSelectedFinancialStatement(
        selectedValues.financialStatement &&
          Object.keys(selectedValues.financialStatement).length > 0
          ? selectedValues.financialStatement
          : defaultItem
      );
    }

    if(invalidCountryIndustryGov){
      govtSupport = {
        ...govtSupport,
        showStep: false,
        isDisabled: true
      };
    }

    const compTypeObj = { fieldType, value: currToggleValue };
    batch(() => {
      dispatch(setEPDState({
        ...epdState,
        scoreWithFinancials: currToggleValue === financialsType.WithFinancials
      }));
      dispatch(updateData(compTypeObj));
      dispatch(
        stepSelection([sizeAdjustmentObj, parentAdjustment, govtSupport])
      );
    });
  };

  const handleDateChange = fieldType => date => {
    setCurrentDate(date);
    const compTypeObj = {
      label: fieldType,
      value: date,
      ...((fieldType === 'asOfDate') && {
        prevDate: selectedValues.asOfDate
      })
    };
    batch(() => {
      dispatch(
        resetCompanyDataSettings({
          [fieldType]: date,
          ['financialType']: companySelectedData?.type?.value === '2' ? selectedValues?.financialType : '0'
        })
      );
      dispatch(updateData(compTypeObj));
    });
    if (selectedValues.dataSource?.value === '0' || isPropCompany ||
      (isPrivateCompany && selectedValues?.selectPeriod?.restatementtype === 'LP')) {
      getCompData(true, date,isPropCompany, isUnlinkCompany);
    }
  };

  const handlePeriodTypeChange = fieldType => period => {
    setPeriodTypeProps(setProps(compInfoType.PeriodType, false, false));
    setSelectedPeriodType(period[0]);
    const compTypeObj = { ...period[0], fieldType };
    const compResetObj = {
      asOfDate: selectedValues?.asOfDate,
      financialType: selectedValues.financialType
    };
    batch(() => {
      dispatch(resetCompanyDataSettings(compResetObj));
      dispatch(updateData(compTypeObj));
    });
  };

  const handleFinancialStatementChange =
    fieldType => financialStatement => {
      setFinancialStatementProps(
        setProps(compInfoType.FinancialStatement, false, false)
      );
      setSelectedFinancialStatement(financialStatement[0]);
      const compTypeObj = { ...financialStatement[0], fieldType };
      dispatch(updateData(compTypeObj));

      if (financialStatement[0].currencyCode) {
        if (financialStatement[0].isProp) {
          setPropCurrency(financialStatement[0].currencyCode);
          dispatch(
            updateData({
              value: financialStatement[0].currencyCode,
              fieldType: 'propCurrency'
            })
          );
        } else {
          setPropCurrency(null);
          dispatch(updateData({ value: null, fieldType: 'propCurrency' }));
        }
        const updatedCurrency = getCurrencyObject(
          financialStatement[0].currencyCode,
          companyMetaData
        );
        if (updatedCurrency) {
          handleCurrencyChange('currency')([updatedCurrency]);
        }
      }
    };

  const handleSelectPeriodChange = fieldType => selectPeriod => {
    setSelectPeriodProps(setProps(compInfoType.SelectPeriod, false, false));
    setSelectPeriod(selectPeriod[0]);
    const compTypeObj = { ...selectPeriod[0], fieldType };
    dispatch(updateData(compTypeObj));
    const currentRestatementType = selectPeriod[0]?.restatementType;
    const prevRestatementType = selectedValues?.selectPeriod?.restatementType;
    if (currentRestatementType && prevRestatementType && prevRestatementType !== currentRestatementType) {
      getCompData(selectPeriod[0]?.restatementType === 'LP', currentDate, isPropCompany, isUnlinkCompany);
    }
  };

  const handleCurrencyChange = fieldType => currency => {
    setCurrencyProps(setProps(compInfoType.Currency, false, false));
    setSelectedCurrency(currency[0]);
    const compTypeObj = { ...currency[0], fieldType };
    dispatch(updateData(compTypeObj));
  };

  const handleDataSourceChange = fieldType => dataSource => {
    setDataSourceProps(setProps(compInfoType.DataSource, false, false));
    setSelectedDataSource(dataSource[0]);
    const compTypeObj = { ...dataSource[0], fieldType };
    dispatch(updateData(compTypeObj));
    setPropCurrency(null);
    dispatch(updateData({ value: null, fieldType: 'propCurrency' }));
    fetchFinancialStatement(
      true,
      dataSource[0]?.value
    );

      getCompData(dataSource[0]?.value === '0', currentDate, isPropCompany, isUnlinkCompany);
  };

  const showWithFinancial = !(
    isPrivateCompany &&
    selectedValues.financialType === financialsType.WithoutFinancials
  );

  const withoutFinTooltip = (
    <span className={'spg-d-inline-block radio-icon'}>
      <Tooltip
        triggerElement={
          <span className="spg-ml-xs">
            <Icon icon={IconNames.CIRCLE_INFO_O} size={'xsmall'} />
          </span>
        }
      >
        <div>
          <div className="spg-text spg-text-bold spg-pb-sm">
            {t('scoringui:companyInput:withoutFinancialdisabledTitle')}
          </div>
          <div className="spg-text">
            {t('scoringui:companyInput:withoutFinancialdisabledDesc')}
          </div>
        </div>
      </Tooltip>
    </span>
  );

  const loadInputsClick = () => {
    if(companyInfoValidation && activeStep.stepId === stepIds.COMPANY_DATA_INPUTS) {
      batch(() => {
        dispatch(removeStandaloneScore());
        dispatch(triggerValidationStatus(true));
        setLoadInputsBtn(true);
      });
    } else {
      dispatch(trigCompanyInfoValidation(true));
      setIsFinStateLoad(false);
    }
  };

  useEffect(()=>{
    if(isFinStateLoad && companyInfoValidation && validateCompanyInfo){
      if(activeStep.stepId === stepIds.COMPANY_DATA_INPUTS) {
        batch(()=>{
          dispatch(triggerValidationStatus(true));
        });
        setLoadInputsBtn(true);
        setIsFinStateLoad(false);
      }
    }
  }, [isFinStateLoad]);

  const handleScroll = e => {
    e.preventDefault();
    scrollRef.current = window.scrollY;
  };

  useEffect(()=>{
    window.addEventListener('scroll', handleScroll);
    if(companyInfoValidation === null) {
      dispatch(trigCompanyInfoValidation(false));
    }

    return(() => {
      window.removeEventListener('scroll', handleScroll);
    });
  }, [companyInfoValidation]);

  useEffect(() => {
    dispatch(setLoadButtonStatus(
      Boolean(!isCompanyInfoAvailable || disableLoadInputsBtn)
    ));
  }, [isCompanyInfoAvailable, disableLoadInputsBtn]);

 const isEditableDataSource = () => (companyId && (!isUnlinkCompany || isExtractedData));
 const checkToggleDisable = () => isFinancialTypeLoader || withoutFinancialsError || !Boolean(selectedValues.financialType);
 const loadInputsDisable = () => (!isCompanyInfoAvailable || disableLoadInputsBtn);
  return (
    <div className={styles['company-information-container']}>
      <div className={styles['information-container']}>
        <div className='spg-d-flex spg-align-center spg-justify-between'>
          <div className='spg-w-75'>
            <div className={styles['content-text']}>
              {t('scoringui:companyInput:calculateScore')}
            </div>
            {isPrivateCorporateOnly && (
              <div className={`spg-col ${styles['company-financials']}`}>
                <div className="spg-col spg-pl-0">
                  {isFinancialTypeLoader && (
                    <div className="spg-w-25 spg-mb-xs">
                      <LoadingBar
                        type={LoaderType.TOP}
                        position={LoaderPosition.STATIC}
                        overlay={LoaderOverlay.DEFAULT}
                      ></LoadingBar>
                    </div>
                  )}
                  <div className={styles['radio-class']}>
                    <Switch
                      label="Calculate Score with Financials"
                      checked={selectedValues.financialType === '0'}
                      disabled={checkToggleDisable()}
                      onKeyDown={e => handleAccessibilityKeys(e, {
                        onEnter: ()=>{
                          handleOptionClick('financialType')(
                            { target: { value: selectedValues.financialType==='0' ? '1' : '0' } }
                          );
                        }
                      })}
                      onChange={e => handleOptionClick('financialType')(
                        { target: { value: e.target.checked ? '0' : '1' } }
                      )} />
                    {withoutFinancialsError && withoutFinTooltip}
                  </div>
                </div>
              </div>
            )}
            <div
              className={`spg-d-flex spg-justify-between
            ${styles['company-information-container']} ${styles['company-information-width']}`}
            >
              <div className={`spg-mb-md ${styles['date-Picker']} ${styles['width-30']}`}>
                <DatePicker
                  selected={currentDate}
                  open={isDatepickerOpen}
                  onChange={handleDateChange('asOfDate')}
                  format="MM/DD/YYYY"
                  disabledDate={isFutureDate}
                  value={currentDate}
                  triggerComponent={
                    <InputField
                      onKeyDown={e => handleAccessibilityKeys(e, {
                        onEscape: ()=>setDatePickerOpen(false),
                        onTab: ()=>setDatePickerOpen(false),
                        onEnter: ()=>setDatePickerOpen(true)
                      }, true)}
                      type="text"
                      placeholder={t('scoringui:companyInput:selectDate')}
                      elementProps={{
                        ...asOfDateProps,
                        icon: IconNames.CALENDAR,
                        value: formatDate(currentDate, 'MM/DD/YYYY')
                      }}
                    ></InputField>
                  }
                />
              </div>
              <div className={styles['width-30']}>
                {showWithFinancial && (
                  <Select
                    dataSource={periodTypeConstants}
                    defaultItem={selectedPeriodType}
                    labelField={'label'}
                    valueField={'value'}
                    isMulti={false}
                    isControlButtons={false}
                    propValue={null}
                    isSearchable={false}
                    maxOptionsToSelect={1}
                    elementProps={{
                      ...periodTypeProps,
                      values: [selectedPeriodType]
                    }}
                    onChange={handlePeriodTypeChange('periodType')}
                    triggerValidation={props.triggerValidation}
                    validationcallback={props.validationHandler}
                    requiredFeedbackText= {t('scoringui:companyInput:feedBacktext')}
                  />
                )}
              </div>
              {showWithFinancial &&
                (isEditableDataSource() ? (
                  <div className={styles['width-30']}>
                    <Select
                      dataSource={getDataSourceOptions(isPropCompany,
                        isUnlinkPropCompany, isExtractedData, isRVLinkedCompany)}
                      defaultItem={selectedDataSource}
                      labelField={'label'}
                      valueField={'value'}
                      isMulti={false}
                      isControlButtons={false}
                      propValue={null}
                      isSearchable={false}
                      sortOrder={'desc'}
                      maxOptionsToSelect={1}
                      elementProps={{
                        ...dataSourceProps,
                        values: [selectedDataSource]
                      }}
                      onChange={handleDataSourceChange('dataSource')}
                      triggerValidation={props.triggerValidation}
                      validationcallback={props.validationHandler}
                      requiredFeedbackText= {t('scoringui:companyInput:feedBacktext')}
                    />
                  </div>
                ) : (
                  <div className={`${styles['width-30']} spg-pt-xs`}>
                    <span className="spg-text spg-text-medium spg-text-bold">
                      {t('scoringui:PCA:datasource')}
                    </span>
                    <span className="spg-text spg-text-medium spg-text-italic spg-pl-sm">
                      {getDataSourceText(t, isUnlinkCompany, isExtractedData, isRVunLinkedCompany,
                        unlinkedSource === 'CREDITSAFE')}
                    </span>
                  </div>
                ))}
            </div>
            <div
              className={`spg-d-flex spg-justify-between
            ${styles['company-information-container']} ${
                styles[showWithFinancial ? '' : 'company-select-hidden']
              }`}
            >
              <div
                className={classNames(
                  styles['width-30'],
                  styles['company-information-prop']
                )}
              >
                {isShowLoader && (
                  <LoadingBar
                    type={LoaderType.TOP}
                    position={LoaderPosition.STATIC}
                    overlay={LoaderOverlay.DEFAULT}
                  ></LoadingBar>
                )}
                <Select
                  dataSource={getFinancialStatementOptions(financialStatementList)}
                  defaultItem={selectedFinancialStatement}
                  labelField={'label'}
                  valueField={'value'}
                  propValue={propFinancialStatement}
                  isMulti={false}
                  isControlButtons={false}
                  orderBy="id"
                  isRequired={
                    selectedValues.financialType === financialsType.WithFinancials
                  }
                  isSearchable={true}
                  maxOptionsToSelect={1}
                  elementProps={{
                    ...financialStatementProps,
                    values: [selectedFinancialStatement],
                    disabled: isShowLoader
                  }}
                  onChange={handleFinancialStatementChange('financialStatement')}
                  triggerValidation={props.triggerValidation}
                  validationcallback={props.validationHandler}
                  showAddOption={true}
                  footerElement={<AddStatement onSave={addStatementSaveHandler} />}
                  requiredFeedbackText= {t('scoringui:companyInput:feedBacktext')}
                />
              </div>
              <div
                className={classNames(
                  styles['width-30'],
                  styles['company-information-prop']
                )}
              >
                <Select
                  dataSource={defaultCurrencylist}
                  defaultItem={selectedCurrency}
                  labelField={'label'}
                  valueField={'value'}
                  isMulti={false}
                  isControlButtons={false}
                  isRequired={
                    selectedValues.financialType === financialsType.WithFinancials
                  }
                  propValue={propCurrency}
                  isSearchable={true}
                  maxOptionsToSelect={1}
                  elementProps={{
                    ...currencyProps,
                    values: [selectedCurrency],
                    disabled: extractedData?.fromPage === extractedDataFromPage
                    ? isCurrencyEnabled
                    : selectedValues?.dataSource?.value === dataSourceConstants[2].value
                  }}
                  onChange={handleCurrencyChange('currency')}
                  triggerValidation={props.triggerValidation}
                  validationcallback={props.validationHandler}
                  requiredFeedbackText= {t('scoringui:companyInput:feedBacktext')}
                />
              </div>
              <div className={styles['width-30']}></div>
            </div>
            <div
              className={`spg-d-flex ${
                styles['company-information-container']
              }
              ${styles[showWithFinancial ? 'company-select-hidden' : '']}`}
            >
                <div
                className={classNames(
                  styles['width-30'],
                  styles['company-information-prop']
                )}
              >
              <div>
                {isShowLoader && (
                  <LoadingBar
                    type={LoaderType.TOP}
                    position={LoaderPosition.STATIC}
                    overlay={LoaderOverlay.DEFAULT}
                  ></LoadingBar>
                )}
                <Select
                  dataSource={getSelectPeriodOptions(selectPeriodList)}
                  defaultItem={selectPeriod}
                  labelField={'label'}
                  valueField={'value'}
                  isMulti={false}
                  isControlButtons={false}
                  propValue={propSelectPeriod}
                  isSearchable={true}
                  orderBy="id"
                  isRequired={
                    selectedValues.financialType ===
                    financialsType.WithoutFinancials
                  }
                  maxOptionsToSelect={1}
                  elementProps={{
                    ...selectPeriodProps,
                    values: [selectPeriod],
                    disabled: isShowLoader
                  }}
                  onChange={handleSelectPeriodChange('selectPeriod')}
                  triggerValidation={props.triggerValidation}
                  validationcallback={props.validationHandler}
                  showAddOption={true}
                  footerElement={<AddStatement onSave={selectPeriodSaveHandler} />}
                ></Select>
              </div>
            </div>
            </div>
            <div className={`${styles['checkbox-text']}`}>
              <Checkbox
                id="check"
                name="check"
                onKeyDown={e => handleAccessibilityKeys(e, {
                  onEnter: ()=>{
                    const value = !selectedValues?.useFinancialStmtDateConsent;
                    batch(() => {
                      dispatch(updateData({
                        fieldType: 'useFinancialStmtDateConsent',
                        value
                      }));
                      dispatch(setScoreDate({'checked':value}));
                    });
                  }
                })}
                checked={selectedValues.useFinancialStmtDateConsent}
                label={t('scoringui:companyInput:dataAndExchange')}
                className={`${styles['content-text']}`}
                onClick={handleOnclick('useFinancialStmtDateConsent')}
              />
            </div>
          </div>
          {selectedValues?.financialType !== '1' && <div className={styles['load-inputs-btn']}>
            <Tooltip
              disabled={!loadInputsDisable()}
              triggerElement={
                <span>
                  <Button
                    className='spg-mr-xs'
                    purpose={'primary'}
                    disabled={loadInputsDisable()}
                    onClick={loadInputsClick}
                    size={utils.Helpers.Size.SMALL}
                    loading={loadingInputs}>{t('scoringui:companyInput:loadInputs')}</Button>
                </span>
              }
            >
              { !isCompanyInfoAvailable ?
              <span
              dangerouslySetInnerHTML={{__html:
               (t('scoringui:companyInput:loadInputsSelectCompanyInfoText')
               .replace(t('scoringui:companyInput:companyType'), `<b>${t('scoringui:companyInput:companyType')}</b>`)
               .replace(t('scoringui:companyInput:countryText'), `<b>${t('scoringui:companyInput:countryText')}</b>`)
               .replace(t('scoringui:companyInput:industry'), `<b>${t('scoringui:companyInput:industry')}</b>`))}}>
             </span> : <span>
                {t('scoringui:companyInput:loadInputsDisableText')}
              </span>}
            </Tooltip>
          </div>}
        </div>
      </div>
    </div>
  );
};

export default WithValidation(CompanyInformation);
