"use client"

import { Box, FormHelperText, Grid, 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 { ServiceProviderFormFields } from "../utils/form-fields-service-provider"
import { serviceProviderSchema } from "../utils/service-provider-schema"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useCallback, useEffect, useRef, useState } from "react"
import { Intervention, mapServiceProviderToRequest, ServiceProvider, ServiceProviderRequest } from "@/shared/types/fleet-management/service-provider"
import { useSnackbar } from "notistack"
import { useServiceProviderStore } from "@/shared/api/stores/fleet-service/service-provider-store"
import { useInterventionStore } from "@/shared/api/stores/fleet-service/intervention-store"

interface ServiceProviderFormProps {
  serviceProvider: ServiceProvider
  mode: ModeType
  onSave: (ServiceProviderRequest: ServiceProviderRequest) => void
  onEdit: (ServiceProviderRequest: ServiceProviderRequest) => void
  onClose: (isSaved: boolean) => void
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: ServiceProviderRequest) => void
  tabId?: string
}

export default function ServiceProviderForm({ serviceProvider, mode, onSave, onClose, onEdit, setHasUnsavedChanges, updateTabContent, tabId }: ServiceProviderFormProps) {
  const isReadOnly = mode === "view"

  const { enqueueSnackbar } = useSnackbar();

  const [formData, setFormData] = useState({} as ServiceProviderRequest)

  const [interventionsOptions, setInterventionsOptions] = useState<{ value: string; label: string }[]>([]);

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

  const {
    allInterventions,
    fetchAllInterventions
  } = useInterventionStore();

  const {
    existsByNameLoading,
    getServiceProviderById,
    createServiceProvider,
    updateServiceProvider,
    existsByName,
  } = useServiceProviderStore();

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

  const formik = useFormik<ServiceProviderRequest>({
    initialValues: formData,
    validationSchema: serviceProviderSchema,
    enableReinitialize: true,
    onSubmit: handleFormSubmit
  })

  const getInitialValues = async () => {
    const allInterventions: Intervention[] = await fetchAllInterventions();
    if (allInterventions.length > 0) {
      setInterventionsOptions(allInterventions.map((intervention: Intervention) => ({
        value: String(intervention.id),
        label: intervention.name
      })));
    }
    if (serviceProvider.id && mode !== 'add') {
      const serviceProviderData = await getServiceProviderById(serviceProvider.id);
      if (serviceProviderData) {
        setFormData(mapServiceProviderToRequest(serviceProviderData));
      }
    }
  }

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

  useEffect(() => {
    if (formik.values.interventionId) {
      const intervention = allInterventions.find(
        (i) => String(i.id) === String(formik.values.interventionId)
      );
      if (intervention && formik.values.interventionType !== intervention.interventionType) {
        formik.setFieldValue('interventionType', String(intervention.interventionType));
      }
    }
  }, [formik.values.interventionId, allInterventions, formik]);

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

  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 verifyName = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsByName(trimmedCode, Number(serviceProvider.id))
            : await existsByName(trimmedCode);

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

      verifyName();
    }, 500);
  }, [mode, serviceProvider.id, existsByName]);

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

  const renderField = (field: FormFieldType<ServiceProviderRequest>) => {
    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 ServiceProviderRequest]}
          onChange={handleChange}
          error={
            Boolean(formik.touched[field.name as keyof ServiceProviderRequest]) &&
              formik.errors[field.name as keyof ServiceProviderRequest]
              ? String(formik.errors[field.name as keyof ServiceProviderRequest])
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={field.name === 'interventionType' ? true : isReadOnly}
        />
        <ConditionalComponent isValid={field.name === 'name'}>
          <FormHelperText
            sx={{
              color: existsByNameLoading ? 'text.secondary' : (nameAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsByNameLoading}>
              <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={!existsByNameLoading}>
              {nameAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>
      </>
    )
  }

  return (
    <FormContainer titre="Fiche Fournisseur">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          tooltipTitle="le fournisseur"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={5}>
          {ServiceProviderFormFields(interventionsOptions).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 ServiceProviderRequest] = true;
                          return acc;
                        }, {} as FormikTouched<ServiceProviderRequest>)
                      );
                    }
                  });
                }}
                onCancel={() => {
                  onClose(false);
                }}
                mode={mode}
              />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  )
} 