'use client';

import React from 'react';
import {
  Grid,
  Typography,
} from '@mui/material';
import { FormFieldType, TableType } from '@/shared/types/common';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import { VehicleRequest } from '@/shared/types/fleet-management/vehicle';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { pxToRem } from '@/shared/theme/typography';
import { _documents } from '@/shared/_mock/_documents';
import { FormikTouched } from 'formik';

export default function VehicleTab({
  renderField,
  baseFields,
  locationFields,
  isReadOnly,
  formik,
  onEdit,
  onClose,
  tableHead,
  mode,
}: any) {
  return (
    <>
      <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}>
          {baseFields.map((field: FormFieldType<VehicleRequest>) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>
        <Typography sx={{
          my: 3, fontSize: pxToRem(25),
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}>
          Informations de location
        </Typography>
        <Grid container spacing={5}>
          {locationFields.map((field: FormFieldType<VehicleRequest>) => (
            <Grid item xs={12} sm={4} key={field.name}>
              {renderField(field)}
            </Grid>
          ))}
        </Grid>
        <ConditionalComponent isValid={!isReadOnly}>
          <Grid item xs={12} sx={{ mt: 4 }}>
            <ActionButtons
              onSave={() => {
                formik.validateForm().then((errors: any) => {
                  const hasErrors = Object.keys(errors).length > 0;
                  if (!hasErrors) {
                    formik.submitForm();
                  } else {
                    formik.setTouched(
                      Object.keys(errors).reduce((acc, key) => {
                        acc[key as keyof VehicleRequest] = true;
                        return acc;
                      }, {} as FormikTouched<VehicleRequest>)
                    );
                  }
                });
              }}
              onCancel={() => {
                onClose(false);
              }}
              mode={mode}
            />
          </Grid>
        </ConditionalComponent>
      </form>
    </>
  );
}