"use client";

import React, { useMemo } from "react";
import Feature from "ol/Feature";

import SCADADataPanel from "@components/olmap/SCADA/SCADADataPanel";
import { inferHistoryFeatureInfos } from "./toolbarFeatureHelpers";
import HistoryDataPanel from "./HistoryDataPanel";

type ToolbarHistoryPanelProps = {
  showHistoryPanel: boolean;
  chatPanelType: "realtime" | "scheme" | "none";
  chatPanelFeatureInfos: [string, string][] | null;
  chatPanelTimeRange: {
    startTime?: string;
    endTime?: string;
  } | null;
  highlightFeatures: Feature[];
  HistoryPanel?: React.ComponentType<any>;
  schemeName?: string;
  queryType?: string;
  onClose: () => void;
};

const ToolbarHistoryPanel: React.FC<ToolbarHistoryPanelProps> = ({
  showHistoryPanel,
  chatPanelType,
  chatPanelFeatureInfos,
  chatPanelTimeRange,
  highlightFeatures,
  HistoryPanel,
  schemeName,
  queryType,
  onClose,
}) => {
  const featureInfos = useMemo(
    () => chatPanelFeatureInfos ?? inferHistoryFeatureInfos(highlightFeatures),
    [chatPanelFeatureInfos, highlightFeatures],
  );

  if (!showHistoryPanel) {
    return null;
  }

  if (chatPanelType === "none" && chatPanelFeatureInfos) {
    return (
      <SCADADataPanel
        deviceIds={chatPanelFeatureInfos.map(([id]) => id)}
        visible={showHistoryPanel}
        start_time={chatPanelTimeRange?.startTime}
        end_time={chatPanelTimeRange?.endTime}
        onClose={onClose}
      />
    );
  }

  if (HistoryPanel) {
    return (
      <HistoryPanel
        featureInfos={featureInfos}
        scheme_type="burst_analysis"
        scheme_name={schemeName}
        type={
          chatPanelFeatureInfos
            ? chatPanelType
            : (queryType as "realtime" | "scheme" | "none")
        }
        start_time={chatPanelTimeRange?.startTime}
        end_time={chatPanelTimeRange?.endTime}
        onClose={onClose}
      />
    );
  }

  return (
    <HistoryDataPanel
      featureInfos={featureInfos}
      scheme_type="burst_analysis"
      scheme_name={schemeName}
      type={
        chatPanelFeatureInfos
          ? chatPanelType
          : (queryType as "realtime" | "scheme" | "none")
      }
      start_time={chatPanelTimeRange?.startTime}
      end_time={chatPanelTimeRange?.endTime}
      onClose={onClose}
    />
  );
};

export default ToolbarHistoryPanel;
