import * as React from "react";
import { useTranslation } from "react-i18next";
import { PauseIcon, PlayIcon } from "@patternfly/react-icons";
import {
  K8sResourceKind,
  useK8sWatchResource,
  Action,
  K8sResourceCommon,
} from "@openshift-console/dynamic-plugin-sdk";
import { pauseNamespace, unpauseNamespace } from "../utils/namespace-utils";
import { PauseButton } from './PauseButton';

const RESOURCE_LIMITS_ANNOTATION = "devns.openshift.io/resource-limits";

type NamespaceActionProps = {
  namespace: string;
  onClick: () => void;
  isPaused: boolean;
  isDisabled?: boolean;
};

const NamespaceAction: React.FC<NamespaceActionProps> = ({
  namespace,
  onClick,
  isPaused,
  isDisabled,
}) => {
  const { t } = useTranslation();

  return (
    <button
      onClick={onClick}
      disabled={isDisabled}
      className="pf-c-dropdown__menu-item"
      data-test-action={isPaused ? "unpause-namespace" : "pause-namespace"}
    >
      <span className="pf-c-dropdown__menu-item-icon">
        {isPaused ? <PlayIcon /> : <PauseIcon />}
      </span>
      {isPaused ? t("Unpause namespace") : t("Pause namespace")}
    </button>
  );
};

export const useNamespacePauseAction = (namespace: string): Action => {
  const [isLoading, setIsLoading] = React.useState<boolean>(false);

  const [nsResource] = useK8sWatchResource<K8sResourceKind>({
    groupVersionKind: {
      group: "",
      version: "v1",
      kind: "Namespace",
    },
    name: namespace,
  });

  const isPaused = React.useMemo(() => {
    return !!nsResource?.metadata?.annotations?.[RESOURCE_LIMITS_ANNOTATION];
  }, [nsResource]);

  const handleClick = React.useCallback(async () => {
    if (!namespace) return;

    try {
      setIsLoading(true);
      if (isPaused) {
        await unpauseNamespace(namespace);
      } else {
        await pauseNamespace(namespace);
      }
    } catch (error) {
      console.error("Failed to toggle namespace pause state:", error);
    } finally {
      setIsLoading(false);
    }
  }, [namespace, isPaused]);

  return React.useMemo(
    () => ({
      id: "namespace-pause-action",
      label: isPaused ? "Unpause namespace" : "Pause namespace",
      cta: () => {
        handleClick();
      },
      disabled: isLoading || !namespace,
      icon: isPaused ? PlayIcon : PauseIcon,
    }),
    [handleClick, isPaused, isLoading, namespace]
  );
};

type NamespacePauseActionProps = {
  resource: K8sResourceCommon;
};

export const NamespacePauseAction: React.FC<NamespacePauseActionProps> = ({ resource }) => {
  const { t } = useTranslation('plugin__project-pause-plugin');
  
  return (
    <PauseButton 
      namespace={resource.metadata.name} 
      label={t('Pause Project')}
    />
  );
};

export default NamespaceAction;
