'use client';

import { useState, useEffect } from 'react';
import { Grid } from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import {
  TableType,
  type FormFieldType,
  type ModeType,
  type TableColumn,
} from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { preparationDriverFormFields } from '../utils/form-fields-driver';
import type { IPreparationDriver } from '@/shared/types/driver';
import { useFormik } from 'formik';
import { preparationDriverSchema } from '../utils/preparation-driver-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface PreparationDriverFormProps {
  preparationDriver: IPreparationDriver;
  mode: ModeType;
  onSave: (updated: IPreparationDriver) => void;
  onEdit: (updated: IPreparationDriver) => void;
  onClose: (forceClose: boolean) => void;
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, newContent: IPreparationDriver) => void
  tabId?: string
}

export default function PreparationDriverForm({
  preparationDriver,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  updateTabContent,
  tabId,
  }: PreparationDriverFormProps) {
  const [formData, setFormData] = useState<IPreparationDriver>(preparationDriver);
  const isReadOnly = mode === 'view';

  const formik = useFormik<IPreparationDriver>({
    initialValues: preparationDriver,
    validationSchema: preparationDriverSchema,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
  });

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

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


  return (
    <FormContainer titre="Fiche Chauffeurs">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formData)}
          onExport={() => void 0}
          tooltipTitle={TableType.Driver}
          dataRow={preparationDriver}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {preparationDriverFormFields.map((field) => (
            <Grid item xs={12} sm={4} 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>
  );
}
