'use client';

import { Box, Button } from '@mui/material';
import { ScrollBox } from '@/shared/theme/css';
import CreateRoadMapMileage from './create-roadmap-mileage';
import VisitSection from './add-other-roads';
import UserInformationCard from './create-roadmap-details';
import RoadMapDrawer from './roadmap-drawer';
import { useBoolean } from '@/hooks';
import RoadMapTimePickerComponent from './time-section-roadmap';
import { SubmittedRoadMapDTO} from '@/shared/types/roadMap';
import { WorkedDayDTO } from '@/shared/types/driver-roadmap';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import { useState, useEffect } from 'react';
import { useWorkedDayStore } from '@/shared/api/stores/workedDayStore';
import dayjs, { Dayjs } from 'dayjs';
import { enqueueSnackbar } from 'notistack';

type Props = {
  activeTabData: SubmittedRoadMapDTO;
};

const roadTypes = ['MATIN', 'MIDI', 'APRES_MIDI', 'SOIR'] as const;

type RoadType = typeof roadTypes[number];

function convertRoadsArrayToObject(roadsArray: any[]): Record<RoadType, any> {
  const roads: Record<RoadType, any> = {
    MATIN: { startHour: '', endHour: '', disabled: true },
    MIDI: { startHour: '', endHour: '', disabled: true },
    APRES_MIDI: { startHour: '', endHour: '', disabled: true },
    SOIR: { startHour: '', endHour: '', disabled: true },
  };

  roadsArray?.forEach((road) => {
    const type = road.type as RoadType;
    if (roads[type]) {
      roads[type] = {
        startHour: road.startHour?.substring(0, 5) || '',
        endHour: road.endHour?.substring(0, 5) || '',
        disabled: false,
      };
    }
  });

  return roads;
}

export default function CreatRoadMapPage({ activeTabData }: Props) {
  const DRAWER_WIDTH = 550;
  const openDrawer = useBoolean();

  const [workedDay, setWorkedDay] = useState<WorkedDayDTO | null>(null);
  const [selectedDate, setSelectedDate] = useState<Dayjs | null>(dayjs());

  const handleOnClick = () => openDrawer.onTrue();

  const cleanHour = (hour: string | undefined | null): string => {
    if (!hour) return '';
    return hour.slice(0, 5);
  };

  return (
    <Box sx={{ display: 'flex' }}>
      <ScrollBox
        sx={{
          display: 'flex',
          flexDirection: 'column',
          width: openDrawer.value ? `calc(100% - ${DRAWER_WIDTH}px)` : '100%',
        }}
      >
        <UserInformationCard
          handleOnClick={handleOnClick}
          activeTabData={activeTabData}
          setWorkedDay={setWorkedDay}
          setSelectedDate={setSelectedDate} 
        />

      <Formik
        enableReinitialize
        initialValues={{
          fuelAmount: workedDay?.fuelAmount ?? '',
          startMileage: workedDay?.mileageIntervall?.startMileage ?? '',
          endMileage: workedDay?.mileageIntervall?.endMileage ?? '',
          observation: workedDay?.observation ?? '',
          garageStart:
            workedDay?.otherTrips?.find((t) => t.type === 'GARAGE_VISIT')?.startHour?.substring(0, 5) ?? '',
          garageEnd:
            workedDay?.otherTrips?.find((t) => t.type === 'GARAGE_VISIT')?.endHour?.substring(0, 5) ?? '',
          medicalStart:
            workedDay?.otherTrips?.find((t) => t.type === 'MEDICAL_VISIT')?.startHour?.substring(0, 5) ?? '',
          medicalEnd:
            workedDay?.otherTrips?.find((t) => t.type === 'MEDICAL_VISIT')?.endHour?.substring(0, 5) ?? '',
          roads: convertRoadsArrayToObject(workedDay?.roads || []),
        }}
        validationSchema={Yup.object().shape({
          fuelAmount: Yup.number().required(),
          startMileage: Yup.number().required(),
          endMileage: Yup.number().required(),
        })}
        onSubmit={async (values) => {
        
          const date = selectedDate?.format('YYYY-MM-DD') ?? '';
          if (!activeTabData?.id || !date) {
            console.warn('No ID or date - skipping submit');
            return;
          }
        
          const payload: WorkedDayDTO = {
            driverRoadMapId: Number(activeTabData.id),
            date,
            fuelAmount: Number(values.fuelAmount),
            observation: values.observation,
            mileageIntervall: {
              startMileage: Number(values.startMileage),
              endMileage: Number(values.endMileage),
            },
            roads: Object.entries(values.roads)
              .filter(([_, r]) => !r.disabled)
              .map(([type, r]) => ({
                type,
                startHour: r.startHour + ':00',
                endHour: r.endHour + ':00',
              })),
            otherTrips: [
              ...(values.garageStart && values.garageEnd
                ? [{
                    type: 'GARAGE_VISIT',
                    startHour: values.garageStart + ':00',
                    endHour: values.garageEnd + ':00',
                  }]
                : []),
              ...(values.medicalStart && values.medicalEnd
                ? [{
                    type: 'MEDICAL_VISIT',
                    startHour: values.medicalStart + ':00',
                    endHour: values.medicalEnd + ':00',
                  }]
                : []),
            ],
          };
          try {
            await useWorkedDayStore.getState().submitWorkedDay(payload);
            enqueueSnackbar('crée avec succès.', { variant: 'success' });
          } catch (err) {
            console.error('Error during API call:', err);
            enqueueSnackbar('Error.', { variant: 'error' });
          }
        }}
        
        
      >
        {({ handleSubmit }) => (
          <Form>
            <RoadMapTimePickerComponent />
            <CreateRoadMapMileage />
            <VisitSection />

            <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2, p: 3 }}>
              <Button variant="outlined" color="primary">
                Annuler
              </Button>
              <Button
                variant="contained"
                color="primary"
                type="submit" 
              >
                Soumettre
              </Button>
            </Box>
          </Form>
        )}
      </Formik>
      </ScrollBox>

      <RoadMapDrawer isOpen={openDrawer} onClose={openDrawer.onFalse} />
    </Box>
  );
}
