'use client';

import React, { useEffect } from 'react';
import { Grid } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import { IAppointment } from '@/shared/types/appointment';
import { formFields } from '../utils/form-fields-appointment';
import FormField from '@/shared/components/form/form-field';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import ActionButtons from '@/shared/components/form/buttons-action';
import FormContainer from '@/layouts/form/form-container';
import { useFormik } from 'formik';
import { appointmentSchema } from '../utils/appiontement-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface AppointmentFormProps {
  appointment: IAppointment;
  mode?: 'add' | 'edit' | 'view' | 'copy';
  onSave: (updatedAppointment: IAppointment) => void;
  onEdit: (appointment: IAppointment) => void;
  onClose: (forceClose: boolean) => void;
  updateTabContent: (tabId: string, newContent: IAppointment) => void;
  tabId: string;
}

export default function AppointmentForm({
  appointment,
  mode = 'add',
  onSave,
  onClose,
  onEdit,
  updateTabContent,
  tabId,
}: AppointmentFormProps) {
  const isReadOnly = mode === 'view';

  const formik = useFormik<IAppointment>({
    initialValues: appointment,
    validationSchema: appointmentSchema,
    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
    enableReinitialize: true
  });

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

  const handleChange = (name: string, value: any) => {
    if (name === 'type' && value !== 'Visites Médicales avec la médecine du travail') {
      formik.setFieldValue('medicalCenterId', '');
      formik.setFieldValue('doctorId', '');
      formik.setFieldValue('medicalCenterName', '');
      formik.setFieldValue('doctorName', '');
    }

    if (name === 'type' && value !== 'Autre') {
      formik.setFieldValue('otherType', '');
    }
    
    formik.setFieldValue(name, value);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <FormContainer titre="Rendez-vous">
        <ConditionalComponent isValid={isReadOnly}>
          <EditExportButtons
            onEdit={() => onEdit(appointment)}
            onExport={() => void 0}
            tooltipTitle="le rendez-vous"
          />
        </ConditionalComponent>
  
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={3}>
            {formFields.map((field) => (
              <Grid item xs={12} md={4} key={field.name}>
                <FormField
                  field={field}
                  value={formik.values[field.name]}
                  onChange={handleChange}
                  error={
                    formik.touched[field.name]
                      ? (formik.errors[field.name] as string | undefined)
                      : undefined
                  }
                  onBlur={formik.handleBlur}
                  isReadOnly={Boolean(isReadOnly || (field.isDisabled && field.isDisabled(formik.values)))}
                />
              </Grid>
            ))}
            <Grid item xs={12}>
                <ActionButtons 
                  onSave={() => formik.handleSubmit()} 
                  onCancel={() => onClose(false)} 
                  mode={mode}
                />
            </Grid>
          </Grid>
        </form>
      </FormContainer>
    </LocalizationProvider>
  );
}
