"use client";
import { Mission, MissionAlertLog, MissionLog, Station } from "@repo/db";
import { ColumnDef } from "@tanstack/react-table";
import { Error } from "_components/Error";
import { PaginatedTable } from "_components/PaginatedTable";
import { NotebookText } from "lucide-react";
import { useSession } from "next-auth/react";

const Page = () => {
	const session = useSession();

	if (!session) return <Error title="Nicht eingelogt" statusCode={401} />;

	return (
		<div className="grid grid-cols-6 gap-4">
			<div className="col-span-full">
				<p className="text-2xl font-semibold text-left flex items-center gap-2">
					<NotebookText className="w-5 h-5" /> Logbook
				</p>
			</div>
			<div className="card bg-base-200 shadow-xl mb-4 col-span-6">
				<PaginatedTable
					prismaModel={"missionOnStationUsers"}
					filter={{
						userId: session.data?.user?.id ?? "",
						Mission: {
							state: "finished",
						},
					}}
					include={{
						Station: true,
						User: true,
						Mission: true,
					}}
					columns={
						[
							{
								header: "Station",
								accessorKey: "Station.name",
								cell: ({ row }) => row.original.Station.bosCallsign,
							},
							{
								header: "Stichwort",
								accessorKey: "Mission.name",
								cell: ({ row }) =>
									`${row.original.Mission.missionKeywordCategory} / ${row.original.Mission.missionKeywordName}`,
							},

							{
								header: "Datum",
								accessorKey: "createdAt",
								cell: ({ row }) => new Date(row.original.Mission.createdAt).toLocaleDateString(),
							},
							{
								header: "Einsatzlänge",
								cell: ({ row }) => {
									const missionStartLogs = row.original.Mission.missionLog.filter(
										(log) => (log as unknown as MissionLog).type === "alert-log",
									) as unknown as MissionAlertLog[] | undefined;
									// Find the first log with a station ID that matches the current row's station ID or use the first log if none match
									const missionStartLog =
										missionStartLogs?.find(
											(log) => log.data.station?.id === row.original.Station.id,
										) || missionStartLogs?.[0];

									const missionEndLog = row.original.Mission.missionLog.find(
										(log) => (log as unknown as MissionLog).type === "completed-log",
									) as unknown as MissionAlertLog | undefined;

									if (!missionStartLog) return "Unbekannt";
									if (!missionEndLog) return "Unbekannt";

									const start = new Date(missionStartLog.timeStamp);
									const end = new Date(missionEndLog?.timeStamp);
									const duration = Math.round((end.getTime() - start.getTime()) / 1000 / 60); // in minutes
									return `${duration} Minuten`;
								},
							},
						] as ColumnDef<{
							Station: Station;
							Mission: Mission;
						}>[]
					}
				/>
			</div>
		</div>
	);
};

export default Page;
