import React, { MouseEvent } from "react";
import { ArrowsCirclepathIcon, TrashIcon } from "@navikt/aksel-icons";
import { Button } from "../../../button";
import { Loader } from "../../../loader";
import { Spacer } from "../../../primitives/stack";
import type { TFunction } from "../../../utils/i18n/i18n.types";

interface ItemActionFieldProps {
  isLoading: boolean;
  button?:
    | {
        action: "delete" | "retry";
        onClick: (event: MouseEvent<HTMLButtonElement>) => void;
        id?: string;
      }
    | React.ReactNode;
  translate: TFunction<"FileUpload">;
}

function ItemActionField({
  isLoading,
  button,
  translate,
}: ItemActionFieldProps) {
  if (isLoading) {
    return (
      <>
        <Spacer />
        <div className="aksel-file-item__icon--loading">
          <Loader size="medium" />
        </div>
      </>
    );
  }

  if (!button) {
    return null;
  }

  if (isCustomButton(button)) {
    return (
      <>
        <Spacer />
        {button}
      </>
    );
  }

  const Icon = button.action === "delete" ? TrashIcon : ArrowsCirclepathIcon;

  return (
    <>
      <Spacer />
      <Button
        id={button.id}
        className="aksel-file-item__button"
        type="button"
        variant="tertiary-neutral"
        onClick={button.onClick}
        icon={
          <Icon
            title={translate(
              button.action === "retry"
                ? "item.retryButtonTitle"
                : "item.deleteButtonTitle",
            )}
          />
        }
      />
    </>
  );
}

function isCustomButton(
  button:
    | {
        action: "delete" | "retry";
        onClick: (event: MouseEvent<HTMLButtonElement>) => void;
        id?: string;
      }
    | React.ReactNode,
): button is React.ReactNode {
  return React.isValidElement(button);
}

export { ItemActionField };
