"use client";

import { useCallback, useMemo, useState } from "react";
import MapComponent from "@app/OlMap/MapComponent";
import Timeline from "@app/OlMap/Controls/Timeline";
import SCADADeviceList from "@components/olmap/SCADADeviceList";
import SCADADataPanel from "@components/olmap/SCADADataPanel";

const mockDevices = [
  {
    id: "SCADA-001",
    name: "SCADA-001",
    type: "pressure",
    coordinates: [121.4737, 31.2304] as [number, number],
    status: "online" as const,
  },
  {
    id: "SCADA-002",
    name: "SCADA-002",
    type: "flow",
    coordinates: [121.4807, 31.2204] as [number, number],
    status: "warning" as const,
  },
  {
    id: "SCADA-003",
    name: "SCADA-003",
    type: "pressure",
    coordinates: [121.4607, 31.2354] as [number, number],
    status: "offline" as const,
  },
  {
    id: "SCADA-004",
    name: "SCADA-004",
    type: "demand",
    coordinates: [121.4457, 31.2104] as [number, number],
    status: "online" as const,
  },
  {
    id: "SCADA-005",
    name: "SCADA-005",
    type: "level",
    coordinates: [121.4457, 31.2104] as [number, number],
    status: "online" as const,
  },
];

export default function Home() {
  const [selectedDeviceIds, setSelectedDeviceIds] = useState<string[]>([]);
  const [panelVisible, setPanelVisible] = useState<boolean>(false);

  const devices = useMemo(() => mockDevices, []);

  const deviceLabels = useMemo(
    () =>
      devices.reduce<Record<string, string>>((acc, device) => {
        acc[device.id] = device.name;
        return acc;
      }, {}),
    [devices]
  );

  const handleSelectionChange = useCallback((ids: string[]) => {
    setSelectedDeviceIds(ids);
    setPanelVisible(ids.length > 0);
  }, []);

  const handleDeviceClick = useCallback(() => {
    setPanelVisible(true);
  }, []);

  const handleClosePanel = useCallback(() => {
    setPanelVisible(false);
  }, []);

  return (
    <div className="relative w-full h-full overflow-hidden">
      <MapComponent>
        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10 w-[800px] opacity-90 hover:opacity-100 transition-opacity duration-300">
          <Timeline />
        </div>
      </MapComponent>
      <SCADADeviceList
        devices={devices}
        onDeviceClick={handleDeviceClick}
        onSelectionChange={handleSelectionChange}
        selectedDeviceIds={selectedDeviceIds}
      />
      <SCADADataPanel
        deviceIds={selectedDeviceIds}
        deviceLabels={deviceLabels}
        visible={panelVisible}
        onClose={handleClosePanel}
      />
    </div>
  );
}
