import React from "react"
import {
    Table,
    TableHead,
    TableBody,
    TableCell,
    Typography,
    Box,
    styled
} from "@mui/material"
import { AmendmentPassengerScheduleDTO, AmendmentTripDTO, PeriodOfDay } from "@/shared/types/ammendment-passenger"
import { SensTrip } from "@/shared/types/passenger"
import { DAY_MAPPING } from "./schedule-table"
import { StyledTableContainer } from "@/shared/theme/css"
import {
    HeaderCellWidthColor,
    HeaderRow,
    StyledFirstRow,
    StyledSecondRow,
    StyledSubTableRow,
    StyledTableRow,
} from "./style"
import { pxToRem } from "@/shared/theme/typography"
import { WEEKDAYS_NOTCHER } from "@/shared/sections/establishment/attendance/utils/attendance-utils"
import FontAwesome from "../fontawesome"
import { faClock } from "@fortawesome/free-solid-svg-icons"

interface TransportScheduleTableProps {
    title: string
    amendmentData?: AmendmentTripDTO
}
const periods = ["All", "Ret"]

const PERIOD_ORDER = {
    [PeriodOfDay.MORNING]: 1,
    [PeriodOfDay.MIDI]: 2,
    [PeriodOfDay.EVENING]: 3,
}

const DataCell = styled(TableCell)(({ theme }) => ({
    padding: theme.spacing(1),
    minHeight: '60px',
}))

export default function TransportScheduleTable({
    title,
    amendmentData,
}: TransportScheduleTableProps) {
    const formatTime = (timeString: string): string => {
        if (!timeString) return "--:--"

        try {
            const timeParts = timeString.split(":")
            if (timeParts.length >= 2) {
                const hours = Number.parseInt(timeParts[0])
                const minutes = timeParts[1]
                return `${hours.toString().padStart(2, "0")}:${minutes}`
            }
            return timeString
        } catch (error) {
            return "--:--"
        }
    }

    const getPeriodLabel = (period: PeriodOfDay): string => {
        switch (period) {
            case PeriodOfDay.MORNING:
                return "Matin"
            case PeriodOfDay.MIDI:
                return "Midi"
            case PeriodOfDay.EVENING:
                return "Soir"
            default:
                return period
        }
    }

    const getSchedulesForDay = (
        day: string,
        weekType: string,
    ): {
        departures: AmendmentPassengerScheduleDTO[]
        returns: AmendmentPassengerScheduleDTO[]
    } => {
        const dayOfWeek = DAY_MAPPING[day]
        const weekData = amendmentData?.passengerScheduleWeeks?.find((week) => week.weekType === weekType)
        if (!weekData || !weekData.amendmentPassengerSchedule) {
            return { departures: [], returns: [] }
        }

        const daySchedules =
            weekData.amendmentPassengerSchedule.filter((schedule) => schedule.dayOfWeek === dayOfWeek)

        const departures = daySchedules
            .filter((schedule) => schedule.sensTrip === SensTrip.DEPARTURE)
            .sort((a, b) => PERIOD_ORDER[a.periodOfDay] - PERIOD_ORDER[b.periodOfDay])

        const returns = daySchedules
            .filter((schedule) => schedule.sensTrip === SensTrip.RETURN)
            .sort((a, b) => PERIOD_ORDER[a.periodOfDay] - PERIOD_ORDER[b.periodOfDay])

        return { departures, returns }
    }

    const renderScheduleCell = (schedules: AmendmentPassengerScheduleDTO[]) => {
        if (schedules.length === 0) {
            return (
                <DataCell sx={{ verticalAlign: 'center' }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '24px' }}>
                        <Typography variant="caption" color="text.secondary">
                            --:--
                        </Typography>
                    </Box>
                </DataCell>
            )
        }

        return (
            <DataCell sx={{ verticalAlign: 'top' }}>
                <Box>
                    {schedules.map((schedule, index) => (
                        <Box
                            key={index}
                            sx={{
                                display: 'flex',
                                alignItems: 'center',
                                mb: index < schedules.length - 1 ? 1 : 0,
                                p: 0.5,
                                backgroundColor: 'action.hover',
                                borderRadius: 1,
                            }}
                        >
                            <FontAwesome icon={faClock} color="primary.main" width={12} sx={{ mr: 1 }} />
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                {formatTime(schedule.scheduledTime)}
                            </Typography>
                            <Typography
                                variant="caption"
                                color="text.secondary"
                                sx={{ ml: 1, fontSize: '0.7rem' }}
                            >
                                ({getPeriodLabel(schedule.periodOfDay)})
                            </Typography>
                        </Box>
                    ))}
                </Box>
            </DataCell>
        )
    }

    return (
        <Box sx={{ mt: 3 }}>
            <Typography
                variant="h6"
                sx={{
                    mb: 2,
                    color: "primary.main",
                    fontWeight: 600,
                }}
            >
                {title}
            </Typography>

            <StyledTableContainer>
                <Table stickyHeader sx={{ mt: 1 }}>
                    <TableHead>
                        <StyledTableRow >

                            <HeaderCellWidthColor sx={{ textAlign: "left", px: 2, fontSize: pxToRem(13) }} applySecondaryColor rowSpan={2}>
                                Semaines
                            </HeaderCellWidthColor>
                            {WEEKDAYS_NOTCHER.map((day) => (
                                <HeaderCellWidthColor sx={{ fontSize: pxToRem(13) }} applySecondaryColor key={day} colSpan={2}>
                                    {day}
                                </HeaderCellWidthColor>
                            ))}
                        </StyledTableRow>
                        <StyledSubTableRow>
                            {WEEKDAYS_NOTCHER.map((day) => (
                                <React.Fragment key={`${day}-subheaders`}>
                                    {periods.map((period) => (
                                        <HeaderCellWidthColor sx={{ fontSize: pxToRem(13), px: "4px" }} applySecondaryColor key={`${day}-${period}`}>
                                            {period}
                                        </HeaderCellWidthColor>
                                    ))}

                                </React.Fragment>
                            ))}
                        </StyledSubTableRow>
                    </TableHead>
                    <TableBody>
                        <StyledFirstRow key="EVEN">
                            <HeaderRow sx={{ fontSize: pxToRem(13), pl: 1, pr: 0 }} highlighted>Semaine Paire</HeaderRow>
                            {WEEKDAYS_NOTCHER.map((day) => {
                                const { departures, returns } = getSchedulesForDay(day, "EVEN")
                                return (
                                    <React.Fragment key={`EVEN-${day}`}>
                                        {renderScheduleCell(departures)}
                                        {renderScheduleCell(returns)}
                                    </React.Fragment>
                                )
                            })}
                        </StyledFirstRow>

                        <StyledSecondRow key="ODD">
                            <HeaderRow sx={{ fontSize: pxToRem(13), pl: 1, pr: 0 }} highlighted>Semaine Impaire</HeaderRow>
                            {WEEKDAYS_NOTCHER.map((day) => {
                                const { departures, returns } = getSchedulesForDay(day, "ODD")
                                return (
                                    <React.Fragment key={`ODD-${day}`}>
                                        {renderScheduleCell(departures)}
                                        {renderScheduleCell(returns)}
                                    </React.Fragment>
                                )
                            })}
                        </StyledSecondRow>
                    </TableBody>
                </Table>
            </StyledTableContainer>
        </Box>
    )
}
