import {
  AnimateSlideDown,
  Dropdown,
  DropdownItem,
  DropdownSeparator,
  IconLoading,
  location,
  MeatballMenu
} from "@heydovetail/ui-components";
import React from "react";
import { AttachmentService } from "../../AttachmentService";
import { Attachment } from "../../util/attrs";
import { AttachmentDownloadUrlSubscribe } from "./AttachmentDownloadUrlSubscribe";
import { AttachmentInfoDropdown } from "./AttachmentInfoDropdown";

interface Props {
  attachment: Attachment;
  attachmentService: AttachmentService;
  editable: boolean;
  hasPreview: boolean;
  menuAlign?: "left" | "right";
  onHidePreview?: () => void;
  onMenuToggle?: (open: boolean) => void;
  onRemove: () => void;
  onShowPreview?: () => void;
}

export function AttachmentActions(props: Props) {
  const { menuAlign = "right" } = props;
  const { hidePreview } = props.attachment;

  return (
    <MeatballMenu align={menuAlign} subtle height={24} onToggle={props.onMenuToggle}>
      {({ dismiss, push }) => (
        <Dropdown onLeafClick={dismiss}>
          <AttachmentDownloadUrlSubscribe attachment={props.attachment} attachmentService={props.attachmentService}>
            {(attachmentDownloadUrl): React.ReactNode => {
              const value = "Open";
              switch (attachmentDownloadUrl.type) {
                case "pending":
                case "unavailable":
                  return <DropdownItem disabled value={value} />;
                case "refreshing":
                  return <DropdownItem disabled value={value} icon={<IconLoading />} />;
                case "available":
                  return (
                    <DropdownItem value={value} action={location.external(attachmentDownloadUrl.url, { openInNewTab: true })} />
                  );
              }
            }}
          </AttachmentDownloadUrlSubscribe>
          {props.hasPreview ? (
            hidePreview ? (
              <DropdownItem value="Show preview" disabled={!props.editable} action={props.onShowPreview} />
            ) : (
              <DropdownItem value="Hide preview" disabled={!props.editable} action={props.onHidePreview} />
            )
          ) : null}
          <DropdownItem
            branch
            value="Properties"
            action={() =>
              push(
                <AnimateSlideDown>
                  <AttachmentInfoDropdown attachment={props.attachment} />
                </AnimateSlideDown>
              )
            }
          />
          <DropdownSeparator />
          <DropdownItem value="Remove" disabled={!props.editable} action={props.onRemove} />
        </Dropdown>
      )}
    </MeatballMenu>
  );
}
