import React from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Typography,
  alpha,
  styled,
  CircularProgress,
  Box,
} from '@mui/material';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { faAddressCard, faClock, faPhone, faMapMarkerAlt } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import Link from 'next/link';
import { paths } from '@/routes/paths';
import { StyledTableContainer } from '@/shared/theme/css';
import { TripCircuitDTO } from '@/shared/types/circuit';
import TransportScheduleField from '@/shared/components/form/transport-schedule-field';
import {
  formatTripId,
  getTripTimeForPassenger,
  getObservationSchedulesForPassenger,
  calculateTotalDuration,
  calculateTotalDistance,
  calculateMaxPassengers,
  extractUniquePassengers,
  extractUniqueEstablishments,
  separateTripsByDirection,
  formatDistance
} from './trajet-details.helpers';
import { primary } from '@/shared/theme/palette';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { dateFormat, formatDate } from '@/utils/format-time';

// Styled components
const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '& > *:first-of-type': {
    borderBottomLeftRadius: '10px',
    borderTopLeftRadius: '10px',
  },
  '& > *:last-child': {
    borderTopRightRadius: '10px',
    borderBottomRightRadius: '10px',
  },
}));

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  padding: '8px',
}));

const HeaderCell = styled(StyledTableCell)(({ theme }) => ({
  backgroundColor: alpha(theme.palette.primary.main, 0.1),
  textAlign: 'center',
  color: theme.palette.text.disabled,
  fontWeight: 600,
}));

const DataCell = styled(StyledTableCell)(({ theme }) => ({
  textAlign: 'center',
  verticalAlign: 'middle',
}));

const PassengerCell = styled(StyledTableCell)(({ theme }) => ({
  '& > div:not(:last-child)': {
    marginBottom: '4px',
  },
  '& > div': {
    fontWeight: 500,
  },
}));

const SeparatorCell = styled(TableCell)(({ theme }) => ({
  width: '1px',
  padding: '0 !important',
  backgroundColor: alpha(primary.main, 0.5),
  borderRight: `2px solid ${theme.palette.divider}`,
}));

interface TripColumns {
  departures: TripCircuitDTO[];
  returns: TripCircuitDTO[];
}

interface TransportScheduleProps {
  circuitTripDetails?: TripCircuitDTO[];
  loadingCircuitTripDetails?: boolean;
  activationDate?: string;
}

export default function TransportSchedule({
  circuitTripDetails = [],
  loadingCircuitTripDetails = false,
  activationDate
}: TransportScheduleProps) {

  const tripColumns = React.useMemo((): TripColumns => {
    return separateTripsByDirection(circuitTripDetails);
  }, [circuitTripDetails]);

  const allPassengers = React.useMemo(() => {
    return extractUniquePassengers(circuitTripDetails);
  }, [circuitTripDetails]);

  const allEstablishments = React.useMemo(() => {
    return extractUniqueEstablishments(circuitTripDetails);
  }, [circuitTripDetails]);

  const hasReturns = tripColumns.returns.length > 0;
  const hasDepartures = tripColumns.departures.length > 0;

  if (loadingCircuitTripDetails) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" p={4}>
        <CircularProgress />
        <Typography variant="body2" sx={{ ml: 2 }}>
          Chargement des détails des trajets...
        </Typography>
      </Box>
    );
  }

  if (!circuitTripDetails || circuitTripDetails.length === 0) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" p={4}>
        <Typography variant="body2" color="text.secondary">
          Aucun détail de trajet disponible
        </Typography>
      </Box>
    );
  }

  return (
    <StyledTableContainer>
      <Table stickyHeader sx={{ mt: 1, minWidth: 960 }}>
        <TableHead>
          <StyledTableRow>
            <HeaderCell rowSpan={2} sx={{ minWidth: 200 }}>
              Date : {formatDate(activationDate || new Date(),dateFormat.split.date) }
            </HeaderCell>
            <SeparatorCell rowSpan={2} />

            <ConditionalComponent isValid={hasDepartures}>
              <HeaderCell colSpan={tripColumns.departures.length}>
                Aller
              </HeaderCell>
            </ConditionalComponent>

            <ConditionalComponent isValid={hasDepartures && hasReturns}>
              <SeparatorCell rowSpan={2} />
            </ConditionalComponent>

            <ConditionalComponent isValid={hasReturns}>
              <HeaderCell colSpan={tripColumns.returns.length}>
                Retour
              </HeaderCell>
            </ConditionalComponent>

            <SeparatorCell rowSpan={2} />

            <HeaderCell rowSpan={2} sx={{ minWidth: 300 }}>
              Observations
            </HeaderCell>
          </StyledTableRow>
          <TableRow>
            {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => (
              <HeaderCell key={`departure-${index}`} sx={{ minWidth: 120 }}>
                <Link href={`${paths.dashboard.exploitation.circuitUsager.trajet}?id=${trip.id}`}>
                  <Typography
                    component="a"
                    sx={{
                      color: 'primary.main',
                      textDecoration: 'none',
                      '&:hover': { textDecoration: 'underline' }
                    }}
                  >
                    {formatTripId(trip.id)}
                  </Typography>
                </Link>
                <Typography variant="body2" sx={{ fontSize: '10px' }}>
                  {trip.tripTitled}
                </Typography>
              </HeaderCell>
            ))}
            {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => (
              <HeaderCell key={`return-${index}`} sx={{ minWidth: 120 }}>
                <Link href={`${paths.dashboard.exploitation.circuitUsager.trajet}?id=${trip.id}`}>
                  <Typography
                    component="a"
                    sx={{
                      color: 'primary.main',
                      textDecoration: 'none',
                      '&:hover': { textDecoration: 'underline' }
                    }}
                  >
                    {formatTripId(trip.id)}
                  </Typography>
                </Link>
                <Typography variant="body2" sx={{ fontSize: '10px' }}>
                  {trip.tripTitled}
                </Typography>
              </HeaderCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {allPassengers.map((passenger, passengerIndex) => (
            <TrajetStyledRow key={`passenger-${passenger.id}`}>
              <PassengerCell>
                <Box>
                  <FontAwesome
                    icon={faAddressCard}
                    color="primary.main"
                    width={15}
                    sx={{ mr: 1 }}
                  />
                  {passenger.name}
                </Box>
                <Box>
                  <FontAwesome icon={faPhone} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {passenger.phone}
                </Box>
                <Box>
                  <FontAwesome icon={faMapMarkerAlt} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {passenger.address}
                </Box>
                <Box>
                  <Box
                    component="img"
                    src="/assets/icons/menu/ic_exploitation.svg"
                    sx={{
                      width: 15,
                      height: 15,
                      color: 'primary.main',
                      mr: 1,
                      pt: 0.5,
                      display: 'inline-flex',
                    }}
                  />
                  {passenger.establishment}
                </Box>
              </PassengerCell>
              <SeparatorCell />

              {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => (
                <DataCell key={`departure-time-${index}`}>
                  {getTripTimeForPassenger(trip, passenger.id)}
                </DataCell>
              ))}

              <ConditionalComponent isValid={hasDepartures && hasReturns}>
                <SeparatorCell />
              </ConditionalComponent>

              {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => (
                <DataCell key={`return-time-${index}`}>
                  {getTripTimeForPassenger(trip, passenger.id)}
                </DataCell>
              ))}

              <SeparatorCell />

              <StyledTableCell sx={{ p: 1, minWidth: 300 }}>
                <TransportScheduleField
                  initialSchedules={getObservationSchedulesForPassenger(
                    circuitTripDetails,
                    passenger.id,
                    { latitude: (passenger as any).latitude, longitude: (passenger as any).longitude }
                  )}
                  onChange={() => { }}
                  isReadOnly={true}
                />
              </StyledTableCell>
            </TrajetStyledRow>
          ))}

          {allEstablishments.map((establishment, establishmentIndex) => (
            <TrajetStyledRow key={`establishment-${establishmentIndex}`}>
              <PassengerCell>
                <Box>
                  <Box
                    component="img"
                    src="/assets/icons/menu/ic_exploitation.svg"
                    sx={{
                      width: 15,
                      height: 15,
                      color: 'primary.main',
                      mr: 1,
                      pt: 0.5,
                      display: 'inline-flex',
                    }}
                  />
                  {establishment.name}
                </Box>
                <Box>
                  <FontAwesome icon={faPhone} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {establishment.phone}
                </Box>
                <Box>
                  <FontAwesome icon={faMapMarkerAlt} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {establishment.address}
                </Box>
              </PassengerCell>
              <SeparatorCell />

              {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => {
                const establishmentInfo = trip.tripCircuitDays?.find(day =>
                  day.establishmentInfoTrip?.establishmentName === establishment.name
                )?.establishmentInfoTrip;
                return (
                  <DataCell key={`departure-establishment-${index}`}>
                    {establishmentInfo?.arrivalTime || '-'}
                  </DataCell>
                );
              })}

              <ConditionalComponent isValid={hasDepartures && hasReturns}>
                <SeparatorCell />
              </ConditionalComponent>

              {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => {
                const establishmentInfo = trip.tripCircuitDays?.find(day =>
                  day.establishmentInfoTrip?.establishmentName === establishment.name
                )?.establishmentInfoTrip;
                return (
                  <DataCell key={`return-establishment-${index}`}>
                    {establishmentInfo?.arrivalTime || '-'}
                  </DataCell>
                );
              })}
              <SeparatorCell />

              <StyledTableCell sx={{ p: 1, minWidth: 300 }}>
                <Typography variant="body2" color="text.secondary">
                  {'-'}
                </Typography>
              </StyledTableCell>
            </TrajetStyledRow>
          ))}

          <TrajetStyledRow>
            <StyledTableCell sx={{ fontWeight: 500 }}>
              <FontAwesome icon={faClock} color="primary.main" width={15} sx={{ mr: 1 }} />
              Temps en charge
            </StyledTableCell>
            <SeparatorCell />
            {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`departure-duration-${index}`}>
                {trip.duration || ''}
              </DataCell>
            ))}
            <ConditionalComponent isValid={hasDepartures && hasReturns}>
              <SeparatorCell />
            </ConditionalComponent>
            {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`return-duration-${index}`}>
                {trip.duration || ''}
              </DataCell>
            ))}
            <SeparatorCell />
            <StyledTableCell>
              Total Temps en charge : {calculateTotalDuration(circuitTripDetails)}min
            </StyledTableCell>
          </TrajetStyledRow>

          <TrajetStyledRow>
            <StyledTableCell sx={{ fontWeight: 500 }}>
              <Box
                component="img"
                src="/assets/icons/menu/ic_exploitation.svg"
                sx={{
                  width: 15,
                  height: 15,
                  color: 'primary.main',
                  mr: 1,
                  display: 'inline-flex',
                }}
              />
              Kilomètre en charge
            </StyledTableCell>
            <SeparatorCell />
            {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`departure-distance-${index}`}>
                {formatDistance(trip.distanceKm || 0)}
              </DataCell>
            ))}
            <ConditionalComponent isValid={hasDepartures && hasReturns}>
              <SeparatorCell />
            </ConditionalComponent>
            {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`return-distance-${index}`}>
                {formatDistance(trip.distanceKm || 0)}
              </DataCell>
            ))}
            <SeparatorCell />
            <StyledTableCell>
              Total Kilomètre en charge : {calculateTotalDistance(circuitTripDetails)}Km
            </StyledTableCell>
          </TrajetStyledRow>

          <TrajetStyledRow>
            <StyledTableCell sx={{ fontWeight: 500 }}>
              <FontAwesome icon={faAddressCard} color="primary.main" width={15} sx={{ mr: 1 }} />
              Usagers transportés
            </StyledTableCell>
            <SeparatorCell />
            {tripColumns.departures.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`departure-passengers-${index}`}>
                {trip.passengerCount || 0}
              </DataCell>
            ))}
            <ConditionalComponent isValid={hasDepartures && hasReturns}>
              <SeparatorCell />
            </ConditionalComponent>
            {tripColumns.returns.map((trip: TripCircuitDTO, index: number) => (
              <DataCell key={`return-passengers-${index}`}>
                {trip.passengerCount || 0}
              </DataCell>
            ))}
            <SeparatorCell />
            <StyledTableCell>
              Total Usagers transportés : {calculateMaxPassengers(circuitTripDetails)}
            </StyledTableCell>
          </TrajetStyledRow>
        </TableBody>
      </Table>
    </StyledTableContainer>
  );
}