import React from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Typography,
  alpha,
  styled,
} from '@mui/material';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { faAddressCard, faClock, faPhone } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import { Box } from '@mui/system';
import { passengers, summaryRows, timeSlots } from '@/shared/_mock/_circuitTrajets';
import Link from 'next/link';
import { paths } from '@/routes/paths';
import { StyledTableContainer } from '@/shared/theme/css';
import { ScheduleDTO, TripDTO } from '@/shared/types/amendment';

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,
  '&.date-cell, &.observations-cell': {
    width: '25%',
  },
}));
const SousHeaderCell = styled(HeaderCell)(({ theme }) => ({
  color: theme.palette.text.primary,
  fontWeight: 400,
}));

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

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

interface TransportScheduleProps {
  schedules?: ScheduleDTO[];
  trips?: TripDTO[];
}

export default function TransportSchedule({ schedules, trips }: TransportScheduleProps) {
  // If no real data is provided, fall back to mock data
  const displaySchedules = schedules || [];
  const displayTrips = trips || [];

  // Process schedules to create time slots for table headers
  const processedTimeSlots = React.useMemo(() => {
    if (displaySchedules.length === 0) {
      return timeSlots; // Fall back to mock data
    }

    // Group schedules by direction and create time slots
    const outboundSchedules = displaySchedules.filter(s => s.direction === 'OUTBOUND');
    const returnSchedules = displaySchedules.filter(s => s.direction === 'RETURN');

    const slots: Array<{ id: string; days: string; time: string; direction: string }> = [];

    // Add outbound slots
    outboundSchedules.forEach(schedule => {
      slots.push({
        id: schedule.tripId,
        days: schedule.day,
        time: schedule.departureTime,
        direction: 'OUTBOUND'
      });
    });

    // Add return slots
    returnSchedules.forEach(schedule => {
      slots.push({
        id: schedule.tripId,
        days: schedule.day,
        time: schedule.departureTime,
        direction: 'RETURN'
      });
    });

    return slots.length > 0 ? slots : timeSlots; // Fall back if empty
  }, [displaySchedules]);

  // Process trips data for passenger information
  const processedPassengers = React.useMemo(() => {
    if (displayTrips.length === 0) {
      return passengers; // Fall back to mock data
    }

    // Convert trips data to passenger format
    return displayTrips.map(trip => ({
      name: trip.driver || 'Driver',
      schedule: `${trip.title}`,
      phone: 'N/A', // This data might not be available in trips
      route: trip.establishment || 'N/A',
      times: processedTimeSlots.map(slot => {
        // Find corresponding schedule for this trip and time slot
        const schedule = displaySchedules.find(s =>
          s.tripId === trip.id &&
          s.day === slot.days
        );
        return schedule ? `${schedule.departureTime} - ${schedule.arrivalTime}` : '-';
      }),
      observation: `${trip.distance}km, ${trip.duration}min, ${trip.passengerCount} passagers`
    }));
  }, [displayTrips, displaySchedules, processedTimeSlots]);

  // Create summary rows based on real data
  const processedSummaryRows = React.useMemo(() => {
    if (displayTrips.length === 0) {
      return summaryRows; // Fall back to mock data
    }

    return [
      {
        icon: faClock,
        label: 'Durée totale',
        values: processedTimeSlots.map(() => {
          const totalDuration = displayTrips.reduce((sum, trip) => sum + (trip.duration || 0), 0);
          return `${totalDuration}min`;
        }),
        total: `${displayTrips.reduce((sum, trip) => sum + (trip.duration || 0), 0)}min`
      },
      {
        icon: '/assets/icons/menu/ic_exploitation.svg',
        label: 'Distance totale',
        values: processedTimeSlots.map(() => {
          const totalDistance = displayTrips.reduce((sum, trip) => sum + (trip.distance || 0), 0);
          return `${totalDistance}km`;
        }),
        total: `${displayTrips.reduce((sum, trip) => sum + (trip.distance || 0), 0)}km`
      },
      {
        icon: faAddressCard,
        label: 'Passagers totaux',
        values: processedTimeSlots.map(() => {
          const totalPassengers = displayTrips.reduce((sum, trip) => sum + (trip.passengerCount || 0), 0);
          return totalPassengers.toString();
        }),
        total: displayTrips.reduce((sum, trip) => sum + (trip.passengerCount || 0), 0).toString()
      }
    ];
  }, [displayTrips, processedTimeSlots]);

  return (
    <StyledTableContainer>
      <Table stickyHeader sx={{ mt: 1, minWidth: 960 }}>
        <TableHead>
          <StyledTableRow>
            <HeaderCell className="date-cell" rowSpan={2}>
              Date : {new Date().toLocaleDateString('fr-FR')}
            </HeaderCell>
            <HeaderCell colSpan={Math.ceil(processedTimeSlots.length / 2)}>Aller</HeaderCell>
            <HeaderCell colSpan={Math.floor(processedTimeSlots.length / 2)}>Retour</HeaderCell>
            <HeaderCell className="observations-cell" rowSpan={2}>
              Observations
            </HeaderCell>
          </StyledTableRow>
          <TableRow>
            {processedTimeSlots.map((slot, index) => (
              <SousHeaderCell key={index}>
                <Link
                  href={`${paths.dashboard.exploitation.circuitUsager.trajet}?id=${slot.id}`}
                >
                  <Typography
                    component="a"
                    sx={{
                      color: 'primary.main',
                    }}
                  >
                    {slot.id}
                  </Typography>
                </Link>
                <Box>{`${slot.days} ${slot.time}`}</Box>
              </SousHeaderCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {processedPassengers.map((passenger, index) => (
            <TrajetStyledRow key={index}>
              <PassengerCell>
                <Box>
                  <FontAwesome
                    icon={faAddressCard}
                    color="primary.main"
                    width={15}
                    sx={{ mr: 1 }}
                  />
                  {passenger.name}
                </Box>
                <Box>
                  <FontAwesome icon={faClock} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {passenger.schedule}
                </Box>
                <Box>
                  <FontAwesome icon={faPhone} color="primary.main" width={15} sx={{ mr: 1 }} />
                  {passenger.phone}
                </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.route}
                </Box>
              </PassengerCell>
              {passenger.times.map((time, timeIndex) => (
                <DataCell key={timeIndex}>{time}</DataCell>
              ))}
              <StyledTableCell>{passenger.observation}</StyledTableCell>
            </TrajetStyledRow>
          ))}
          {processedSummaryRows.map((row, index) => (
            <TrajetStyledRow key={index}>
              <StyledTableCell sx={{ fontWeight: 500 }}>
                {typeof row.icon === 'string' ? (
                  <Box
                    component="img"
                    src={row.icon}
                    sx={{
                      width: 15,
                      height: 15,
                      color: 'primary.main',
                      mr: 1,
                      pt: 0.5,
                      display: 'inline-flex',
                    }}
                  />
                ) : (
                  <FontAwesome icon={row.icon} color="primary.main" width={15} sx={{ mr: 1 }} />
                )}
                {row.label}
              </StyledTableCell>
              {row.values.map((value, valueIndex) => (
                <DataCell key={valueIndex}>{value}</DataCell>
              ))}
              <StyledTableCell>{row.total}</StyledTableCell>
            </TrajetStyledRow>
          ))}
        </TableBody>
      </Table>
    </StyledTableContainer>
  );
}
