"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import useSWR from "swr";

import Map from "@components/Map";
import Sidebar from "@components/Sidebar";
import { createPoster, fetcher } from "@utils/axiosHelpers";
import { Earthquake } from "@prismaclient";
import { getRelativeDate } from "@utils/formatters";

export default function Earthquakes() {
	const [selectedEventId, setSelectedEventId] = useState("");
	const [hoveredEventId, setHoveredEventId] = useState("");
	// todo properly integrate loading
	const { data, error, isLoading } = useSWR("/api/earthquakes", createPoster({ rangeDaysPrev: 5 }));

	const earthquakeEvents = useMemo(
		() =>
			data && data.earthquakes
				? data.earthquakes.map((x: Earthquake) => ({
						id: x.id,
						// e.g Earthquake in Germany
						title: `Earthquake in ${x.code.split("-")[2]}`,
						magnitude: x.magnitude,
						longitude: x.longitude,
						latitude: x.latitude,
						text2: getRelativeDate(x.date),
				  }))
				: [],
		[data]
	);

	return (
		<div className="h-full flex overflow-hidden">
			<div className="flex-grow">
				<Map
					events={earthquakeEvents}
					selectedEventId={selectedEventId}
					setSelectedEventId={setSelectedEventId}
					hoveredEventId={hoveredEventId}
					setHoveredEventId={setHoveredEventId}
					mapType="Earthquakes"
				></Map>
			</div>
			<Sidebar
				logTitle="Log an Earthquake"
				logSubtitle="Record new earthquakes - time/date, location, magnitude, observatory and scientists"
				recentsTitle="Recent Earthquakes"
				events={earthquakeEvents}
				selectedEventId={selectedEventId}
				setSelectedEventId={setSelectedEventId}
				hoveredEventId={hoveredEventId}
				setHoveredEventId={setHoveredEventId}
				button1Name="Log an Earthquake"
				button2Name="Search Earthquakes"
			></Sidebar>
		</div>
	);
}
