import React, { useEffect, useState } from 'react';
import {
  Card,
  Grid,
  Button,
  Stack,
  Typography,
  Box,
  IconButton,
  DialogContent
} from '@mui/material';
import { FieldType, FormulaireChamp, IFormulaire } from '@/shared/types/formulaire';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPen, faEye, faEdit, faPenToSquare, faTimes } 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 { iconButtonStyles } from "@/shared/theme/css";
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom";
import FontAwesome from "@/shared/components/fontawesome";
import FormContainer from '@/layouts/form/form-container';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import FormulairePreviewDialog from './FormulairePreviewDialog';
import { StyledDialog, StyledDialogTitleGrey } from '../../styles';
import { ModeType } from '@/shared/types/common';
import { useFormik } from 'formik';
import { formulaireSchema } from '../utils/formulaire-schema';
import { useUpdateForm } from '@/shared/api/stores/hr-service/forms-recruitment';
import { useSnackbar } from 'notistack';

export const ExistingFormulaireForm = ({
  formulaire,
  mode,
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId
}: {
  formulaire: IFormulaire;
  mode: ModeType;
  onSave: (form: IFormulaire) => void;
  onClose: (forceClose: boolean) => void;
  onEdit: (form: IFormulaire) => void;
  updateTabContent: (tabId: string, newContent: IFormulaire) => void
  tabId: string
}) => {
  const { enqueueSnackbar } = useSnackbar();
  const { updateForm } = useUpdateForm();
  const [formBuilderOpen, setFormBuilderOpen] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  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);
            if (!values.id) {
                throw new Error('Form ID is required for update');
            }
            const preparedValues = prepareFormDataForSubmission(values);

            const response = await updateForm(values.id, {
              ...preparedValues,
              lastModifiedDate: new Date().toISOString()
            });    

            enqueueSnackbar('Formulaire mis à jour 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 mise à jour du formulaire: ' + 
                (error instanceof Error ? error.message : 'Erreur inconnue'), 
                {
                    variant: 'error',
                    autoHideDuration: 5000,
                }
            );
        } finally {
            setIsSubmitting(false);
        }
    },
    enableReinitialize: true
  });

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])
  return (
    <>
      <FormContainer titre={`Formulaire: ${formik.values.title}`}>
        <ConditionalComponent isValid={mode === 'view'}>
          <Stack direction="row" justifyContent="flex-end" gap="8px" pb={1}>
            <CustomTooltip title="Prévisualiser" arrow>
              <IconButton color="info" onClick={() => setPreviewOpen(true)} sx={iconButtonStyles}>
                <FontAwesome icon={faEye} width={16} />
              </IconButton>
            </CustomTooltip>
            <CustomTooltip title="Modifier Formulaire" arrow>
              <IconButton onClick={() => onEdit(formik.values)} sx={iconButtonStyles}>
                <FontAwesome icon={faPenToSquare} width={16} />
              </IconButton>
            </CustomTooltip>
          </Stack>
        </ConditionalComponent>

        <form onSubmit={(e) => {
            formik.handleSubmit(e);
        }}>
          <Grid container spacing={3}>
            {formulaireFormFields.map((field) => (
              <Grid item xs={12} md={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={mode === 'view'}
                />
              </Grid>
            ))}

            <Grid item xs={12}>
              <Stack direction="row" spacing={2} justifyContent="space-between" sx={{ mt: 2, mb: 1 }}>
                <Typography variant="h6" color="primary.main">Champs du formulaire</Typography>
                <Button
                  variant="outlined"
                  color="primary"
                  endIcon={<FontAwesomeIcon icon={faEdit} />}
                  onClick={() => setFormBuilderOpen(true)}
                  disabled={mode === 'view'}
                >
                  Modifier les champs
                </Button>
              </Stack>

              <Box sx={{ mt: 2 }}>
                <ConditionalComponent
                  isValid={formik.values.fields?.length > 0}
                  defaultComponent={
                    <Typography variant="body2" color="text.secondary">
                      Aucun champ défini
                    </Typography>
                  }
                >
                  <Grid container spacing={2}>
                    {formik.values.fields.map((champ) => (
                      <Grid item xs={12} md={6} key={champ.id}>
                        <Card variant="outlined" sx={{ p: 2 }}>
                          <Typography variant="subtitle1">{champ.label}</Typography>
                          <Typography variant="body2">Type: {champ.type}</Typography>
                          <Typography variant="body2">
                            Obligatoire: {champ.required ? 'Oui' : 'Non'}
                          </Typography>
                        </Card>
                      </Grid>
                    ))}
                  </Grid>
                </ConditionalComponent>
              </Box>
            </Grid>
          </Grid>
          <ConditionalComponent
            isValid={mode !== 'view'}>
            <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ mt: 3 }}>
              <Button 
                variant="outlined" 
                onClick={() => onClose(false)}
                >
                Annuler
              </Button>
              <Button 
                variant="contained" 
                type="submit" 
                color="primary"
                disabled={isSubmitting}
              >
              {isSubmitting ? 'Enregistrement...' : 'Enregistrer'}
              </Button>
            </Stack>
          </ConditionalComponent>
        </form>
      </FormContainer>

      <FormulairePreviewDialog
        open={previewOpen}
        onClose={() => setPreviewOpen(false)}
        formData={formik.values}
      />

      <StyledDialog open={formBuilderOpen} onClose={() => setFormBuilderOpen(false)} maxWidth="xl" fullWidth>
        <StyledDialogTitleGrey>
          <Box display="flex" alignItems="center">
            <FontAwesomeIcon icon={faEdit} style={{ marginRight: '10px' }} />
            <Typography variant="h6">Éditeur de formulaire</Typography>
          </Box>
          <CustomTooltip arrow title="Fermer">
            <IconButton onClick={() => setFormBuilderOpen(false)} edge="end">
              <FontAwesome icon={faTimes} width={16} />
            </IconButton>
          </CustomTooltip>
        </StyledDialogTitleGrey>

        <DialogContent sx={{ p: 0, flex: 1 }}>
          <FormBuilder
            formulaire={formik.values}
            onChange={(values) => {
              Object.entries(values).forEach(([key, value]) => {
                formik.setFieldValue(key, value);
              });
            }}
            onSave={() => {
              formik.handleSubmit();
              setFormBuilderOpen(false);
            }}
            readOnly={false}
          />
        </DialogContent>
      </StyledDialog>
    </>
  );
};