import React, { useMemo } 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 { IAvenant } from '@/shared/types/circuit';
import { ScheduleDTO } from '@/shared/types/amendment';
import { Pageable } from '@/shared/types/client';

interface EtablissementTabProps {
  mode: ModeType;
  onSave: () => void;
  onClose: (isSaved: boolean) => void;
  onEdit: () => void;
  avenant?: IAvenant;
  schedules?: Pageable<ScheduleDTO>;
}

export default function AvenantHoraireForm({
  mode,
  onSave,
  onClose,
  onEdit,
  avenant,
  schedules
}: EtablissementTabProps) {
  const isReadOnly = mode === 'view';

  // Transform schedules data for HorairesSpecifiqueTabs
  const transformedSchedules = useMemo(() => {
    if (!schedules?.content || !Array.isArray(schedules.content)) {
      return [];
    }
    
    return schedules.content.map((schedule: ScheduleDTO) => ({
      id: schedule.id,
      direction: schedule.direction === 'OUTBOUND' ? 'OUTBOUND' : 'RETURN',
      days: schedule.days?.split(',') || [],
      time: schedule.time || schedule.departureTime,
      departureTime: schedule.departureTime,
      arrivalTime: schedule.arrivalTime,
      tripId: schedule.tripId,
      day: schedule.day,
      capacity: schedule.capacity,
      active: schedule.active,
      type: schedule.type,
      status: schedule.status
    })) as unknown as ScheduleDTO[];
  }, [schedules]);

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