"use client";
import React, { useState } from "react";
import { FMS_STATUS_COLORS, FMS_STATUS_TEXT_COLORS } from "_helpers/fmsStatusColors";
import {
	ConnectedAircraft,
	getPublicUser,
	Mission,
	MissionLog,
	MissionSdsLog,
	MissionStationLog,
	Prisma,
	PublicUser,
	Station,
} from "@repo/db";
import { toast } from "react-hot-toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { editConnectedAircraftAPI } from "_querys/aircrafts";
import { useDispatchConnectionStore } from "_store/dispatch/connectionStore";
import { cn } from "_helpers/cn";
import { PersonIcon } from "@radix-ui/react-icons";
import {
	Ban,
	BellRing,
	CircleGaugeIcon,
	Clock,
	CompassIcon,
	Component,
	GaugeIcon,
	Hash,
	ListCollapse,
	LocateFixed,
	Lollipop,
	MapPin,
	Mountain,
	Navigation,
	Plus,
	RadioTower,
	Sunset,
	TextSearch,
} from "lucide-react";
import { useSession } from "next-auth/react";
import { editMissionAPI, sendSdsMessageAPI } from "_querys/missions";

const FMSStatusHistory = ({
	aircraft,
	mission,
}: {
	aircraft: ConnectedAircraft & { Station: Station };
	mission?: Mission;
}) => {
	const log = ((mission?.missionLog as unknown as MissionLog[]) || [])
		.filter((entry) => entry.type === "station-log" && entry.data.stationId === aircraft.Station.id)
		.reverse()
		.splice(0, 6) as MissionStationLog[];

	const aircraftUser: PublicUser =
		typeof aircraft.publicUser === "string" ? JSON.parse(aircraft.publicUser) : aircraft.publicUser;

	return (
		<div className="p-4">
			<ul className="text-base-content font-semibold">
				<li className="flex items-center gap-2 mb-1">
					<p className="flex items-center gap-2 flex-1">
						<PersonIcon className="w-5 h-5" /> {aircraftUser.fullName} ({aircraftUser.publicId})
					</p>
					<p className="text-sm font-thin text-gray-500">
						{aircraft.esimatedLogoutTime
							? `Geplante Abmeldung: ${new Date(aircraft.esimatedLogoutTime).toLocaleTimeString(
									[],
									{
										hour: "2-digit",
										minute: "2-digit",
									},
								)}`
							: "Keine geplante Abmeldung"}
					</p>
				</li>
			</ul>
			<div className="divider mt-0 mb-0" />
			<ul className="space-y-2">
				{log.map((entry, index) => (
					<li key={index} className="flex items-center gap-2">
						<span
							className="font-bold text-base"
							style={{
								color: FMS_STATUS_TEXT_COLORS[entry.data.newFMSstatus],
							}}
						>
							{entry.data.newFMSstatus}
						</span>
						<span className="text-base-content">
							{new Date(entry.timeStamp).toLocaleTimeString([], {
								hour: "2-digit",
								minute: "2-digit",
							})}
						</span>
					</li>
				))}
			</ul>
		</div>
	);
};

const FMSStatusSelector = ({
	aircraft,
}: {
	aircraft: ConnectedAircraft & { Station: Station };
}) => {
	const dispatcherConnected = useDispatchConnectionStore((s) => s.status) === "connected";
	const [hoveredStatus, setHoveredStatus] = useState<string | null>(null);
	const queryClient = useQueryClient();
	const changeAircraftMutation = useMutation({
		mutationFn: async ({
			id,
			update,
		}: {
			id: number;
			update: Prisma.ConnectedAircraftUpdateInput;
		}) => {
			await editConnectedAircraftAPI(id, update);
			queryClient.invalidateQueries({
				queryKey: ["aircrafts"],
			});
		},
	});

	return (
		<div className="flex flex-col gap-2 mt-2 p-4 text-base-content">
			<div className="flex gap-2 justify-center items-center h-full">
				{Array.from({ length: 9 }, (_, i) => (i + 1).toString())
					.filter((status) => status !== "5") // Exclude status 5
					.map((status) => (
						<button
							disabled={!dispatcherConnected}
							key={status}
							className={cn(
								"flex justify-center items-center min-w-13 min-h-13 cursor-pointer text-4xl font-bold",
								!dispatcherConnected && "cursor-not-allowed",
							)}
							style={{
								backgroundColor:
									hoveredStatus === status
										? FMS_STATUS_COLORS[status]
										: aircraft.fmsStatus === status
											? FMS_STATUS_COLORS[status]
											: "var(--color-base-200)",
								color:
									aircraft.fmsStatus === status
										? "white"
										: hoveredStatus === status
											? "white"
											: "gray",
							}}
							onMouseEnter={() => setHoveredStatus(status)}
							onMouseLeave={() => setHoveredStatus(null)}
							onClick={async () => {
								await changeAircraftMutation.mutateAsync({
									id: aircraft.id,
									update: {
										fmsStatus: status,
									},
								});
								toast.success(`Status changed to ${status}`);
							}}
						>
							{status}
						</button>
					))}
			</div>
			<div className="flex gap-1 p-2 justify-center items-center">
				{["E", "C", "F", "J", "L", "c", "d", "h", "o", "u"].map((status) => (
					<button
						disabled={!dispatcherConnected}
						key={status}
						className={cn(
							"flex justify-center items-center min-w-10 min-h-10 cursor-pointer text-lg font-bold",
							!dispatcherConnected && "cursor-not-allowed",
						)}
						style={{
							backgroundColor:
								hoveredStatus === status
									? FMS_STATUS_COLORS[6]
									: aircraft.fmsStatus === status
										? FMS_STATUS_COLORS[status]
										: "var(--color-base-200)",
							color:
								aircraft.fmsStatus === status
									? "white"
									: hoveredStatus === status
										? "white"
										: "gray",
						}}
						onMouseEnter={() => setHoveredStatus(status)}
						onMouseLeave={() => setHoveredStatus(null)}
						onClick={async () => {
							await changeAircraftMutation.mutateAsync({
								id: aircraft.id,
								update: {
									fmsStatus: status,
								},
							});
							toast.success(`Status changed to ${status}`);
						}}
					>
						{status}
					</button>
				))}
			</div>
		</div>
	);
};

const RettungsmittelTab = ({
	aircraft,
}: {
	aircraft: ConnectedAircraft & { Station: Station };
}) => {
	const station = aircraft.Station;
	return (
		<div className="p-4 text-base-content">
			<ul className="text-base-content font-semibold">
				<li className="flex items-center gap-2 mb-1">
					<Component size={16} /> Aktuelle Rufgruppe: LST_01
				</li>
				<li className="flex items-center gap-2 mb-1">
					<RadioTower size={16} /> Leitstellenbereich: Florian Berlin
				</li>
			</ul>
			<div className="divider mt-0 mb-0" />
			<div className="flex items-center text-sm font-semibold justify-between pr-2 mt-2 mb-2">
				<span className="flex items-center gap-2">
					<Clock size={16} /> {station.is24h ? "24h Betrieb" : "Tagbetrieb"}
				</span>
				<span className="flex items-center gap-2">
					<Sunset size={16} /> NVG: {station.hasNvg ? "Ja" : "Nein"}
				</span>
				<span className="flex items-center gap-2">
					<Mountain size={16} /> Winch: {station.hasWinch ? "Ja" : "Nein"}
				</span>
				<span className="flex items-center gap-2">
					<TextSearch size={16} /> {station.aircraftRegistration}
				</span>
			</div>
			<div className="divider mt-0 mb-0" />
			<div className="flex items-center text-sm font-semibold justify-between pr-2 mt-2">
				<span className="flex items-center gap-2">
					<CompassIcon size={16} /> HDG: {aircraft.posHeading}°
				</span>
				<span className="flex items-center gap-2">
					<GaugeIcon size={16} /> SPD: {aircraft.posSpeed} kt
				</span>
				<span className="flex items-center gap-2">
					<CircleGaugeIcon size={16} /> ALT: {aircraft.posAlt} ft
				</span>
			</div>
			<div className="flex items-center text-sm font-semibold justify-between pr-2 mt-2">
				<span className="flex items-center gap-2">
					<Lollipop size={16} />{" "}
					<span className={cn(aircraft.posH145active && "text-green-500")}>
						{aircraft.posH145active ? "H145 Aktiv" : "H145 Inaktiv"}
					</span>
				</span>
			</div>
		</div>
	);
};

const MissionTab = ({ mission }: { mission: Mission }) => {
	return (
		<div className="p-4 text-base-content">
			<ul className="text-base-content font-semibold">
				<li className="flex items-center gap-2 mb-1">
					<BellRing size={16} /> {mission.missionKeywordCategory}
				</li>
				<li className="flex items-center gap-2 mb-1">
					<ListCollapse size={16} />
					{mission.missionKeywordName}
				</li>
				<li className="flex items-center gap-2 mt-3">
					<Hash size={16} />
					__{new Date().toISOString().slice(0, 10).replace(/-/g, "")}
					{mission.id}
				</li>
			</ul>
			<div className="divider mt-0 mb-0" />
			<div className="text-sm font-semibold">
				<p className="flex items-center gap-2">
					<MapPin size={16} /> {mission.addressLat} {mission.addressLng}
				</p>
				<p className="flex items-center gap-2">
					<Navigation size={16} /> {mission.addressStreet}
				</p>
				<p className="flex items-center gap-2">
					<LocateFixed size={16} /> {mission.addressZip} {mission.addressCity}
				</p>
			</div>
		</div>
	);
};

const SDSTab = ({
	aircraft,
	mission,
}: {
	aircraft: ConnectedAircraft & {
		Station: Station;
	};
	mission?: Mission;
}) => {
	const session = useSession();
	const [isChatOpen, setIsChatOpen] = useState(false);
	const [note, setNote] = useState("");
	const queryClient = useQueryClient();

	const dispatcherConnected = useDispatchConnectionStore((s) => s.status) === "connected";

	const sendSdsMutation = useMutation({
		mutationFn: async ({
			missionId,
			sdsMessage,
		}: {
			missionId?: number;
			sdsMessage: MissionSdsLog;
		}) => {
			await sendSdsMessageAPI({ missionId, sdsMessage });
			queryClient.invalidateQueries({
				queryKey: ["missions"],
			});
		},
	});

	const log =
		(mission?.missionLog as unknown as MissionLog[])
			?.slice()
			.reverse()
			.filter(
				(entry) => entry.type === "sds-log" && entry.data.stationId === aircraft.Station.id,
			) || [];

	return (
		<div className="p-4">
			{dispatcherConnected && (
				<div>
					<div className="flex items-center gap-2">
						{!isChatOpen ? (
							<button
								className="text-base-content text-base cursor-pointer"
								onClick={() => setIsChatOpen(true)}
							>
								<span className="flex items-center gap-2">
									<Plus size={18} /> Notiz hinzufügen
								</span>
							</button>
						) : (
							<div className="flex items-center gap-2 w-full">
								<input
									type="text"
									placeholder=""
									className="input input-sm text-base-content flex-1"
									value={note}
									onChange={(e) => setNote(e.target.value)}
								/>
								<button
									className="btn btn-sm btn-primary btn-outline"
									onClick={() => {
										sendSdsMutation
											.mutateAsync({
												missionId: mission?.id,
												sdsMessage: {
													type: "sds-log",
													auto: false,
													timeStamp: new Date().toISOString(),
													data: {
														stationId: aircraft.Station.id,
														station: aircraft.Station,
														message: note,
														user: getPublicUser(session.data!.user),
													},
												},
											})
											.then(() => {
												setIsChatOpen(false);
												setNote("");
											});
									}}
								>
									<Plus size={20} />
								</button>
								<button
									className="btn btn-sm btn-outline"
									onClick={() => {
										setIsChatOpen(false);
										setNote("");
									}}
								>
									<Ban size={20} />
								</button>
							</div>
						)}
					</div>
					<div className="divider m-0" />
				</div>
			)}
			<ul className="space-y-2 max-h-[300px] overflow-y-auto overflow-x-auto">
				{log.map((entry, index) => {
					const sdsEntry = entry as MissionSdsLog;
					return (
						<li key={index} className="flex items-center gap-2">
							<span className="text-base-content">
								{new Date(sdsEntry.timeStamp).toLocaleTimeString([], {
									hour: "2-digit",
									minute: "2-digit",
								})}
							</span>
							<span
								className="font-bold text-base"
								style={{
									color: FMS_STATUS_TEXT_COLORS[6],
								}}
							>
								{sdsEntry.data.user.firstname?.[0]?.toUpperCase() ?? "?"}
								{sdsEntry.data.user.lastname?.[0]?.toUpperCase() ?? "?"}
							</span>
							<span className="text-base-content">{sdsEntry.data.message}</span>
						</li>
					);
				})}
				{!log.length && (
					<p className="text-gray-500 w-full text-center my-10 font-semibold">
						Kein SDS-Verlauf verfügbar
					</p>
				)}
			</ul>
		</div>
	);
};

export { FMSStatusSelector, RettungsmittelTab, MissionTab, SDSTab };
export default FMSStatusHistory;
