"use client";
import { useMemo } from "react";

import { useState } from "react";
import useSWR from "swr";

import Sidebar from "@/components/Sidebar";
import Map from "@components/Map";
import { fetcher } from "@utils/axiosHelpers";
import { Observatory } from "@prismaclient";
import { getRelativeDate } from "@utils/formatters";
import GeologicalEvent from "@appTypes/Event";

export default function Observatories() {
	const [selectedEventId, setSelectedEventId] = useState("");
	const [hoveredEventId, setHoveredEventId] = useState("");
	const { data, error, isLoading } = useSWR("/api/observatories", fetcher);

	// todo add in earthquake events
	const observatoryEvents = useMemo(
		() =>
			data && data.observatories
				? data.observatories
						.map(
							(x: Observatory): GeologicalEvent => ({
								id: x.id.toString(),
								title: `New Observatory - ${x.name}`,
								longitude: x.longitude,
								latitude: x.latitude,
								text1: "",
								text2: getRelativeDate(x.dateEstablished),
								date: x.dateEstablished,
							})
						)
						.sort((a: GeologicalEvent, b: GeologicalEvent) => new Date(b.date).getTime() - new Date(a.date).getTime()) // Remove Date conversion
				: [],
		[data]
	);

	return (
		<div className="flex h-[calc(100vh-3.5rem)] w-full overflow-hidden">
			<div className="flex-grow h-full">
				<Map
					events={observatoryEvents}
					selectedEventId={selectedEventId}
					setSelectedEventId={setSelectedEventId}
					hoveredEventId={hoveredEventId}
					setHoveredEventId={setHoveredEventId}
					mapType="observatories"
				/>
			</div>
			<Sidebar
				logTitle="Observatory Mapping"
				logSubtitle="Record and search observatories - time/date set-up, location, scientists and recent earthquakes"
				recentsTitle="Observatory Events"
				events={observatoryEvents}
				selectedEventId={selectedEventId}
				setSelectedEventId={setSelectedEventId}
				hoveredEventId={hoveredEventId}
				setHoveredEventId={setHoveredEventId}
				button1Name="Log a New Observatory"
				button2Name="Search Observatories"
			/>
		</div>
	);
}
