'use client';

import React, { useEffect } from 'react';
import {
  Grid,
  Box,
  Typography,
} from '@mui/material';
import { useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType, ModeType, TableColumn, TableType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import { ISupplierType, IVehicle } from '@/shared/types/flottes/vehicule';
import { vehicleformFields } from '../utils/form-fields-vehicle';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import FormContainer from '@/layouts/form/form-container';
import { vehicleSchema } from '../utils/vehicle-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { _supplierTypes } from '@/shared/_mock/flottes/_supplier';

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

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

  const formik = useFormik<IVehicle>({
    initialValues: vehicle,
    validationSchema: vehicleSchema,
    onSubmit: (values) => {
      onSave(values)
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose()
    },
  })

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

  const renderField = (field: FormFieldType<IVehicle>) => (
    <FormField
      field={field}
      value={field.name === 'providerType' ? (formik.values[field.name as keyof IVehicle] as ISupplierType)?.id : formik.values[field.name as keyof IVehicle]}
      onChange={(name, value) => name === 'providerType' ? formik.setFieldValue(name, _supplierTypes.find(p => p.id === value)) : formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof IVehicle]
          ? (formik.errors[field.name as keyof IVehicle] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={field.name === 'chauffeur' ? true : isReadOnly}
    />
  );
  
  return (
    <FormContainer titre="Fiche Véhicule">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          onExport={() => void 0}
          tooltipTitle={TableType.Vehicle}
          dataRow={formik.values}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={5}>
          {vehicleformFields.map((field) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
          <Grid item xs={12} sm={4} key={"document"}>
            <Box display="flex" alignItems="center" justifyContent="space-between" gap={4}>
              <Typography sx={{ color: isReadOnly ? "text.disabled" : "primary.main" }}>Carte grise</Typography>
              <AddButton
                variant="contained"
                sx={{ minHeight: "43px" }}
                endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                disabled={isReadOnly}
              >
                Importez un document
              </AddButton>
            </Box>
          </Grid>
          
          <ConditionalComponent isValid={!isReadOnly}>
            <Grid item xs={12}>
              <ActionButtons
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm()
                  })
                }}
                onCancel={onClose}
                mode={mode}
              />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  )
}

