"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import {
	BADGES,
	ConnectedAircraft,
	ConnectedDispatcher,
	PERMISSION,
	Report,
	Station,
	User,
} from "@repo/db";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { deleteDispoHistory, deletePilotHistory, editUser, resetPassword } from "../../action";
import { toast } from "react-hot-toast";
import {
	PersonIcon,
	EnvelopeClosedIcon,
	BookmarkIcon,
	MixerHorizontalIcon,
	LightningBoltIcon,
	LockOpen1Icon,
	HobbyKnifeIcon,
	ExclamationTriangleIcon,
} from "@radix-ui/react-icons";
import { Button } from "../../../../../_components/ui/Button";
import { Select } from "../../../../../_components/ui/Select";
import { UserOptionalDefaults, UserOptionalDefaultsSchema } from "@repo/db/zod";
import { useRouter } from "next/navigation";
import { PaginatedTable, PaginatedTableRef } from "_components/PaginatedTable";
import { cn } from "../../../../../../helper/cn";
import { ChartBarBigIcon, Check, Eye, PlaneIcon, Timer, X } from "lucide-react";
import Link from "next/link";
import { ColumnDef } from "@tanstack/react-table";
import { Error } from "_components/Error";
import { useSession } from "next-auth/react";

interface ProfileFormProps {
	user: User;
}

export const ProfileForm: React.FC<ProfileFormProps> = ({ user }: ProfileFormProps) => {
	const [isLoading, setIsLoading] = useState(false);
	const session = useSession();
	const form = useForm<UserOptionalDefaults>({
		defaultValues: user,
		resolver: zodResolver(UserOptionalDefaultsSchema),
	});
	if (!user) return <Error title="User not found" statusCode={404} />;
	return (
		<form
			className="card-body"
			onSubmit={form.handleSubmit(async (values) => {
				setIsLoading(true);
				if (!values.id) return;
				await editUser(values.id, values);
				form.reset(values);
				setIsLoading(false);
				toast.success("Deine Änderungen wurden gespeichert!", {
					style: {
						background: "var(--color-base-100)",
						color: "var(--color-base-content)",
					},
				});
			})}
		>
			<h2 className="card-title">
				<MixerHorizontalIcon className="w-5 h-5" /> User bearbeiten
			</h2>
			<div className="text-left">
				<label className="floating-label w-full mb-5 mt-5">
					<span className="text-lg flex items-center gap-2">
						<PersonIcon /> Vorname
					</span>
					<input
						{...form.register("firstname")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={user?.firstname}
						placeholder="Vorname"
					/>
				</label>
				{form.formState.errors.firstname && (
					<p className="text-error">{form.formState.errors.firstname.message}</p>
				)}
				<label className="floating-label w-full mb-5">
					<span className="text-lg flex items-center gap-2">
						<PersonIcon /> Nachname
					</span>
					<input
						{...form.register("lastname")}
						type="text"
						className="input input-bordered w-full"
						defaultValue={user?.lastname}
						placeholder="Nachname"
					/>
				</label>
				{form.formState.errors.lastname && (
					<p className="text-error">{form.formState.errors.lastname?.message}</p>
				)}
				<label className="floating-label w-full">
					<span className="text-lg flex items-center gap-2">
						<EnvelopeClosedIcon /> E-Mail
					</span>
					<input
						{...form.register("email")}
						type="text"
						className="input input-bordered w-full mb-2"
						defaultValue={user?.email}
						placeholder="E-Mail"
					/>
				</label>
				{form.formState.errors.email && (
					<p className="text-error">{form.formState.errors.email?.message}</p>
				)}

				<label className="label">
					<input type="checkbox" {...form.register("emailVerified")} className="checkbox" />
					Email bestätigt
				</label>
				<Select
					isMulti
					form={form}
					name="badges"
					label="Badges"
					options={Object.entries(BADGES).map(([key, value]) => ({
						label: value,
						value: key,
					}))}
				/>
				<Select
					isMulti
					form={form}
					name="permissions"
					label="Permissions"
					isDisabled={user.permissions.length > (session.data?.user?.permissions?.length ?? 0)}
					options={Object.entries(PERMISSION).map(([key, value]) => ({
						label: value,
						value: key,
					}))}
				/>
				<div className="card-actions justify-center pt-6">
					<Button
						role="submit"
						className="btn-sm btn-wide btn-outline btn-primary"
						disabled={!form.formState.isDirty}
						isLoading={isLoading}
					>
						<BookmarkIcon /> Speichern
					</Button>
				</div>
			</div>
		</form>
	);
};

export const ConnectionHistory: React.FC<{ user: User }> = ({ user }: { user: User }) => {
	const dispoTableRef = useRef<PaginatedTableRef>(null);
	return (
		<div className="card-body flex-row flex-wrap">
			<div className="flex-1">
				<h2 className="card-title">
					<MixerHorizontalIcon className="w-5 h-5" /> Dispo-Verbindungs Historie
					<button
						onClick={() => {
							dispoTableRef.current?.refresh();
						}}
					>
						refresh
					</button>
				</h2>
				<PaginatedTable
					ref={dispoTableRef}
					filter={{
						userId: user.id,
					}}
					prismaModel={"connectedDispatcher"}
					columns={
						[
							{
								accessorKey: "loginTime",
								header: "Login",
								cell: ({ row }) => {
									return new Date(row.getValue("loginTime")).toLocaleString("de-DE");
								},
							},
							{
								header: "Time Online",
								cell: ({ row }) => {
									if (row.original.logoutTime == null) {
										return <span className="text-success">Online</span>;
									}
									const loginTime = new Date(row.original.loginTime).getTime();
									const logoutTime = new Date(row.original.logoutTime).getTime();

									const timeOnline = logoutTime - loginTime;

									const hours = Math.floor(timeOnline / 1000 / 60 / 60);
									const minutes = Math.floor((timeOnline / 1000 / 60) % 60);

									return (
										<span className={cn(hours > 2 && "text-error")}>
											{hours}h {minutes}min
										</span>
									);
								},
							},
							{
								header: "Aktionen",
								cell: ({ row }) => {
									return (
										<div>
											<button
												className="btn btn-sm btn-error"
												onClick={async () => {
													await deleteDispoHistory(row.original.id);
													dispoTableRef.current?.refresh();
												}}
											>
												löschen
											</button>
										</div>
									);
								},
							},
						] as ColumnDef<ConnectedDispatcher>[]
					}
				/>
			</div>
			<div className="flex-1">
				<h2 className="card-title">
					<PlaneIcon className="w-5 h-5" /> Pilot-Verbindungs Historie
				</h2>
				<PaginatedTable
					ref={dispoTableRef}
					filter={{
						userId: user.id,
					}}
					prismaModel={"connectedAircraft"}
					include={{ Station: true }}
					columns={
						[
							{
								accessorKey: "Station.bosCallsign",
								header: "Station",
								cell: ({ row }) => {
									return (
										<Link className="link link-hover" href={`/admin/station/${row.original.id}`}>
											{row.original.Station.bosCallsign}
										</Link>
									);
								},
							},
							{
								accessorKey: "loginTime",
								header: "Login",
								cell: ({ row }) => {
									return new Date(row.getValue("loginTime")).toLocaleString("de-DE");
								},
							},
							{
								header: "Time Online",
								cell: ({ row }) => {
									if (!row.original.logoutTime) {
										return <span className="text-success">Online</span>;
									}
									const loginTime = new Date(row.original.loginTime).getTime();
									const logoutTime = new Date(row.original.logoutTime).getTime();
									const timeOnline = logoutTime - loginTime;

									const hours = Math.floor(timeOnline / 1000 / 60 / 60);
									const minutes = Math.floor((timeOnline / 1000 / 60) % 60);

									return (
										<span className={cn(hours > 2 && "text-error")}>
											{hours}h {minutes}min
										</span>
									);
								},
							},
							{
								header: "Aktionen",
								cell: ({ row }) => {
									return (
										<div>
											<button
												className="btn btn-sm btn-error"
												onClick={async () => {
													await deletePilotHistory(row.original.id);
													dispoTableRef.current?.refresh();
												}}
											>
												löschen
											</button>
										</div>
									);
								},
							},
						] as ColumnDef<ConnectedAircraft & { Station: Station }>[]
					}
				/>
			</div>
		</div>
	);
};

export const UserReports = ({ user }: { user: User }) => {
	return (
		<div className="card-body">
			<h2 className="card-title">
				<ExclamationTriangleIcon className="w-5 h-5" /> User Reports
			</h2>
			<PaginatedTable
				prismaModel="report"
				filter={{
					reportedUserId: user.id,
				}}
				include={{
					Sender: true,
					Reported: true,
				}}
				columns={
					[
						{
							accessorKey: "reviewed",
							header: "Erledigt",

							cell: ({ row }) => {
								return (
									<div className="text-center">
										{row.getValue("reviewed") ? (
											<Check className="text-green-500 w-5 h-5" />
										) : (
											<X className="text-red-500 w-5 h-5" />
										)}
									</div>
								);
							},
						},
						{
							accessorKey: "Sender",
							header: "Sender",
							cell: ({ row }) => {
								const user = row.getValue("Sender") as User;
								return `${user.firstname} ${user.lastname} (${user.publicId})`;
							},
						},
						{
							accessorKey: "timestamp",
							header: "Time",
							cell: ({ row }) => new Date(row.getValue("timestamp")).toLocaleString(),
						},
						{
							accessorKey: "actions",
							header: "Actions",
							cell: ({ row }) => (
								<Link href={`/admin/report/${row.original.id}`}>
									<button className="btn btn-sm btn-outline btn-info flex items-center gap-2">
										<Eye className="w-4 h-4" /> Anzeigen
									</button>
								</Link>
							),
						},
					] as ColumnDef<Report>[]
				}
			/>
		</div>
	);
};

interface AdminFormProps {
	user: User;
	dispoTime: {
		hours: number;
		minutes: number;
		lastLogin?: Date;
	};
	pilotTime: {
		hours: number;
		minutes: number;
		lastLogin?: Date;
	};
	reports: {
		total: number;
		open: number;
		total60Days: number;
	};
}

export const AdminForm = ({ user, dispoTime, pilotTime, reports }: AdminFormProps) => {
	const router = useRouter();

	return (
		<div className="card-body">
			<h2 className="card-title">
				<LightningBoltIcon className="w-5 h-5" /> Administration
			</h2>
			<div className="text-left">
				<div className="card-actions pt-6">
					<Button
						onClick={async () => {
							const { password } = await resetPassword(user.id);
							toast.success(
								`Neues Passwort
							${password}, es wurde dem Nutzer an die E-Mail gesendet!`,
								{
									style: {
										background: "var(--color-base-100)",
										color: "var(--color-base-content)",
									},
								},
							);
						}}
						className="btn-sm btn-wide btn-outline btn-success"
					>
						<LockOpen1Icon /> Passwort zurücksetzen
					</Button>
					{!user.isBanned && (
						<Button
							onClick={async () => {
								await editUser(user.id, { isBanned: true });
								toast.success("Nutzer wurde gesperrt!", {
									style: {
										background: "var(--color-base-100)",
										color: "var(--color-base-content)",
									},
								});
								router.refresh();
							}}
							role="submit"
							className="btn-sm btn-wide btn-outline btn-error"
						>
							<HobbyKnifeIcon /> User Sperren
						</Button>
					)}
					{user.isBanned && (
						<Button
							onClick={async () => {
								await editUser(user.id, { isBanned: false });
								toast.success("Nutzer wurde entsperrt!", {
									style: {
										background: "var(--color-base-100)",
										color: "var(--color-base-content)",
									},
								});
								router.refresh();
							}}
							role="submit"
							className="btn-sm btn-wide btn-outline btn-warning"
						>
							<HobbyKnifeIcon /> User Entperren
						</Button>
					)}
				</div>
			</div>
			<h2 className="card-title">
				<ChartBarBigIcon className="w-5 h-5" /> Aktivität
			</h2>
			<div className="stats flex">
				<div className="stat">
					<div className="stat-figure text-primary">
						<LightningBoltIcon className="w-8 h-8" />
					</div>
					<div className="stat-value text-primary">
						{dispoTime.hours}h {dispoTime.minutes}min
					</div>
					<div className="stat-title">Dispo Zeit</div>
					<div className="stat-desc text-secondary">
						{dispoTime.lastLogin && new Date(dispoTime.lastLogin).toLocaleString("de-DE")}
					</div>
				</div>
				<div className="stat">
					<div className="stat-figure text-primary">
						<PlaneIcon className="w-8 h-8" />
					</div>
					<div className="stat-value text-primary">
						{pilotTime.hours}h {pilotTime.minutes}min
					</div>
					<div className="stat-title">Pilot Zeit</div>
					<div className="stat-desc text-secondary">
						{pilotTime.lastLogin && new Date(pilotTime.lastLogin).toLocaleString("de-DE")}
					</div>
				</div>
			</div>
			<h2 className="card-title">
				<ExclamationTriangleIcon className="w-5 h-5" /> Reports
			</h2>

			{/* TODO: Report summary Here */}
			<div className="stats flex">
				<div className="stat">
					<div className="stat-figure text-primary">
						<ExclamationTriangleIcon className="w-8 h-8" />
					</div>
					<div className={cn("stat-value text-primary", reports.open && "text-warning")}>
						{reports.open}
					</div>
					<div className="stat-title">Offen</div>
				</div>
				<div className="stat">
					<div className="stat-figure text-primary">
						<Timer className="w-8 h-8" />
					</div>
					<div className="stat-value text-primary">{reports.total60Days}</div>
					<div className="stat-title">in den letzten 60 Tagen</div>
					<div className="stat-desc text-secondary">{reports.total} insgesammt</div>
				</div>
			</div>
		</div>
	);
};
