import React, { useEffect } from 'react';
import { Grid } from '@mui/material';
import { useFormik } from 'formik';
import FormField from '@/shared/components/form/form-field';
import type { FormFieldType, ModeType } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import ActionButtons from '@/shared/components/form/buttons-action';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { AssignmentHistory } from '@/shared/types/flottes/vehicle-affectation';
import { vehiculeFields } from '../../utils/form-fields-affectation';
import { attributionSchema } from '../../utils/affectation-schema';

interface AssignmentHistoryFormProps {
  assignment: AssignmentHistory;
  mode: ModeType;
  onSave: (updated: AssignmentHistory) => void;
  onEdit: (updated: AssignmentHistory) => void;
  onClose: () => void;
  setHasUnsavedChanges?: (value: boolean) => void;
  updateTabContent?: (tabId: string, newContent: AssignmentHistory) => void;
  tabId?: string;
}

export default function AssignmentHistoryForm({ assignment, mode, onSave, onClose, onEdit, setHasUnsavedChanges, updateTabContent, tabId }: AssignmentHistoryFormProps) {
  const isReadOnly = mode === 'view';

  const formik = useFormik<AssignmentHistory>({
    initialValues: assignment,
    validationSchema: attributionSchema,
    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<AssignmentHistory>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof AssignmentHistory]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        Boolean(formik.touched[field.name as keyof AssignmentHistory]) &&
        formik.errors[field.name as keyof AssignmentHistory]
          ? String(formik.errors[field.name as keyof AssignmentHistory])
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  );

  return (
    <FormContainer titre="Historique d'affectation" hasBorder isSousElemnt>
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={3}>
          {vehiculeFields.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} mode={mode} />
            </Grid>
          </ConditionalComponent>
        </Grid>
      </form>
    </FormContainer>
  );
}