import { type FC, useState } from 'react';
import { useFormContext } from 'react-hook-form';

import Container from '@material-hu/mui/Container';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Alert from '@material-hu/components/design-system/Alert';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';

import { generateFormProgressData } from 'src/pages/dashboard/serviceManagement/utils';
import {
  type FormSectionBody,
  type InputType,
  type SectionComponent,
  type SectionContent,
  type ServiceItem,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { FormInputComponent } from '../../../form/FormInputComponent';
import CoverPicture from '../../../general/CoverPicture';
import TypographyLinkSensitive from '../../../general/TypographyLinkSensitive';
import { getUploadingFieldNames } from '../../../utils';

import ComponentTitle from './ComponentTitle';
import Description from './Description';
import Footer from './Footer';
import FormCompletionSkeleton from './FormCompletionSkeleton';

export const FOOTER_HEIGHT = '94px';

type Props = {
  currentForm: SectionContent | null;
  isLoading: boolean;
  isLoadingSection: boolean;
  serviceItem: ServiceItem | undefined;
  createFormMutation: { isLoading: boolean };
  updateSectionMutation: (data: FormSectionBody, options?: unknown) => void;
  handleCloseFormModal: () => void;
  showDescription: boolean;
};

const RegularFormCompletion: FC<Props> = ({
  currentForm,
  isLoading,
  isLoadingSection,
  createFormMutation,
  serviceItem,
  updateSectionMutation,
  handleCloseFormModal,
  showDescription,
}) => {
  const { t } = useLokaliseTranslation('service_management');

  const {
    getValues,
    trigger,
    watch,
    formState: { errors },
  } = useFormContext();

  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const uploadingFieldNames = getUploadingFieldNames(currentForm);
  const uploadingValues = watch(uploadingFieldNames);
  const isUploadingFiles = uploadingValues.some(Boolean);

  const handleNextSection = async () => {
    if (isLoadingSection || createFormMutation.isLoading || isUploadingFiles)
      return;

    if (currentForm) {
      const isValidForm = await trigger(
        currentForm.components.map(
          (component: SectionComponent) => component.nameId,
        ),
      );
      if (isValidForm) {
        const formValues = getValues();
        const formDataBody = generateFormProgressData(currentForm, formValues);
        updateSectionMutation(formDataBody);
        setErrorMessage(null);
      } else {
        const firstErrorComponent = currentForm.components.find(
          (component: SectionComponent) => errors[component.nameId],
        );
        if (firstErrorComponent) {
          const element = document.getElementById(
            `form-field-${firstErrorComponent.nameId}`,
          );
          element?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }

        const requiredError = Object.values(errors).some(
          error => error?.type === 'required',
        );
        setErrorMessage(
          requiredError
            ? t('required_questions_message')
            : t('wrong_pattern_message'),
        );
      }
    }
  };

  const handleGoBackSection = async () => {
    if (isLoadingSection || createFormMutation.isLoading || isUploadingFiles)
      return;

    if (currentForm) {
      const formValues = getValues();
      const formDataBody = generateFormProgressData(
        currentForm,
        formValues,
        true,
      );
      updateSectionMutation(formDataBody);
    }
  };

  return (
    <Stack
      sx={{
        width: 1,
        height: '100vh',
      }}
    >
      <TaskFocusHeader
        title={serviceItem?.name || ''}
        onClose={handleCloseFormModal}
        loading={isLoading}
        slotProps={{
          root: {
            sx: {
              flexShrink: 0,
            },
          },
        }}
      />
      <Stack
        sx={{
          flex: 1,
          overflow: 'auto',
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
        }}
      >
        <Container
          maxWidth="md"
          sx={{
            pb: 4,
            pt: 3,
          }}
        >
          {isLoading && <FormCompletionSkeleton />}
          {!isLoading && (
            <Stack sx={{ gap: 3 }}>
              {showDescription && (
                <>
                  <CoverPicture
                    serviceItem={serviceItem}
                    sx={{ borderRadius: ({ shape }) => shape.borderRadiusL }}
                  />
                  <Description serviceItem={serviceItem} />
                </>
              )}
              <Typography
                variant="globalXS"
                color={({ palette }) => palette.new.text.neutral.lighter}
              >
                {t('required_field_disclaimer')}
              </Typography>
              {errorMessage && (
                <Alert
                  title={errorMessage}
                  severity="error"
                  hasClose={false}
                />
              )}
              <Stack sx={{ gap: 0.4 }}>
                <Typography
                  variant="globalL"
                  fontWeight="fontWeightSemiBold"
                >
                  {currentForm?.title}
                </Typography>
                {currentForm?.description && (
                  <TypographyLinkSensitive variant="globalS">
                    {currentForm?.description}
                  </TypographyLinkSensitive>
                )}
              </Stack>
              {currentForm?.components.map(component => (
                <Stack
                  key={component.nameId}
                  id={`form-field-${component.nameId}`}
                >
                  <CardContainer fullWidth>
                    <Stack sx={{ gap: 1 }}>
                      <ComponentTitle
                        name={component.nameId}
                        title={component.content.title}
                        required={component.content.required}
                        type={component.type as InputType}
                      />
                      <FormInputComponent
                        inputType={component.type as InputType}
                        name={component.nameId}
                        attachments={component.attachments}
                        validations={component.validations}
                        answer={component.answer ?? null}
                        {...component.content}
                      />
                    </Stack>
                  </CardContainer>
                </Stack>
              ))}
            </Stack>
          )}
        </Container>
      </Stack>
      {!isLoading && (
        <Footer
          onNextSection={handleNextSection}
          onGoBackSection={handleGoBackSection}
          isBackSectionDisabled={showDescription || isUploadingFiles}
          isNextSectionDisabled={isUploadingFiles}
          isLoading={isLoadingSection || createFormMutation.isLoading}
        />
      )}
    </Stack>
  );
};

export default RegularFormCompletion;
