'use client';

import { useFormik } from 'formik';
import { Grid } from '@mui/material';
import * as yup from 'yup';
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 type { IPreparationCircuit } from '@/shared/types/circuit';
import ActionButtons from '@/shared/components/form/buttons-action';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { preparationCircuitFormFields } from '../utils/form-fields-circuit';
import { preparationCircuitSchema } from '../utils/preparation-circuit-schema';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useEffect } from 'react';

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

export default function PreparationCircuitForm({
  preparationCircuit,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  updateTabContent,
  tabId,
}: PreparationCircuitFormProps) {
  const isReadOnly = mode === 'view';

  const formik = useFormik<IPreparationCircuit>({
    initialValues: preparationCircuit,
    validationSchema: preparationCircuitSchema,

    onSubmit: (values) => {
      onSave(values);
      onClose(true);
    },
    enableReinitialize: true,
  });

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<IPreparationCircuit>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof IPreparationCircuit]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={formik.touched[field.name as keyof IPreparationCircuit]
        ?
        field.name === "adresseEtablissement" ? (formik.errors.adresseEtablissement as any)?.address
          :
          String(formik.errors[field.name])
        : undefined}
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  );

  return (
    <FormContainer titre="Fiche Circuits">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={() => onEdit(formik.values)}
          onExport={() => void 0}
          tooltipTitle={TableType.Circuit}
          dataRow={preparationCircuit}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          {preparationCircuitFormFields.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>
  );
}