"use client";
import { useState, useMemo } from "react";
import useSWR from "swr";
import Sidebar from "@/components/Sidebar";
import Map from "@components/Map";
import LogObservatoryModal from "@/components/LogObservatoryModal"; // Adjust if your path is different
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 [logModalOpen, setLogModalOpen] = useState(false);

  const { data, error, isLoading, mutate } = useSWR(
    "/api/observatories",
    fetcher
  );

  const observatoryEvents = useMemo(
    () =>
      data && data.observatories
      ? data.observatories
        .map((x: Observatory): GeologicalEvent & { isFunctional: boolean } => ({
            id: x.id.toString(),
            title: ` ${x.name}`,
            longitude: x.longitude,
            latitude: x.latitude,
            isFunctional: x.isFunctional, // <-- include this!
            text1: "",
            text2: getRelativeDate(x.dateEstablished),
            date: x.dateEstablished,
        }))
            .sort(
              (a: GeologicalEvent, b: GeologicalEvent) =>
                new Date(b.date).getTime() - new Date(a.date).getTime()
            )
        : [],
    [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="New Observatories"
        events={observatoryEvents}
        selectedEventId={selectedEventId}
        setSelectedEventId={setSelectedEventId}
        hoveredEventId={hoveredEventId}
        setHoveredEventId={setHoveredEventId}
        button1Name="Log a New Observatory"
        button2Name="Search Observatories"
        onButton1Click={() => setLogModalOpen(true)}
      />
      <LogObservatoryModal
        open={logModalOpen}
        onClose={() => setLogModalOpen(false)}
        onSuccess={() => mutate()}
      />
    </div>
  );
}
