"use client";
import { Mission, MissionAlertLog, MissionLog, Prisma, 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="flex items-center gap-2 text-left text-2xl font-semibold">
					<NotebookText className="h-5 w-5" /> Einsatzhistorie
				</p>
			</div>
			<div className="card bg-base-200 col-span-6 mb-4 shadow-xl">
				<PaginatedTable
					prismaModel={"missionOnStationUsers"}
					getFilter={() =>
						({
							userId: session.data?.user?.id ?? "",
							Mission: {
								state: "finished",
							},
						}) as Prisma.MissionOnStationUsersWhereInput
					}
					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;
