'use client';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Grid, Box, FormHelperText, Typography } from '@mui/material';
import { FormikTouched, useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import type { FormFieldType, ModeType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import FormContainer from '@/layouts/form/form-container';
import { FuelType } from '@/shared/types/fleet-management/fuelType';
import { fuelTypeSchema } from '../utils/fuel-type-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { fuelTypeFormFields } from '../utils/form-fields-fuel-type';
import { useFuelTypeStore } from '@/shared/api/stores/fleet-service/fuel-type-store';
import { useSnackbar } from 'notistack';

interface FuelTypeFormProps {
  fuelType: FuelType;
  mode: ModeType;
  onEdit: (updatedFuelType: FuelType) => void;
  onClose: (isSaved: boolean) => void;
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: FuelType) => void
  tabId?: string
}

export default function FuelTypeForm({
  fuelType,
  mode,
  onClose,
  onEdit,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: FuelTypeFormProps) {

  const { enqueueSnackbar } = useSnackbar();

  const isReadOnly = mode === 'view';

  const [fuelTypeFormData, setFuelTypeFormData] = useState<FuelType>({} as FuelType)

  const [nameAvailability, setNameAvailability] = useState<{ message: string; isAvailable: boolean } | null>(null);

  const {
    fuelTypeById,
    existsFuelTypeByNameLoading,
    getFuelTypeById,
    createFuelType,
    updateFuelType,
    existsFuelTypeByName
  } = useFuelTypeStore();

  const handleFormSubmit = async (values: FuelType) => {
    if (nameAvailability != null && !nameAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer un nom valide !', { variant: 'error' });
      return;
    }
    if (mode === 'edit') {
      try {
        await updateFuelType(fuelType.id, values);
        onClose(true);
        enqueueSnackbar('Type de carburant modifié avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'add' || mode === 'copy') {
      try {
        await createFuelType(values);
        onClose(true);
        enqueueSnackbar('Type de carburant créé avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

  const getInitialValues = async () => {
    if (fuelType.id && mode !== 'add') {
      getFuelTypeById(fuelType.id);
    }
  }

  useEffect(() => {
    getInitialValues();
  }, [])

  useEffect(() => {
    if (fuelTypeById)
      setFuelTypeFormData(fuelTypeById)
  }, [fuelTypeById])

  const formik = useFormik<FuelType>({
    initialValues: fuelTypeFormData,
    validationSchema: fuelTypeSchema,
    onSubmit: handleFormSubmit,
    enableReinitialize: true
  });

  const nameTimeoutRef = useRef<NodeJS.Timeout>();

  const checkName = useCallback((code: string) => {
    if (nameTimeoutRef.current) {
      clearTimeout(nameTimeoutRef.current);
    }

    if (!code) {
      setNameAvailability(null);
      return;
    }

    const trimmedCode = code.trim();
    if (trimmedCode === '') {
      setNameAvailability(null);
      return;
    }

    nameTimeoutRef.current = setTimeout(() => {
      const verifyCode = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsFuelTypeByName(trimmedCode, Number(fuelType.id))
            : await existsFuelTypeByName(trimmedCode);

          setNameAvailability({
            message: exists ? 'Le nom existe déjà' : 'Le nom est disponible',
            isAvailable: !exists
          });
        } catch (error) {
          setNameAvailability(null);
        }
      };

      verifyCode();
    }, 500);
  }, [mode, fuelType.id, existsFuelTypeByName]);

  useEffect(() => {
    return () => {
      if (nameTimeoutRef.current) {
        clearTimeout(nameTimeoutRef.current);
      }
    };
  }, []);

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<FuelType>) => {
    const handleChange = (name: string, value: any) => {
      formik.setFieldValue(name, value);
      if (name === 'name') {
        checkName(value);
      }
    };
    return (
      <>
        <FormField
          field={field}
          value={formik.values[field.name as keyof FuelType]}
          onChange={handleChange}
          error={
            formik.touched[field.name as keyof FuelType]
              ? (formik.errors[field.name as keyof FuelType] as string | undefined)
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={isReadOnly}
        />
        <ConditionalComponent isValid={field.name === 'name'}>
          <FormHelperText
            sx={{
              color: existsFuelTypeByNameLoading ? 'text.secondary' : (nameAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsFuelTypeByNameLoading}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Box
                  sx={{
                    width: '16px',
                    height: '16px',
                    border: '2px solid #f3f3f3',
                    borderTop: '2px solid #746CD4',
                    borderRadius: '50%',
                    animation: 'spin 1s linear infinite',
                    marginRight: '8px',
                    '@keyframes spin': {
                      '0%': { transform: 'rotate(0deg)' },
                      '100%': { transform: 'rotate(360deg)' }
                    }
                  }}
                />
                <Typography sx={{ color: '#746CD4' }}>
                  Vérification en cours...
                </Typography>
              </Box>
            </ConditionalComponent>
            <ConditionalComponent isValid={!existsFuelTypeByNameLoading}>
              {nameAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>
      </>
    )
  }

  return (
    <FormContainer titre="Pétrolier">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          tooltipTitle="le pétrolier"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {fuelTypeFormFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    const hasErrors = Object.keys(errors).length > 0;
                    if (!hasErrors) {
                      formik.submitForm();
                    } else {
                      formik.setTouched(
                        Object.keys(errors).reduce((acc, key) => {
                          acc[key as keyof FuelType] = true;
                          return acc;
                        }, {} as FormikTouched<FuelType>)
                      );
                    }
                  });
                }}
                onCancel={() => {
                  onClose(false);
                }}
                mode={mode}
              />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  );
}