import { groupEventsByLine } from "@/common/utils";
import { EventCard } from "@/components/EventCard";
import { EventList } from "@/components/EventList";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { getAllLines, getEventsForDate } from "@/db";
import { notFound } from "next/navigation";

export default async function ScheduleByDate({
	params,
	searchParams,
}: {
	params: Promise<{
		date: string;
	}>;
	searchParams: Promise<{
		group?: string;
	}>;
}) {
	const { date } = await params;
	const { group = "time" } = await searchParams;
	const parsedDate = new Date(date);
	if (Number.isNaN(parsedDate.getTime())) {
		return notFound();
	}
	const formattedDate = parsedDate.toISOString().split("T")[0]; // Format to 'YYYY-MM-DD'
	const events = await getEventsForDate(formattedDate);
	if (events.length === 0) {
		return notFound();
	}
	const groupedEvents = groupEventsByLine(events);
	const allLines = await getAllLines();
	return (
		<div className="flex flex-col items-center justify-items-center p-8 pb-20 gap-4 sm:p-20 w-full">
			<div className="flex flex-col sm:flex-row justify-between items-center w-full gap-2 mb-4">
				<h1 className="text-3xl font-bold">
					{parsedDate.toLocaleDateString(["cs-CZ"], {
						weekday: "long",
						day: "numeric",
						month: "numeric",
					})}
				</h1>
				<form
					method="GET"
					action={`/date/${formattedDate}`}
					className="flex items-center"
				>
					<Label htmlFor="group" className="mr-2">
						Seskupit podle:
					</Label>
					<Select name="group" defaultValue={group}>
						<SelectTrigger className="w-20">
							<SelectValue placeholder="Vyberte možnost..." />
						</SelectTrigger>
						<SelectContent>
							<SelectItem value="time">Čas</SelectItem>
							<SelectItem value="line">Linie</SelectItem>
						</SelectContent>
					</Select>
					<Button type="submit" className="ml-2">
						Zobrazit
					</Button>
				</form>
			</div>
			<main className="flex flex-col gap-8 items-center">
				{group === "line" &&
					groupedEvents.map((line) => (
						<EventList
							key={line.lineId}
							events={line.events}
							title={allLines.find((l) => l.id === line.lineId)?.name}
						/>
					))}
				{group !== "line" && <EventList events={events} showLine />}
			</main>
		</div>
	);
}
