import { Button } from "antd";
import { useState } from "react";
import { MODES } from "../../config";
import { useMode } from "../../stores/useMode";
import { LAYER_IDS } from "../Layers/constants";
import { PopupWrapper } from "./PopupWrapper";
import { InitialPointPopup } from "./mode-popup/InitialPointPopup";
import { ApproveWorkingPointPopup } from "./mode-popup/ApproveWorkingPointPopup";
import { WorkingPointPopup } from "./mode-popup/WorkingPointPopup";

const SingleFeaturePopup = ({ feature }) => {
  const { mode } = useMode();

  if (mode === MODES.APPROVE_WORKING) {
    return <ApproveWorkingPointPopup feature={feature} />;
  }

  if (mode === MODES.WORKING) {
    return <WorkingPointPopup feature={feature} />;
  }

  return <InitialPointPopup feature={feature} />;
};

const MultipleFeaturesPopup = ({ features, onSelect }) => {
  return (
    <div className="space-y-2 p-1">
      {features.map((feature) => {
        return (
          <Button
            type={
              feature.layer.id === LAYER_IDS["initial-match"] ? "primary" : ""
            }
            className="flex items-center gap-x-1"
            block
            onClick={() => onSelect(feature)}
            key={feature.properties.id}
          >
            <span>{feature.properties.id}</span>
            <span>{feature.properties.category}</span>
          </Button>
        );
      })}
    </div>
  );
};

export const MapPopup = ({ features, lat, lng, onClose }) => {
  const [selectedFeature, setSelectedFeature] = useState(null);

  const getContent = () => {
    if (features.length === 1) {
      return <SingleFeaturePopup feature={features[0]} />;
    }

    if (selectedFeature) {
      return <SingleFeaturePopup feature={selectedFeature} />;
    }

    return (
      <MultipleFeaturesPopup
        features={features}
        onSelect={setSelectedFeature}
      />
    );
  };

  return (
    <PopupWrapper lat={lat} lng={lng} onClose={onClose}>
      {getContent()}
    </PopupWrapper>
  );
};
