import React, { ReactNode } from "react";
import classNames from "classnames";
import { Flex } from "../Flex";
import { Icon, ICON_TYPE } from "../Icon";
import { Text } from "../Text";
import { VendorLogo } from "../VendorLogo";
import { cn } from "./config";

type OrganizationStatus = "claimed" | "unclaimed" | "pending";

type AppbarOrganizationLogoProps = {
  name: string;
  src?: string;
  status?: OrganizationStatus;
  className?: string;
};

type AppbarOrganizationProps = {
  name: string;
  status?: OrganizationStatus;
  logoSrc?: string;
  hideLogo?: boolean;
  onClick?: () => void;
  className?: string;
};

type AppbarOrganizationsProps = {
  children: ReactNode;
  className?: string;
};

const AppbarOrganizationLogo = ({
  src,
  name,
  status,
  className,
}: AppbarOrganizationLogoProps) => {
  if (status === "pending") {
    return (
      <Flex className={classNames(cn({ e: "organizationLogo" }), className)}>
        <Icon icon={ICON_TYPE.ELLIPSIS_H} />
      </Flex>
    );
  }

  if (!src || status === "unclaimed") {
    return null;
  }

  return (
    <VendorLogo className="ml-2" vendorName={name} src={src} size={6}>
      <VendorLogo.Badge icon={ICON_TYPE.CHECK} />
    </VendorLogo>
  );
};

export const AppbarOrganizations = ({
  children,
  className,
}: AppbarOrganizationsProps) => {
  return (
    <Flex className={classNames(cn({ e: "organizations" }), className)}>
      {children}
    </Flex>
  );
};

export const AppbarOrganization = ({
  name,
  status = "claimed",
  logoSrc,
  hideLogo,
  onClick,
  className,
}: AppbarOrganizationProps) => {
  const Component = onClick ? "button" : "div";
  return (
    <Component
      className={classNames(
        cn({ e: "organization" }),
        onClick && cn({ e: "organization", m: "switcher" }),
        className,
      )}
      type={onClick ? "button" : undefined}
      onClick={onClick}
    >
      <Text as="span" className="text-body">
        {name}
      </Text>

      {!hideLogo && (
        <AppbarOrganizationLogo name={name} src={logoSrc} status={status} />
      )}
    </Component>
  );
};
