'use client';

import {
  Box,
  Button,
  CircularProgress,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} 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';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown, faChevronUp, faEdit } from '@fortawesome/free-solid-svg-icons';
import { useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';

type Props = {
  activeTabData: SubmittedRoadMapDTO;
  onCloseTab?: (tabId: string) => void;
};

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, onCloseTab }: Props) {
  const DRAWER_WIDTH = 550;
  const openDrawer = useBoolean();
  const { getDriverCircuits, circuits, loading, error } = useCircuitStore();
  const [workedDay, setWorkedDay] = useState<WorkedDayDTO | null>(null);
  const [selectedDate, setSelectedDate] = useState<Dayjs | null>(dayjs());
  const [isEditMode, setIsEditMode] = useState(false);
  const { workedDaysDates, getWorkedDaysDates } = useRoadMapStore();
  useEffect(() => {
    if (!selectedDate || !activeTabData.workedDaysDates) return;

    const selectedDateStr = selectedDate.format('YYYY-MM-DD');
    const isToday = dayjs().isSame(selectedDate, 'day');
    const isSelectedDateSubmitted = activeTabData.workedDaysDates.includes(selectedDateStr);

    setIsEditMode(isToday && isSelectedDateSubmitted);
  }, []);

  const handleChoose = (dateStr: string) => {
    if (activeTabData.workedDaysDates?.includes(dateStr)) {
      setIsEditMode(true);
    } else {
      setIsEditMode(false);
    }
  };

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

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

  useEffect(() => {
    if (activeTabData.driverId && selectedDate) {
      getDriverCircuits(activeTabData.driverId, selectedDate.format('YYYY-MM-DD'));
    }
  }, [activeTabData.driverId, selectedDate, getDriverCircuits]);

  const [openRowId, setOpenRowId] = useState<string | null>(null);
  const toggleRow = (rowId: string) => {
    setOpenRowId((prev) => (prev === rowId ? null : rowId));
  };

  useEffect(() => {
    if (!activeTabData?.id) return;
    getWorkedDaysDates(Number(activeTabData.id));
  }, [activeTabData?.id, getWorkedDaysDates]);

  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}
          initialDate={activeTabData.date}
          workedDaysDates={workedDaysDates}
          onChoose={handleChoose}
        />
        <Box>
          <Typography
            variant="h6"
            sx={{
              textAlign: 'center',
              my: 2,
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Circuits du chauffeur
          </Typography>
          <ConditionalComponent
            isValid={!loading}
            defaultComponent={
              <Box sx={{ textAlign: 'center', mt: 4 }}>
                <CircularProgress size={48} />
              </Box>
            }
          >
            <TableContainer
              sx={{
                mt: 2,
                mb: 2,
                bgcolor: ' rgb(188 219 245 / 8%)',
                p: 2,
                borderRadius: 2,
                boxShadow: 1,
              }}
            >
              <Table>
                <TableHead>
                  <tr>
                    <TableCell align="left">Code Circuit </TableCell>
                    <TableCell align="left">Intitulé </TableCell>
                  </tr>
                </TableHead>
                <TableBody>
                  <ConditionalComponent
                    isValid={!!circuits?.length}
                    defaultComponent={
                      <TableRow>
                        <TableCell align="center" colSpan={5}>
                          Aucun circuit trouvé pour cette date.
                        </TableCell>
                      </TableRow>
                    }
                  >
                    {circuits?.map((cirucit) => (
                      <>
                        <TableRow key={cirucit.id}>
                          <TableCell align="left">{cirucit.circuitCode}</TableCell>
                          <TableCell align="left">{cirucit.titled}</TableCell>

                          <TableCell align="right">
                            <IconButton onClick={() => toggleRow(cirucit.id)}>
                              <FontAwesomeIcon
                                icon={openRowId === cirucit.id ? faChevronUp : faChevronDown} 
                              />
                            </IconButton>
                          </TableCell>
                        </TableRow>

                        <ConditionalComponent isValid={openRowId === cirucit.id}>
                          <TableRow>
                            <TableCell colSpan={5} sx={{ pt: 0 }}>
                              <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().moreThan(
                                    0,
                                    'Le montant de carburant doit être supérieure à 0'
                                  ),
                                  startMileage: Yup.number()
                                    .required()
                                    .moreThan(
                                      0,
                                      'Le kilométrage en début de journée doit être > 0'
                                    ),
                                  endMileage: Yup.number()
                                    .required()
                                    .moreThan(0, 'Le kilométrage en fin doit être > 0')
                                    .test(
                                      'is-greater',
                                      'Le kilométrage de fin doit être supérieur au départ',
                                      function (value) {
                                        const { startMileage } = this.parent;
                                        return value > startMileage;
                                      }
                                    ),
                                })}
                                onSubmit={async (values) => {
                                  const date = selectedDate?.format('YYYY-MM-DD') ?? '';
                                  if (!activeTabData?.id || !date) {
                                    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);
                                    await getWorkedDaysDates(Number(activeTabData.id));
                                    enqueueSnackbar('Crée avec succès.', { variant: 'success' });
                                    setOpenRowId(null);
                                  } catch (err) {
                                    enqueueSnackbar('Erreur.', { variant: 'error' });
                                  }
                                }}
                              >
                                {({ handleSubmit }) => (
                                  <Form>
                                    <ConditionalComponent isValid={isEditMode}>
                                      <Box
                                        sx={{ display: 'flex', justifyContent: 'flex-end', mr: 3 }}
                                      >
                                        <CustomTooltip
                                          title="Modification de la feuille de route"
                                          arrow
                                        >
                                          <IconButton onClick={() => setIsEditMode(false)}>
                                            <FontAwesomeIcon icon={faEdit} width={24} />
                                          </IconButton>
                                        </CustomTooltip>
                                      </Box>
                                    </ConditionalComponent>

                                    <RoadMapTimePickerComponent isEditMode={!isEditMode} />
                                    <CreateRoadMapMileage isEditMode={!isEditMode} />
                                    <VisitSection isEditMode={!isEditMode} />
                                    <Box
                                      sx={{
                                        display: 'flex',
                                        justifyContent: 'flex-end',
                                        gap: 2,
                                        p: 3,
                                      }}
                                    >
                                      <Button
                                        variant="outlined"
                                        color="primary"
                                        onClick={() => setOpenRowId(null)}
                                      >
                                        Annuler
                                      </Button>
                                      <Button variant="contained" color="primary" type="submit">
                                        Valider
                                      </Button>
                                    </Box>
                                  </Form>
                                )}
                              </Formik>
                            </TableCell>
                          </TableRow>
                        </ConditionalComponent>
                      </>
                    ))}
                  </ConditionalComponent>
                </TableBody>
              </Table>
            </TableContainer>
          </ConditionalComponent>
        </Box>
      </ScrollBox>

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