import { type FC } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { styled } from '@material-hu/mui/styles';

import { FormFileUploadProvider } from 'src/pages/dashboard/forms/FormFileUploadContext';
import { type Step } from 'src/types/forms';
import { getQuestionName, getQuestions, hasMandatory } from 'src/utils/form';

import FormContent from 'src/components/dashboard/form/formDetail/FormContent';
import FormHeader from 'src/components/dashboard/form/formDetail/FormHeader';
import FormSubmit from 'src/components/dashboard/form/formDetail/FormSubmit';

const Form = styled('form')({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  width: '100%',
  position: 'relative',
  '& > div:last-child': {
    marginBottom: '100px',
  },
});

export type FormStepProps = {
  step: Step;
  totalSteps: number;
  currentStep: number;
  onNext?: () => void;
  onBack?: () => void;
};

export const FormStep: FC<FormStepProps> = props => {
  const {
    step,
    totalSteps,
    currentStep,
    onNext = () => null,
    onBack = () => null,
  } = props;

  const form = useForm({});

  const { handleSubmit } = form;

  const questions = getQuestions(step.questions);

  return (
    <>
      <FormHeader
        title={step.title}
        description={step.description}
        hasMandatory={hasMandatory(questions)}
      />
      <FormProvider {...form}>
        <Form onSubmit={handleSubmit(onNext)}>
          <FormFileUploadProvider>
            <FormSubmit
              handleBack={onBack}
              currentStep={currentStep}
              steps={totalSteps}
              formFilled
            />
            {questions.map((config, index) => (
              <FormContent
                key={config.id}
                name={`${currentStep}-${index}-${getQuestionName(config)}`}
                answerInput={config}
                formFilled
                {...config}
              />
            ))}
          </FormFileUploadProvider>
        </Form>
      </FormProvider>
    </>
  );
};

export default FormStep;
