import React, { useState, useEffect } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  Typography,
  Box,
  CircularProgress,
} from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faClock, faSun, faMoon, faRoute, faTags } from '@fortawesome/free-solid-svg-icons';

import { useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import {
  ITripShort,
  PeriodOfDayTripShort,
  sensTripOptions,
  TripType,
} from '@/shared/types/circuit';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import TableNoData from '@/shared/components/table/table-no-data';
import { PeriodOfDay } from '@/shared/types/ammendment-passenger';

type Props = {
  driverId: number;
  date: string; 
};

const HEAD_CELLS = [
  { id: 'code', label: 'Code Circuit', align: 'center' },
  { id: 'tripInfo', label: 'Intitulé du trajet', align: 'left' },
    { id: 'circuitName', label: 'Nom du circuit', align: 'left' },
];

export default function RoadMapHistoryTable({ driverId, date }: Props) {
  const { getTripsByDriverIdAndDate, loading, error } = useCircuitStore();
  const [trips, setTrips] = useState<ITripShort[]>([]);

  useEffect(() => {
    if (driverId && date) {
      const [monthStr, yearStr] = date.split('/');
      const year = parseInt(yearStr, 10);
      const month = parseInt(monthStr, 10);

      getTripsByDriverIdAndDate?.(driverId, year, month)
        .then(setTrips)
        .catch((err) => console.error('Erreur récupération trajets :', err));
    }
  }, [driverId, date, getTripsByDriverIdAndDate]);
  const getSensTripLabel = (value: string) => {
    const found = sensTripOptions.find((opt) => opt.value === value);
    return found?.label || value;
  };
  const getPeriodOfDayLabel = (value: string): string => {
    return PeriodOfDayTripShort[value as keyof typeof PeriodOfDayTripShort] || value;
  };
  const getTripTypeLabel = (value: string): string => {
    return TripType[value as keyof typeof TripType] || value;
  };

  const renderTripDetails = (trip: ITripShort) => {
    const periodIcon = trip.periodOfDay == PeriodOfDayTripShort.MORNING ? faSun : faMoon;

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', whiteSpace: 'nowrap' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.3 }}>
          <FontAwesome icon={faTags} color="primary.main" width={14} />
          <Typography variant="body2" sx={{ ml: 1, fontWeight: 'bold' }}>
            {trip.tripTitled}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.3 }}>
          <FontAwesome icon={periodIcon} color="primary.main" width={14} />
          <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
            {getPeriodOfDayLabel(trip.periodOfDay)}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 0.3 }}>
          <FontAwesome icon={faRoute} color="primary.main" width={14} />
          <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
            {getSensTripLabel(trip.sensTrip)}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <FontAwesome icon={faClock} color="primary.main" width={14} />
          <Typography variant="caption" color="text.secondary" sx={{ ml: 1 }}>
            {getTripTypeLabel(trip.tripType)}
          </Typography>
        </Box>
      </Box>
    );
  };

  return (
    <>
      <Typography
        variant="h5"
        sx={{
          textAlign: 'center',
          my: 2,
          mb: 3,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Trajets assignés
      </Typography>

      <ConditionalComponent
        isValid={!loading}
        defaultComponent={
          <Box sx={{ textAlign: 'center', mt: 4 }}>
            <CircularProgress size={48} />
          </Box>
        }
      >
        <TableContainer>
          <Table>
            <TableHead>
              <tr>
                {HEAD_CELLS.map((headCell) => (
                  <TableCell
                    key={headCell.id}
                    align={
                      headCell.align as
                        | 'center'
                        | 'left'
                        | 'right'
                        | 'inherit'
                        | 'justify'
                        | undefined
                    }
                  >
                    {headCell.label}
                  </TableCell>
                ))}
              </tr>
            </TableHead>

            <TableBody>
              <ConditionalComponent
                isValid={trips.length > 0}
                defaultComponent={<TableNoData notFound={true} colSpan={4} />}
              >
                {trips.map((trip) => (
                  <tr key={trip.id}>
                    <TableCell align="left">{trip.circuitCode}</TableCell>
                    <TableCell align="left">{renderTripDetails(trip)}</TableCell>
                    <TableCell align="left">{trip.circuitTitled}</TableCell>
                  </tr>
                ))}
              </ConditionalComponent>
            </TableBody>
          </Table>
        </TableContainer>
      </ConditionalComponent>
    </>
  );
}
