import React, { useEffect, useState } from 'react';
import {
  Stepper,
  Step,
  StepLabel,
  Paper,
  Grid,
  Typography,
  Box,
  Button,
  Stack,
  Card,
} from '@mui/material';
import { FieldType, FormulaireChamp, IFormulaire } from '@/shared/types/formulaire';
import {
  faArrowRight,
  faArrowLeft,
} from '@fortawesome/free-solid-svg-icons';
import FormField from '@/shared/components/form/form-field';
import { formulaireFormFields } from '../utils/form-fields-formulaire';
import FormBuilder from './form-builder/form-builder';
import FontAwesome from '@/shared/components/fontawesome';
import FormContainer from '@/layouts/form/form-container';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useFormik } from 'formik';
import { formulaireSchema } from '../utils/formulaire-schema';
import { useAddForm } from '@/shared/api/stores/hr-service/forms-recruitment';
import { useSnackbar } from 'notistack';


export const NewFormulaireTab = ({
  formulaire,
  onSave,
  onClose,
  updateTabContent,
  tabId
}: {
  formulaire: IFormulaire;
  onSave: (form: IFormulaire) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, newContent: IFormulaire) => void
  tabId: string
}) => {
  const [formCreationStep, setFormCreationStep] = useState(0);
  const { enqueueSnackbar } = useSnackbar();
  const { addForm } = useAddForm();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const prepareFormDataForSubmission = (values: IFormulaire): IFormulaire => {
    const preparedValues = { ...values };
    const processFields = (fields: FormulaireChamp[]) => {
      return fields.map(field => {
        const processedField = { ...field };
        
        if (typeof field.id === 'string' && isNaN(Number(field.id))) {
          delete (processedField as { id?: number | string }).id;
        }

        if (field.type === FieldType.SECTION && field.childFields) {
          const childFieldIds = field.childFields;
          const allFields = values.fields;
          const childFields = childFieldIds
            .map(id => allFields.find(f => f.id === id))
            .filter(Boolean) as FormulaireChamp[];
            
          processedField.childFields = processFields(childFields)
            .map(f => f.id)
            .filter((id): id is string => id !== undefined && typeof id === 'string');
        }
        return processedField;
      });
    };
    preparedValues.fields = processFields(values.fields);
    return preparedValues;
  };

  const formik = useFormik<IFormulaire>({
    initialValues: formulaire,
    validationSchema: formulaireSchema,
    onSubmit: async (values) => {
      try {
        setIsSubmitting(true);
        const preparedValues = prepareFormDataForSubmission(values);
        
        const response = await addForm({
          ...preparedValues,
          lastModifiedDate: new Date().toISOString()
        });

        enqueueSnackbar('Formulaire créé avec succès', {
          variant: 'success',
          autoHideDuration: 3000,
        });

        onSave(values);
        onClose(true);
      } catch (error) {
        console.error('Error in form submission:', error);
        enqueueSnackbar(
          'Erreur lors de la création du formulaire: ' + 
          (error instanceof Error ? error.message : 'Erreur inconnue'), 
          {
            variant: 'error',
            autoHideDuration: 5000,
          }
        );
      } finally {
        setIsSubmitting(false);
      }
    },
    enableReinitialize: true
  });

  useEffect(() => {
    if (updateTabContent && tabId && formCreationStep === 0) {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, formCreationStep])

  const handleNextStep = () => {
    formik.validateForm().then((errors) => {
      if (Object.keys(errors).length === 0) {
        setFormCreationStep(1);
      }
    });
  };

  const handlePreviousStep = () => setFormCreationStep(0);

  const handleFormBuilderSave = () => {
    if (!isSubmitting) {
      formik.handleSubmit();
    }
  };

  const steps = ['Informations du formulaire', 'Concepteur de formulaire'];

  return (
    <FormContainer sx={{ height: 'calc(100vh - 100px)' }}>
      <Box sx={{ px: 3, py: 2, borderBottom: 1, borderColor: 'divider' }}>
        <Stepper activeStep={formCreationStep} sx={{ my: 1 }}>
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
            </Step>
          ))}
        </Stepper>
      </Box>

      <Box sx={{ flex: 1, overflow: 'auto', pb: 2 }}>
        <ConditionalComponent
          isValid={formCreationStep === 0}
          defaultComponent={
            <FormBuilder
              formulaire={formik.values}
              onChange={(values) => {
                Object.entries(values).forEach(([key, value]) => {
                  formik.setFieldValue(key, value);
                });
              }}
              onSave={handleFormBuilderSave}
              readOnly={false}
            />
          }
        >
          <Box sx={{ p: 1 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <Typography variant="h5" color={'primary.main'}>
                Informations du formulaire
              </Typography>
            </Box>
            <form onSubmit={formik.handleSubmit}>
              <Grid container spacing={3}>
                {formulaireFormFields
                  .filter((field) =>
                    ['title', 'category', 'department', 'creator', 'description'].includes(
                      String(field.name)
                    )
                  )
                  .sort((a, b) => (a.name === 'description' ? 1 : -1))
                  .map((field) => (
                    <Grid
                      item
                      xs={12}
                      md={field.name === 'description' ? 12 : 6}
                      key={String(field.name)}
                    >
                      <FormField
                        field={field as any}
                        value={formik.values[field.name as keyof IFormulaire]}
                        onChange={(name, value) => formik.setFieldValue(name, value)}
                        error={
                          formik.touched[field.name as keyof IFormulaire]
                            ? (formik.errors[field.name as keyof IFormulaire] as string | undefined)
                            : undefined
                        }
                        onBlur={formik.handleBlur}
                        isReadOnly={false}
                      />
                    </Grid>
                  ))}
              </Grid>
            </form>
          </Box>
        </ConditionalComponent>
      </Box>

      <Box sx={{ px: 2, bgcolor: 'background.paper' }}>
        <Stack direction="row" justifyContent="space-between">
          <Box>
            <ConditionalComponent
              isValid={formCreationStep === 1}>
              <Button
                onClick={handlePreviousStep}
                variant="outlined"
                startIcon={<FontAwesome icon={faArrowLeft} />}
                sx={{ mr: 1 }}
              >
                Retour
              </Button>
            </ConditionalComponent>
          </Box>
          <Box>
            <Button onClick={() => onClose(false)} variant="outlined" sx={{ mr: 1 }}>
              Annuler
            </Button>
            <ConditionalComponent
              isValid={formCreationStep === 0}
              defaultComponent={
                <Button 
                  onClick={handleFormBuilderSave} 
                  variant="contained" 
                  color="primary"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Enregistrement...' : 'Enregistrer'}
                </Button>
              }
            >
              <Button
                onClick={handleNextStep}
                variant="contained"
                color="primary"
                endIcon={<FontAwesome icon={faArrowRight} />}
                disabled={Object.keys(formik.errors).length > 0
                }
              >
                Suivant
              </Button>
            </ConditionalComponent>
          </Box>
        </Stack>
      </Box>
    </FormContainer>
  );
};
