import React, { useEffect } from 'react';
import {
  Box,
  Typography,
  Stack,
  Grid,
  CircularProgress,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableCell,
  TableRow,
} from '@mui/material';
import { pxToRem } from '@/shared/theme/typography';
import {
  faCalendarDay,
  faCalendarTimes,
  faCar,
  faClock,
  faHashtag,
  faMapMarkerAlt,
  faUserFriends,
  faUserTie,
} from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import RoadMapHistoryTable from './roadmap-history-table';
import { fr } from 'date-fns/locale';
import FormContainer from '@/layouts/form/form-container';
import { PlanningRequest, TripDetails } from '@/shared/types/roadMap';
import { formatDate } from '@/utils/format-time';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import TableNoData from '@/shared/components/table/table-no-data';
import { format } from 'date-fns';

interface RoadMapHistoryDetailsProps {
  data: PlanningRequest;
}
const HEAD_CELLS = [
  { id: 'id', label: 'Id', align: 'center' },
  { id: 'driverName', label: 'Nom du chauffeur', align: 'left' },
  { id: 'sendDate', label: "Date d'envoie", align: 'left' },
  { id: 'sendHour', label: "L'heure d'envoie", align: 'left' },
  { id: 'codeCircuit', label: 'Code circuit', align: 'left' },
  { id: 'tripDetails', label: 'Intitulé du trajet', align: 'left' },
];
const RoadMapHistoryDetails = ({ data }: RoadMapHistoryDetailsProps) => {
  const { planningRequestDetails, getPlanningRequestDetails, loading, error } = useRoadMapStore();
  useEffect(() => {
    getPlanningRequestDetails(Number(data.id));
  }, [data.id]);

  const formatTripDetails = (trip: TripDetails) => {
    const formattedDate = trip.date
      ? format(new Date(trip.date), 'eee dd yyyy', { locale: fr })
      : '-';

    return (
      <Stack spacing={0.5}>
        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faCalendarDay} width={14} color="primary.main" />
          <Typography variant="body2">{formattedDate}</Typography>
        </Stack>
        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faMapMarkerAlt} width={14} color="primary.main" />
       <ConditionalComponent
  isValid={!!trip?.departure}
  defaultComponent="-"
>
  <Typography variant="body2">
    Départ : {trip?.departure?.street}, {trip?.departure?.city} ({trip?.departure?.postalCode},{' '}
    {trip?.departure?.country})
  </Typography>
</ConditionalComponent>

        </Stack>

        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faMapMarkerAlt} width={14} color="secondary.main" />
        <ConditionalComponent
  isValid={!!trip?.destination}
  defaultComponent="-"
>
  <Typography variant="body2">
    Arrivé : {trip?.destination?.street}, {trip?.destination?.city} ({trip?.destination?.postalCode},{' '}
    {trip?.destination?.country})
  </Typography>
</ConditionalComponent>

        </Stack>

        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faClock} width={14} />
          <Typography variant="body2">
            Heure départ : {trip.startHeure}:{trip.startMinute} | Heure arrivée : {trip.endHeure}:
            {trip.endMinute}
          </Typography>
        </Stack>
        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faUserFriends} width={14} />
          <Typography variant="body2">Passagers : {trip.nbPassengers}</Typography>
        </Stack>

        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faCar} width={14} />
          <Typography variant="body2">Véhicule : {trip.vehicleId}</Typography>
        </Stack>
      </Stack>
    );
  };

  return (
    <>
      <Box sx={{ bgcolor: 'white', borderRadius: '12px', pb: '30px' }}>
        <Typography
          sx={{
            textAlign: 'center',
            p: 3,
            fontSize: pxToRem(30),
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          {data.title}
        </Typography>
        <Stack direction="row" justifyContent="space-between" sx={{ px: 3 }}>
          <Stack spacing={1}>
            <Stack direction="row" alignItems="center" spacing={1}>
              <FontAwesome icon={faCalendarDay} color="primary.main" width={16} />
              <Typography>Date d&apos;envoie : {data.sendDate}</Typography>
            </Stack>
            <Stack direction="row" alignItems="center" spacing={1}>
              <FontAwesome icon={faUserTie} color="primary.main" width={16} />
              <Typography>Envoyer par : {data.agentName}</Typography>
            </Stack>
          </Stack>

          <Stack spacing={1}>
            <Stack direction="row" alignItems="center" spacing={1}>
              <FontAwesome icon={faUserTie} color="primary.main" width={16} />
              <Typography>Nombre de chauffeurs : {data.driversCount}</Typography>
            </Stack>
            <Stack direction="row" alignItems="center" spacing={1}>
              <FontAwesome icon={faCalendarTimes} color="primary.main" width={16} />
              <Typography>Fréquence : {data.planningType}</Typography>
            </Stack>
          </Stack>
          <Stack spacing={1}>
            <Stack direction="row" alignItems="center" spacing={1}>
              <FontAwesome icon={faClock} color="primary.main" width={16} />
              <Typography>Date de création : {formatDate(data.createdAt)}</Typography>
            </Stack>
            <ConditionalComponent isValid={!!data.endDate}>
              <Stack direction="row" alignItems="center" spacing={1}>
                <FontAwesome icon={faHashtag} color="primary.main" width={16} />
                <Typography>
                  {' '}
                  Période : {formatDate(data.startDate)} → {formatDate(data.endDate)}
                </Typography>
              </Stack>
            </ConditionalComponent>
          </Stack>
        </Stack>
      </Box>{' '}
      <Box sx={{ backgroundColor: 'white' }}>
        <ConditionalComponent
          isValid={!loading}
          defaultComponent={
            <Box sx={{ textAlign: 'center', mt: 4 }}>
              <CircularProgress size={48} />
            </Box>
          }
        >
          <TableContainer sx={{ mb: 4 }}>
            <Table>
              <TableHead>
                <TableRow>
                  {HEAD_CELLS.map((headCell) => (
                    <TableCell key={headCell.id} align={headCell.align as any}>
                      {headCell.label}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>

              <TableBody>
                <ConditionalComponent
                  isValid={planningRequestDetails.length > 0}
                  defaultComponent={<TableNoData notFound colSpan={HEAD_CELLS.length} />}
                >
                  {planningRequestDetails.map((detail) => (
                    <ConditionalComponent
                      key={detail.id}
                      isValid={!!detail.trips && detail.trips.length > 0}
                      defaultComponent={
                        <TableRow>
                          <TableCell align="center">{detail.id}</TableCell>
                          <TableCell align="left">{detail.driverName}</TableCell>
                          <TableCell align="left">{detail.sendDate || '-'}</TableCell>
                          <TableCell align="left">{detail.sendHour || '-'}</TableCell>

                          <TableCell align="left">
                            <ConditionalComponent
                              isValid={!!detail.circuitsCodes && detail.circuitsCodes.length > 0}
                              defaultComponent="-"
                            >
                              <Stack spacing={0.5}>
                                {detail.circuitsCodes?.map((code, idx) => (
                                  <Stack key={idx} direction="row" alignItems="center" spacing={1}>
                                    <FontAwesome icon={faHashtag} width={12} color="primary.main" />
                                    <Typography variant="body2">{code}</Typography>
                                  </Stack>
                                ))}
                              </Stack>
                            </ConditionalComponent>
                          </TableCell>

                          <TableCell align="left">
                            <ConditionalComponent
                              isValid={!!detail.distinctNames && detail.distinctNames.length > 0}
                              defaultComponent="-"
                            >
                              <Stack spacing={0.5}>
                                {detail.distinctNames?.map((name, idx) => (
                                  <Stack key={idx} direction="row" alignItems="center" spacing={1}>
                                    <FontAwesome
                                      icon={faUserTie}
                                      width={12}
                                      color="secondary.main"
                                    />
                                    <Typography variant="body2">{name}</Typography>
                                  </Stack>
                                ))}
                              </Stack>
                            </ConditionalComponent>
                          </TableCell>
                        </TableRow>
                      }
                    >
                      {(detail.trips ?? []).map((trip, idx) => (
                        <TableRow key={`${detail.id}-${idx}`}>
                          <ConditionalComponent isValid={idx === 0}>
                            <>
                              <TableCell align="center" rowSpan={detail.trips?.length || 1}>
                                {detail.id}
                              </TableCell>
                              <TableCell align="left" rowSpan={detail.trips?.length || 1}>
                                {detail.driverName}
                              </TableCell>
                              <TableCell align="left" rowSpan={detail.trips?.length || 1}>
                                {detail.sendDate || '-'}
                              </TableCell>
                              <TableCell align="left" rowSpan={detail.trips?.length || 1}>
                                {detail.sendHour || '-'}
                              </TableCell>
                            </>
                          </ConditionalComponent>
                          <TableCell align="left">
                            <Stack direction="row" alignItems="center" spacing={1}>
                              <FontAwesome icon={faHashtag} width={12} color="primary.main" />
                              <Typography variant="body2">{trip.codeCircuit}</Typography>
                            </Stack>
                          </TableCell>
                          <TableCell align="left">{formatTripDetails(trip)}</TableCell>
                        </TableRow>
                      ))}
                    </ConditionalComponent>
                  ))}
                </ConditionalComponent>
              </TableBody>
            </Table>
          </TableContainer>
        </ConditionalComponent>
      </Box>
    </>
  );
};

export default RoadMapHistoryDetails;
