import TimetableRow from "@/components/TimetableRow/TimetableRow";
import type { DepartureType } from "@/types/departureType";

import style from "./style.module.css";

function parseTimetableData(data: DepartureType[]) {
    const left: DepartureType[] = [];
    const right: DepartureType[] = [];

    data.forEach((departure) => {
        if (
            departure.servingLine?.liErgRiProj?.direction === "R" &&
            right.length < 5
        ) {
            right.push(departure);
        } else if (left.length < 5) {
            left.push(departure);
        }

        // Limit to 5 departures per side
        if (left.length >= 5 && right.length >= 5) {
            return;
        }
    });

    return {
        left,
        right,
    };
}

function departureTables(departures: DepartureType[]) {
    return (
        <div className={style.departureTable}>
            <table>
                <tbody>
                    {departures.map((departure, index) => (
                        // biome-ignore lint/suspicious/noArrayIndexKey: there is no id
                        <TimetableRow key={index} departure={departure} />
                    ))}
                </tbody>
            </table>
        </div>
    );
}

export default function DepartureList(props: {
    departures: DepartureType[];
    name: string;
}) {
    const { departures, name } = props;

    if (!departures || departures.length === 0) {
        return <div>No departures available</div>;
    }

    const { left, right } = parseTimetableData(departures);

    return (
        <div className={style.container}>
            <h2>{name} Departures</h2>
            <div className={style.departureLists}>
                {departureTables(left)}
                {departureTables(right)}
            </div>
        </div>
    );
}
