import {
  createContext,
  type ReactNode,
  useContext,
  useMemo,
  useState,
} from 'react';

import { type StepConfig } from '@material-hu/components/design-system/Stepper/types';

import { CERTIFICATE_STEP_IDS } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type CertificateStepId } from '../types';

type CertificateCreateStepsContextValue = {
  steps: StepConfig[];
  activeStep: number;
  currentStepId: CertificateStepId;
  isFirstStep: boolean;
  isLastStep: boolean;
  goNext: () => void;
  goBack: () => void;
  showCustomBackgroundError: boolean;
  setCustomBackgroundError: (value: boolean) => void;
  clearCustomBackgroundError: () => void;
};

const CertificateCreateStepsContext = createContext<
  CertificateCreateStepsContextValue | undefined
>(undefined);

export const useCertificateCreateSteps = () => {
  const ctx = useContext(CertificateCreateStepsContext);
  if (!ctx)
    throw new Error(
      'useCertificateCreateSteps must be used within CertificateCreateStepsProvider',
    );
  return ctx;
};

type CertificateCreateStepsProviderProps = {
  children: ReactNode;
};

export const CertificateCreateStepsProvider = ({
  children,
}: CertificateCreateStepsProviderProps) => {
  const { t } = useLokaliseTranslation('learning');
  const [activeStep, setActiveStep] = useState(0);
  const [showCustomBackgroundError, setCustomBackgroundError] = useState(false);
  const clearCustomBackgroundError = () => setCustomBackgroundError(false);

  const steps: StepConfig[] = useMemo(
    () => [
      {
        id: 'template',
        title: t('settings.certificates.create_flow.template'),
      },
      { id: 'basic_information', title: t('common.basic_information') },
      { id: 'design', title: t('common.design') },
      { id: 'revision', title: t('common.revision') },
    ],
    [t],
  );

  const isFirstStep = activeStep === 0;
  const isLastStep = activeStep === steps.length - 1;

  const goNext = () => {
    if (!isLastStep) setActiveStep(prev => prev + 1);
  };

  const goBack = () => {
    if (!isFirstStep) setActiveStep(prev => prev - 1);
  };

  return (
    <CertificateCreateStepsContext.Provider
      value={{
        steps,
        activeStep,
        currentStepId: CERTIFICATE_STEP_IDS[activeStep],
        isFirstStep,
        isLastStep,
        goNext,
        goBack,
        showCustomBackgroundError,
        setCustomBackgroundError,
        clearCustomBackgroundError,
      }}
    >
      {children}
    </CertificateCreateStepsContext.Provider>
  );
};
