import React, { useMemo, useState } from 'react';
import { Grid } from '@mui/material';
import type { ModeType } from '@/shared/types/common';
import ActionButtons from '@/shared/components/form/buttons-action';
import HorairesSpecifiqueTabs from '@/shared/sections/usager/components/usager-form/avenants-horaires/horaires-specifique-tabs';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { ScheduleDTO } from '@/shared/types/amendment';
import { Pageable } from '@/shared/types/client';
import { AmendmentCircuit } from '@/shared/types/ammendment-circuit';
import { WeeklyScheduleType } from '@/shared/sections/usager/components/usager-form/avenants-horaires/types/formik-types';
import { FormikProvider, useFormik } from 'formik';
import { enqueueSnackbar } from 'notistack';
import { convertFromFormikValues, convertToFormikValues, extractExistingWeekIds } from '../utils/convert-amendment-circuit';

interface EtablissementTabProps {
  mode: ModeType;
  onSave: () => void;
  onClose: (isSaved: boolean) => void;
  onEdit: () => void;
  avenant: AmendmentCircuit;
  schedules?: Pageable<ScheduleDTO>;
}
export interface FormikAmendmentCircuitDetails
  extends Omit<AmendmentCircuit, 'passengerScheduleWeeks'> {
  weeklySchedules: WeeklyScheduleType;
}

export default function CircuitAvenantHoraireForm({
  mode,
  onSave,
  onClose,
  onEdit,
  avenant,
  schedules
}: EtablissementTabProps) {
  const isReadOnly = mode === 'view';
  const [existingWeekIds, setExistingWeekIds] = useState<{ pair?: string | null; impair?: string | null }>({});
  const initialFormikValues = useMemo(() => {
    const weekIds = extractExistingWeekIds(avenant)
    setExistingWeekIds(weekIds)
    return convertToFormikValues(avenant)
  }, [avenant])

  const formik = useFormik<FormikAmendmentCircuitDetails>({
    initialValues: convertToFormikValues(avenant as AmendmentCircuit),
    enableReinitialize:true,
    onSubmit: async (values) => {
      /*try {
        const backendAmendment = convertFromFormikValues(values, mode === "edit" ? existingWeekIds : undefined)

        if (mode === "edit") {
          await updateAmendment(avenant.id, finalAmendment)
          enqueueSnackbar("Avenant modifié avec succès", { variant: 'success' });
          await fetchAmendments(getAmendmentParams(Number(usager.id)))
          markTabAsSaved(tabId, updatedAmendment)
          formik.resetForm({ values })
      } catch (error: any) {
        enqueueSnackbar(error.message, { variant: 'error' });
      }
    },*/
  }
})


  return (
    <>
      {isReadOnly ? (
        <EditExportButtons onEdit={onEdit} tooltipTitle="les horaires" />
      ) : null}
      <form>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <FormikProvider value={formik}> 
            <HorairesSpecifiqueTabs
              mode={mode}
              title=""
              withData={mode !== "add"}
              useFormik={true}
            />
            </FormikProvider>
          </Grid>
          {!isReadOnly && (
            <Grid item xs={12}>
              <ActionButtons onSave={onSave} onCancel={() => onClose(false)} mode={mode} />
            </Grid>
          )}
        </Grid>
      </form>
    </>
  );
}
