"use client"

import { Box, FormHelperText, Grid, Typography } from "@mui/material"
import { 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 { vehicleTypeFormFields } from "../utils/form-fields-vehicle-type"
import { vehicleTypeSchema } from "../utils/vehicle-type-schema"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useCallback, useEffect, useRef, useState } from "react"
import { VehicleType } from "@/shared/types/fleet-management/vehicleType"
import { useSnackbar } from "notistack"
import { useVehicleTypeStore } from "@/shared/api/stores/fleet-service/vehicle-type-store"

interface VehicleTypeFormProps {
  vehicleType: VehicleType
  mode: ModeType
  onSave: (updatedVehicleType: VehicleType) => void
  onEdit: (updatedVehicleType: VehicleType) => void
  onClose: (isSaved: boolean) => void
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: VehicleType) => void
  tabId?: string
}

export default function VehicleTypeForm({ vehicleType, mode, onSave, onClose, onEdit, setHasUnsavedChanges, updateTabContent, tabId }: VehicleTypeFormProps) {
  const isReadOnly = mode === "view"

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    createVehicleType,
    updateVehicleType,
    existsByNameLoading,
    existsByName
  } = useVehicleTypeStore();

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

  const formik = useFormik<VehicleType>({
    initialValues: vehicleType,
    validationSchema: vehicleTypeSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose(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 existsByName(trimmedCode, Number(vehicleType.id))
            : await existsByName(trimmedCode);

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

      verifyCode();
    }, 500);
  }, [mode, vehicleType.id, existsByName]);

  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<VehicleType>) => {
    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 VehicleType]}
          onChange={handleChange}
          error={
            Boolean(formik.touched[field.name as keyof VehicleType]) &&
              formik.errors[field.name as keyof VehicleType]
              ? String(formik.errors[field.name as keyof VehicleType])
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={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="Type de véhicule" hasBorder isSousElemnt>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(vehicleType)}
          tooltipTitle="le type de véhicule"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={5}>
          {vehicleTypeFormFields.map((field) => (
            <Grid item xs={12} sm={6} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons onSave={formik.submitForm} onCancel={() => onClose(false)} mode={mode} />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  )
}