'use client';

import React from 'react';
import { Box, Grid, Typography } from '@mui/material';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import FormField from '@/shared/components/form/form-field';
import { FormFieldType } from '@/shared/types/common';
import { IRoadMapMileage } from '@/shared/types/driver-roadmap';
import { roadMapFormFields } from '../../utils/form-field-roadmap';
import { pxToRem } from '@/shared/theme/typography';

const roadMapSchema = Yup.object({
  startMileage: Yup.number().required('Champ requis'),
  endMileage: Yup.number().required('Champ requis'),
  fuelAmount: Yup.number().nullable(),
});

const CreateRoadMapMileage: React.FC = () => {
  const formik = useFormik<IRoadMapMileage>({
    initialValues: {
      startMileage: undefined,
      endMileage: undefined,
      fuelAmount: undefined,
    },
    validationSchema: roadMapSchema,
    onSubmit: (values) => {
      console.log('Submitted', values);
    },
  });

  const renderField = (field: FormFieldType<IRoadMapMileage>) => (
    <FormField
      field={field}
      value={formik.values[field.name]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name] ? (formik.errors[field.name] as string | undefined) : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={false}
    />
  );

  return (
    <>
      <Typography
        variant="h5"
        sx={{
          color: 'primary.main',
          fontSize: pxToRem(22),

          fontWeight: (theme) => theme.typography.fontWeightBold,
          m: 3,
        }}
      >
        Intervalle Kilométrage
      </Typography>
      <Box sx={{ backgroundColor: 'white', borderRadius: 2, p: 3 }}>
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={3}>
            {roadMapFormFields.map((field) => (
              <Grid item xs={12} sm={6} key={field.name}>
                {renderField(field)}
              </Grid>
            ))}
          </Grid>
        </form>
      </Box>
    </>
  );
};

export default CreateRoadMapMileage;
