'use client';

import React from 'react';
import { Grid } from '@mui/material';
import { FormFieldType, ModeType } from '@/shared/types/common';
import { interlocuteursFormFields } from '../../utils/form-fields-representative';
import FormField from '@/shared/components/form/form-field';
import ActionButtons from '@/shared/components/form/buttons-action';
import { centerFlexColumn } from '@/shared/theme/css';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { Interlocutor, IPassengerList } from '@/shared/types/passenger';
import { getIn, useFormikContext } from 'formik';

interface AutresInterlocuteursFormProps {
  mode: ModeType;
  onEdit: () => void;
  onSave: () => void;
  onCancel: () => void;
  loading?: boolean;
}

type InterlocutorFieldName = `interlocutor.${keyof Interlocutor}`;

export default function AutresInterlocuteursForm({ 
  mode, 
  onEdit, 
  onSave,
  onCancel,
  loading,
}: AutresInterlocuteursFormProps) {
  const formik = useFormikContext<IPassengerList>();
  const isReadOnly = mode === 'view';
  const renderField = (field: FormFieldType<Interlocutor>) => {
    const fieldName = `interlocutor.${field.name}` as InterlocutorFieldName;
    const touched = getIn(formik.touched, fieldName);
    const value = getIn(formik.values, fieldName) || '';
    const error = getIn(formik.errors, fieldName) || '';
  
    return (
      <FormField
        field={field}
        value={value}
        onChange={(name, value) => formik?.setFieldValue(`interlocutor.${name}`, value)}
        error={touched ? (error as string | undefined) : undefined}
        isReadOnly={isReadOnly}
        onBlur={() => formik?.setFieldTouched(fieldName, true)}
      />
    );
  };

  return (
    <>
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={onEdit}
          tooltipTitle="l'interlocuteur"
        />
      </ConditionalComponent>
      <Grid container spacing={4} sx={{ pt: 2 }}>
        {interlocuteursFormFields.map((field) => (
          <Grid item sx={centerFlexColumn} xs={12} sm={4} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
      </Grid>
      <ConditionalComponent isValid={!isReadOnly}>
        <Grid item xs={12} sx={{ mt: 2, pt: 'calc(100vh - 803px)' }}>
          <ActionButtons onSave={onSave} onCancel={onCancel} mode={mode} loading={loading}/>
        </Grid>
      </ConditionalComponent>
    </>
  );
}
