'use client';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common';
import { _VEHICLE_DOCUMENT_TYPES, vehicleformFields } from '../utils/form-fields-vehicle';
import FormContainer from '@/layouts/form/form-container';
import { vehicleSchema } from '../utils/vehicle-schema';
import TabbedForm from '@/shared/components/tabs/tabbed-form';
import DocumentForm from '@/shared/components/documents/documents-form';
import { _documents } from '@/shared/_mock/_documents';
import VehicleTab from '../components/vehicle-tab';
import { mapVehicleToRequest, VehicleListResponse, VehicleRequest } from '@/shared/types/fleet-management/vehicle';
import { useVehicleStore } from '@/shared/api/stores/fleet-service/vehicle-store';
import { useVehicleTypeStore } from '@/shared/api/stores/fleet-service/vehicle-type-store';
import { useVehicleBrandModelStore } from '@/shared/api/stores/fleet-service/vehicle-brand-model-store';
import { useSnackbar } from 'notistack';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import { useFuelTypeStore } from '@/shared/api/stores/fleet-service/fuel-type-store';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { Box, FormHelperText, Typography } from '@mui/material';

interface VehicleFormProps {
  vehicle: VehicleListResponse;
  mode: ModeType;
  onEdit: (updatedVehicle: VehicleRequest) => void;
  onClose: (isSaved: boolean) => void;
  tableHead: TableColumn[];
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: VehicleRequest) => void
  tabId?: string
}

export default function VehicleForm({
  vehicle,
  mode,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: VehicleFormProps) {
  const isReadOnly = mode === 'view';
  const isAddMode = mode === 'add';

  const { enqueueSnackbar } = useSnackbar();

  const [formData, setFormData] = useState<VehicleRequest>({} as VehicleRequest);

  const [vehicleTypeOptions, setVehicleTypeOptions] = useState<{ value: string; label: string }[]>([]);
  const [brandNameOptions, setBrandNameOptions] = useState<{ value: string; label: string }[]>([]);
  const [modelNameOptions, setModelNameOptions] = useState<{ value: string; label: string }[]>([]);
  const [driverOptions, setDriverOptions] = useState<{ value: string; label: string }[]>([]);
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [fuelTypeOptions, setFuelTypeOptions] = useState<{ value: string; label: string }[]>([]);
  const [sectorOptions, setSectorOptions] = useState<{ value: string; label: string }[]>([]);

  const [vehicleIdentificationNumberAvailability, setVehicleIdentificationNumberAvailability] = useState<{ message: string; isAvailable: boolean } | null>(null);
  const [registrationPlateAvailability, setRegistrationPlateAvailability] = useState<{ message: string; isAvailable: boolean } | null>(null);

  const {
    vehicleById,
    existsByRegistrationPlateLoading,
    existsByVehicleIdentificationNumberLoading,
    getVehicleById,
    createVehicle,
    updateVehicle,
    existsByRegistrationPlate,
    existsByVehicleIdentificationNumber,
  } = useVehicleStore();

  const {
    allVehicleTypes,
    fetchAllVehicleTypes,
  } = useVehicleTypeStore();

  const {
    brands,
    models,
    fetchBrands,
    fetchModelsByBrandName,
    getVehicleTypeByBrandModel
  } = useVehicleBrandModelStore();

  const {
    getAllDriverShort
  } = useDriverStore();

  const {
    departmentNames,
    fetchDepartmentNames,
    sectorNames,
    fetchSectorNames
  } = useInfrastructureStore()

  const {
    fetchAllFuelTypes
  } = useFuelTypeStore();

  const handleFormSubmit = async (values: VehicleRequest) => {
    if (vehicleIdentificationNumberAvailability != null && !vehicleIdentificationNumberAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer un numéro de chassis valide !', { variant: 'error' });
      return;
    }
    if (registrationPlateAvailability != null && !registrationPlateAvailability.isAvailable) {
      enqueueSnackbar('Veuillez entrer une immatriculation valide !', { variant: 'error' });
      return;
    }
    if (mode === 'edit') {
      try {
        await updateVehicle(vehicle.id, values);
        if (setHasUnsavedChanges) setHasUnsavedChanges(false);
        onClose(true);
        enqueueSnackbar('Véhicule modifié avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    } else if (mode === 'add' || mode === 'copy') {
      try {
        createVehicle(values);
        if (setHasUnsavedChanges) setHasUnsavedChanges(false);
        onClose(true);
        enqueueSnackbar('Véhicule créé avec succès', { variant: 'success' });
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
        return;
      }
    }
  };

  const getInitialValues = async () => {
    fetchBrands();
    fetchAllVehicleTypes();

    const allDriverShort = await getAllDriverShort();
    setDriverOptions(allDriverShort.map((d) => ({ value: d.id, label: (d.firstName + ' ' + d.lastName) })));

    fetchSectorNames();
    fetchDepartmentNames();

    const allFuelTypes = await fetchAllFuelTypes();
    setFuelTypeOptions((allFuelTypes.map((ft) => ({ value: ft.id, label: ft.name }))));

    if (vehicle?.id && mode !== 'add')
      getVehicleById(vehicle?.id);
  }

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

  useEffect(() => {
    if (vehicleById) {
      console.log('Vehicle by ID:', vehicleById);
      setFormData(mapVehicleToRequest(vehicleById));
    }
  }, [vehicleById])

  const formik = useFormik<VehicleRequest>({
    initialValues: formData,
    validationSchema: vehicleSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose(true)
    },
    enableReinitialize: true
  })

  useEffect(() => {
    setBrandNameOptions(brands.map((b) => ({ value: b, label: b })));
  }, [brands])

  useEffect(() => {
    setVehicleTypeOptions(allVehicleTypes.map((v) => ({ value: v.id, label: v.name })));
  }, [allVehicleTypes])

  useEffect(() => {
    setDepartmentOptions(departmentNames.map((d) => ({ value: d.id.toString(), label: d.name })));
  }, [departmentNames])

  useEffect(() => {
    setSectorOptions(sectorNames.map((d) => ({ value: d.id.toString(), label: d.name })));
  }, [sectorNames])

  useEffect(() => {
    if (formik.values.brandName)
      fetchModelsByBrandName(formik.values.brandName)
  }, [formik.values.brandName])

  useEffect(() => {
    setModelNameOptions(models.map((m) => ({ value: m, label: m })));
  }, [models])

  useEffect(() => {
    const fetchVehicleType = async () => {
      if (formik.values.brandName && formik.values.modelName) {
        const vehicleType = await getVehicleTypeByBrandModel(formik.values.brandName, formik.values.modelName);
        if (vehicleType?.id) {
          formik.setFieldValue('vehicleTypeId', vehicleType.id);
        }
      }
    };

    fetchVehicleType();
  }, [formik.values.brandName, formik.values.modelName]);

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

  const vehicleIdentificationNumberTimeoutRef = useRef<NodeJS.Timeout>();
  const registrationPlateTimeoutRef = useRef<NodeJS.Timeout>();

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

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

    const trimmedVehicleIdentificationNumber = code.trim();
    if (trimmedVehicleIdentificationNumber === '') {
      setVehicleIdentificationNumberAvailability(null);
      return;
    }

    vehicleIdentificationNumberTimeoutRef.current = setTimeout(() => {
      const verifyVehicleIdentificationNumber = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsByVehicleIdentificationNumber(trimmedVehicleIdentificationNumber, Number(vehicle.id))
            : await existsByVehicleIdentificationNumber(trimmedVehicleIdentificationNumber);

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

      verifyVehicleIdentificationNumber();
    }, 500);
  }, [mode, vehicle.id, existsByVehicleIdentificationNumber]);

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

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

    const trimmedRegistrationPlate = code.trim();
    if (trimmedRegistrationPlate === '') {
      setRegistrationPlateAvailability(null);
      return;
    }

    registrationPlateTimeoutRef.current = setTimeout(() => {
      const verifyRegistrationPlate = async () => {
        try {
          const exists = mode === 'edit'
            ? await existsByRegistrationPlate(trimmedRegistrationPlate, Number(vehicle.id))
            : await existsByRegistrationPlate(trimmedRegistrationPlate);

          setRegistrationPlateAvailability({
            message: exists ? "L'immatriculation existe déjà" : "L'immatriculation est disponible",
            isAvailable: !exists
          });
        } catch (error) {
          setRegistrationPlateAvailability(null);
        }
      };

      verifyRegistrationPlate();
    }, 500);
  }, [mode, vehicle.id, existsByRegistrationPlate]);


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

  const renderField = (field: FormFieldType<VehicleRequest>) => {
    const handleChange = (name: string, value: any) => {
      formik.setFieldValue(name, value);

      if (name === 'vehicleIdentificationNumber') {
        checkVehicleIdentificationNumber(value);
      }

      if (name === 'registrationPlate') {
        checkRegistrationPlate(value);
      }
    };

    return (
      <>
        <FormField
          field={field}
          value={
            field.name === 'departmentId' ? String(formik.values[field.name as keyof VehicleRequest]) :
              field.name === 'sectorId' ? String(formik.values[field.name as keyof VehicleRequest]) :
                field.name === 'driverId' ? String(formik.values[field.name as keyof VehicleRequest]) :
                  formik.values[field.name as keyof VehicleRequest]}
          onChange={handleChange}
          error={
            formik.touched[field.name as keyof VehicleRequest]
              ? (formik.errors[field.name as keyof VehicleRequest] as string | undefined)
              : undefined
          }
          onBlur={formik.handleBlur}
          isReadOnly={isReadOnly || field.name === 'vehicleTypeId'}
        />
        <ConditionalComponent isValid={field.name === 'vehicleIdentificationNumber'}>
          <FormHelperText
            sx={{
              color: existsByVehicleIdentificationNumberLoading ? 'text.secondary' : (vehicleIdentificationNumberAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsByVehicleIdentificationNumberLoading}>
              <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={!existsByVehicleIdentificationNumberLoading}>
              {vehicleIdentificationNumberAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>
        <ConditionalComponent isValid={field.name === 'registrationPlate'}>
          <FormHelperText
            sx={{
              color: existsByRegistrationPlateLoading ? 'text.secondary' : (registrationPlateAvailability?.isAvailable ? 'success.main' : 'error.main'),
              marginTop: '4px',
              display: 'flex',
              alignItems: 'center'
            }}
          >
            <ConditionalComponent isValid={existsByRegistrationPlateLoading}>
              <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={!existsByRegistrationPlateLoading}>
              {registrationPlateAvailability?.message}
            </ConditionalComponent>
          </FormHelperText>
        </ConditionalComponent>
      </>
    );
  }

  const baseFields = vehicleformFields(
    vehicleTypeOptions,
    brandNameOptions,
    modelNameOptions,
    driverOptions,
    departmentOptions,
    fuelTypeOptions,
    sectorOptions
  ).slice(0, 13);

  const locationFields = vehicleformFields(
    vehicleTypeOptions,
    brandNameOptions,
    modelNameOptions,
    driverOptions,
    departmentOptions,
    fuelTypeOptions,
    sectorOptions
  ).slice(13);

  const tabs = [
    {
      label: 'Détails véhicule',
      content: (
        <VehicleTab
          renderField={renderField}
          baseFields={baseFields}
          locationFields={locationFields}
          isReadOnly={isReadOnly}
          formik={formik}
          onEdit={onEdit}
          onSave={() => {
            formik.validateForm().then(() => {
              formik.submitForm();
            });
          }}
          onClose={onClose}
          tableHead={tableHead}
          mode={mode}
          setHasUnsavedChanges={setHasUnsavedChanges}
        />
      ),
    },
    {
      label: 'Documents',
      content: <DocumentForm documents={isAddMode ? [] : _documents} documentTypes={_VEHICLE_DOCUMENT_TYPES} />,
      disabled: isAddMode
    },
  ];

  return (
    <FormContainer titre="Fiche Véhicule">
      <TabbedForm tabs={tabs} />
    </FormContainer>
  );
}