"use client";
import { LogsIcon } from "lucide-react";
import { PaginatedTable } from "../../../_components/PaginatedTable";
import Link from "next/link";
import { ColumnDef } from "@tanstack/react-table";
import { Log, Prisma, User } from "@repo/db";

export default () => {
	return (
		<>
			<PaginatedTable
				stickyHeaders
				initialOrderBy={[{ id: "timestamp", desc: true }]}
				prismaModel="log"
				showSearch
				include={{
					User: true,
				}}
				getFilter={(searchTerm) =>
					({
						OR: [
							{
								User: {
									firstname: { contains: searchTerm, mode: "insensitive" },
									lastname: { contains: searchTerm, mode: "insensitive" },
									publicId: { contains: searchTerm, mode: "insensitive" },
								},
							},
							{ deviceId: { contains: searchTerm, mode: "insensitive" } },
							{ ip: { contains: searchTerm, mode: "insensitive" } },
						],
					}) as Prisma.LogWhereInput
				}
				columns={
					[
						{
							header: "ID",
							accessorKey: "id",
						},
						{
							header: "Aktion",
							accessorKey: "action",
							cell: ({ row }) => {
								const action = row.original.type;

								if (action !== "PROFILE_CHANGE") {
									return <span className="text-blue-500">{action}</span>;
								} else {
									return (
										<span className="text-yellow-500">{`${row.original.field} von "${row.original.oldValue}" zu "${row.original.newValue}"`}</span>
									);
								}
							},
						},
						{
							header: "IP",
							accessorKey: "ip",
						},
						{
							header: "Browser-ID",
							accessorKey: "deviceId",
						},
						{
							header: "Zeitstempel",
							accessorKey: "timestamp",
							cell: (info) => new Date(info.getValue<string>()).toLocaleString("de-DE"),
						},
						{
							header: "Benutzer",
							accessorKey: "userId",
							cell: ({ row }) => {
								return (
									<Link href={`/admin/user/${row.original.userId}`} className={"link"}>
										{row.original.User
											? `${row.original.User.firstname} ${row.original.User.lastname} - ${row.original.User.publicId}`
											: "Unbekannt"}
									</Link>
								);
							},
						},
					] as ColumnDef<Log & { User: User }>[]
				}
				leftOfSearch={
					<span className="flex items-center gap-2">
						<LogsIcon className="h-5 w-5" /> Account Log
					</span>
				}
			/>
		</>
	);
};
