import { Marker, Polyline, useMap } from "react-leaflet";
import { DivIcon, Marker as LMarker, Popup as LPopup } from "leaflet";
import { useMapStore } from "_store/mapStore";
import { Fragment, useCallback, useEffect, useRef, useState, useMemo } from "react";
import { cn } from "_helpers/cn";
import { ChevronsRightLeft, House, MessageSquareText, Minimize2 } from "lucide-react";
import { SmartPopup, calculateAnchor, useSmartPopup } from "_components/SmartPopup";
import FMSStatusHistory, {
	FMSStatusSelector,
	MissionTab,
	RettungsmittelTab,
	SDSTab,
} from "./_components/AircraftMarkerTabs";
import { ConnectedAircraft, Station } from "@repo/db";
import { useQuery } from "@tanstack/react-query";
import { getConnectedAircraftPositionLogAPI, getConnectedAircraftsAPI } from "_querys/aircrafts";
import { getMissionsAPI } from "_querys/missions";
import { checkSimulatorConnected } from "_helpers/simulatorConnected";
import { FMS_STATUS_COLORS, FMS_STATUS_TEXT_COLORS } from "_helpers/fmsStatusColors";

const AircraftPopupContent = ({
	aircraft,
}: {
	aircraft: ConnectedAircraft & { Station: Station };
}) => {
	const setAircraftTab = useMapStore((state) => state.setAircraftTab);
	const currentTab = useMapStore((state) => state.aircraftTabs[aircraft.id] || "home");

	// Memoize the tab change handler to avoid unnecessary re-renders
	const handleTabChange = useCallback(
		(tab: "home" | "fms" | "aircraft" | "mission" | "chat") => {
			if (currentTab !== tab) {
				setAircraftTab(aircraft.id, tab);
			}
		},
		[currentTab, aircraft.id, setAircraftTab],
	);

	const { data: missions } = useQuery({
		queryKey: ["missions", "missions-map"],
		queryFn: () =>
			getMissionsAPI({
				state: "running",
				missionStationIds: {
					has: aircraft.Station.id,
				},
			}),
	});

	const mission = missions && missions[0];

	const renderTabContent = useMemo(() => {
		switch (currentTab) {
			case "home":
				return <FMSStatusHistory aircraft={aircraft} mission={mission} />;
			case "fms":
				return <FMSStatusSelector aircraft={aircraft} />;
			case "aircraft":
				return <RettungsmittelTab aircraft={aircraft} />;
			case "mission":
				return mission ? (
					<MissionTab mission={mission} />
				) : (
					<div className="flex flex-col items-center justify-center min-h-full">
						<span className="text-gray-500 my-10 font-semibold">Kein aktiver Einsatz</span>
					</div>
				);
			case "chat":
				return <SDSTab aircraft={aircraft} mission={mission} />;
			default:
				return <span className="text-gray-100">Error</span>;
		}
	}, [currentTab, aircraft, mission]);

	const setOpenAircraftMarker = useMapStore((state) => state.setOpenAircraftMarker);
	const { anchor } = useSmartPopup();
	return (
		<>
			<div
				className="absolute p-1 z-99 top-0 right-0 transform -translate-y-full bg-base-100 cursor-pointer"
				onClick={() => {
					setOpenAircraftMarker({
						open: [],
						close: [aircraft.id],
					});
				}}
			>
				<Minimize2 className="text-white" size={16} />
			</div>

			<div
				className={cn(
					"absolute w-[calc(100%+2px)] h-4 z-99", // As offset is 2px, we need to add 2px to the width
					anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
					anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
				)}
				style={{
					borderLeft: anchor.includes("left")
						? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
						: "",
					borderRight: anchor.includes("right")
						? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
						: "",
					borderTop: anchor.includes("top")
						? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
						: "",
					borderBottom: anchor.includes("bottom")
						? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
						: "",
				}}
			/>
			<div>
				<div
					className="flex gap-[2px] text-white pb-0.5"
					style={{
						backgroundColor: `${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`,
					}}
				>
					<div
						className="px-3 flex justify-center items-center cursor-pointer"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
							borderBottom:
								currentTab === "home"
									? `5px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
									: "5px solid transparent",
						}}
						onClick={() => handleTabChange("home")}
					>
						<House className="text-sm" />
					</div>
					<div
						className="px-4 flex justify-center items-center cursor-pointer"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
						}}
						/* onClick={() => handleTabChange("fms")} */
					>
						<ChevronsRightLeft className="text-sm" />
					</div>
					<div
						className="flex justify-center items-center text-5xl font-bold px-6 cursor-pointer"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
							borderBottom:
								currentTab === "fms"
									? `5px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
									: "5px solid transparent",
							color: "white",
						}}
						onClick={() => handleTabChange("fms")}
					>
						{aircraft.fmsStatus}
					</div>
					<div
						className="w-100 cursor-pointer px-2"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
							borderBottom:
								currentTab === "aircraft"
									? `5px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
									: "5px solid transparent",
							whiteSpace: "nowrap",
						}}
						onClick={() => handleTabChange("aircraft")}
					>
						<span className="text-white text-base font-medium">
							{aircraft.Station.bosCallsign}
							<br />
							{aircraft.Station.bosUse}
						</span>
					</div>
					<div
						className="w-150 cursor-pointer px-2"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
							borderBottom:
								currentTab === "mission"
									? `5px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
									: "5px solid transparent",
							whiteSpace: "nowrap",
						}}
						onClick={() => handleTabChange("mission")}
					>
						<span className="text-white text-base font-medium">Einsatz</span>
						<br />
						<span className="text-white text-sm font-medium">
							{mission?.publicId || "Kein aktiver Einsatz"}
						</span>
					</div>
					<div
						className="px-4 flex justify-center items-center cursor-pointer"
						style={{
							backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
							borderBottom:
								currentTab === "chat"
									? `5px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
									: "5px solid transparent",
						}}
						onClick={() => handleTabChange("chat")}
					>
						<MessageSquareText className="text-sm" />
					</div>
				</div>
			</div>
			<div className="h-full min-h-[140px]">
				<div className="flex-grow">{renderTabContent}</div>
			</div>
		</>
	);
};

const AircraftMarker = ({ aircraft }: { aircraft: ConnectedAircraft & { Station: Station } }) => {
	const [hideMarker, setHideMarker] = useState(false);
	const map = useMap();
	const markerRef = useRef<LMarker>(null);
	const popupRef = useRef<LPopup>(null);

	const { openAircraftMarker, setOpenAircraftMarker } = useMapStore((store) => store);
	const { data: positionLog } = useQuery({
		queryKey: ["positionlog", aircraft.id],
		queryFn: () =>
			getConnectedAircraftPositionLogAPI({
				id: aircraft.id,
			}),
		refetchInterval: 10000,
	});

	useEffect(() => {
		const handleClick = () => {
			console.log("Marker clicked", aircraft.id);
			const open = openAircraftMarker.some((m) => m.id === aircraft.id);
			if (open) {
				setOpenAircraftMarker({
					open: [],
					close: [aircraft.id],
				});
			} else {
				setOpenAircraftMarker({
					open: [
						{
							id: aircraft.id,
							tab: "home",
						},
					],
					close: [],
				});
			}
		};
		const marker = markerRef.current;
		marker?.on("click", handleClick);
		return () => {
			marker?.off("click", handleClick);
		};
	}, [aircraft.id, openAircraftMarker, setOpenAircraftMarker, markerRef.current]);

	const [anchor, setAnchor] = useState<"topleft" | "topright" | "bottomleft" | "bottomright">(
		"topleft",
	);

	const handleConflict = useCallback(() => {
		const newAnchor = calculateAnchor(`aircraft-${aircraft.id}`, "marker");
		setAnchor(newAnchor);
	}, [aircraft.id]);

	/* useEffect(() => {
		handleConflict();
	}, [aircrafts, openAircraftMarker, handleConflict]); */

	useEffect(() => {
		setTimeout(() => {
			handleZoom();
		}, 100);

		const handleZoom = () => {
			const zoom = map.getZoom();
			setHideMarker(zoom < 8);
			handleConflict();
		};

		map.on("zoomend", handleZoom);
		return () => {
			map.off("zoomend", handleZoom);
		};
	}, [map, openAircraftMarker, handleConflict]);

	const getMarkerHTML = (
		aircraft: ConnectedAircraft & { Station: Station },
		anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
	) => {
		return `<div 
						id="marker-aircraft-${aircraft.id}"
						class="${cn(
							"relative w-auto transform inline-flex items-center gap-2 px-2 z-100",
							anchor.includes("right") && "-translate-x-full",
							anchor.includes("bottom") && "-translate-y-full",
							hideMarker ? "opacity-0 pointer-events-none" : "opacity-100",
						)}"
						style="
							background-color: ${FMS_STATUS_COLORS[aircraft.fmsStatus]};
							${openAircraftMarker.some((m) => m.id === aircraft.id) ? "opacity: 0; pointer-events: none;" : ""}
						">
						
						<div 
							class="${cn(
								"absolute w-4 h-4 z-99",
								anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
								anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
							)}" 
							style="
								${anchor.includes("left") ? `border-left: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-right: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
								${anchor.includes("top") ? `border-top: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-bottom: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
							"
						></div>
						<span 
							class="font-semibold text-xl"
							style="color: ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};"
						>
							${aircraft.fmsStatus}
						</span>
						<span class="text-white text-[15px] text-nowrap">
							${aircraft.Station.bosCallsign}
						</span>
						<div 
							data-id="${aircraft.id}"
							data-anchor-lat="${aircraft.posLat}"
							data-anchor-lng="${aircraft.posLng}"
							id="marker-domain-aircraft-${aircraft.id}" 
							class="${cn(
								"map-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
								anchor.includes("left") && "-translate-x-1/2",
								anchor.includes("top") && "-translate-y-1/2",
							)}"
						></div>
					</div>`;
	};

	if (!aircraft.posLat || !aircraft.posLng) return null;
	return (
		<Fragment key={aircraft.id}>
			<Marker
				ref={markerRef}
				position={[aircraft.posLat, aircraft.posLng]}
				icon={
					new DivIcon({
						iconAnchor: [0, 0],
						html: getMarkerHTML(aircraft, anchor),
					})
				}
			/>
			{openAircraftMarker.some((m) => m.id === aircraft.id) && !hideMarker && (
				<>
					<SmartPopup
						options={{
							ignoreCluster: true,
						}}
						id={`aircraft-${aircraft.id}`}
						ref={popupRef}
						position={[aircraft.posLat!, aircraft.posLng!]}
						autoClose={false}
						closeOnClick={false}
						autoPan={false}
						wrapperClassName="relative"
						className="w-[502px]"
					>
						<div style={{ height: "auto", maxHeight: "90vh", overflowY: "auto" }}>
							<AircraftPopupContent aircraft={aircraft} />
						</div>
					</SmartPopup>
					<Polyline
						pathOptions={{
							color: "var(--color-rescuetrack)",
							weight: 3,
						}}
						positions={positionLog?.map((pos) => [pos.lat, pos.lng]) || []}
					/>
				</>
			)}
		</Fragment>
	);
};

export const AircraftLayer = () => {
	const { data: aircrafts } = useQuery({
		queryKey: ["aircrafts"],
		queryFn: getConnectedAircraftsAPI,
		refetchInterval: 10000,
	});

	return (
		<>
			{aircrafts
				?.filter((a) => checkSimulatorConnected(a.lastHeartbeat))
				?.map((aircraft) => {
					return <AircraftMarker key={aircraft.id} aircraft={aircraft} />;
				})}
		</>
	);
};
