import { Link } from 'react-router-dom';

import { usePopup } from 'components/layers';

import { MenuIconButton } from 'components/MenuIconButton';
import { FlyoutMenu } from 'components/FlyoutMenu';

import { formatNumber } from 'utils';

interface WorkspaceListItemMenuProps {
  onRename: () => void;
  onDelete: () => void;
  onDismiss: () => void;
}

const WorkspaceListItemMenu = ({
  onRename,
  onDelete,
  onDismiss,
}: WorkspaceListItemMenuProps) => {
  return (
    <FlyoutMenu
      style={{ marginBottom: -24 }}
      options={[
        {
          label: 'Rename workspace',
          value: 'rename',
          onClick: onRename,
        },
        {
          label: 'Delete workspace',
          value: 'delete',
          onClick: onDelete,
        },
      ]}
      onDismiss={onDismiss}
      key="WorkspaceListItemMenu"
    />
  );
};

interface WorkspaceListItemProps {
  data: {
    id: string;
    name: string;
    totalProfiles: number;
  };
  onRename: (a: { workspaceId: string; value: string }) => void;
  onDelete: (a: { workspaceId: string }) => void;
}

export const WorkspaceListItem = ({
  data,
  onRename,
  onDelete,
}: WorkspaceListItemProps) => {
  const workspaceListItemMenu = usePopup(WorkspaceListItemMenu, {
    defaultProps: {
      onDelete: () =>
        onDelete({
          workspaceId: data.id,
        }),
      onRename: () =>
        onRename({
          workspaceId: data.id,
          value: data.name,
        }),
    },
    placement: 0,
  });

  return (
    <Link
      to={data.id}
      className="flexNone flex flexColumn padding4 hover rounded2 tdn oh"
      style={{ width: 200, height: 200 }}
    >
      <div className="h100 flex justifyBetween">
        <div className="medium">{data.name || data.id}</div>
      </div>
      <div className="flex alignCenter justifyBetween">
        {data.totalProfiles ? (
          <div className="mark--orange fz14 paddingX2 rounded2">
            {formatNumber(data.totalProfiles)} profiles
          </div>
        ) : (
          <div className="mark--gray fz14 paddingX2 rounded2">Empty</div>
        )}

        <div>
          <MenuIconButton
            className="onHover"
            onClickCapture={(ev) => {
              ev.preventDefault();
              workspaceListItemMenu.toggle(ev.currentTarget);
            }}
          />
        </div>
      </div>
    </Link>
  );
};
