import clsx from "clsx";
import { Avatar as AvatarPrimative } from "radix-ui";
import * as React from "react";
import * as styles from "./styles.module.css";

interface User {
  profile_image_url?: { src?: string } | string;
  given_name?: string;
  family_name?: string;
}

function imgSrc(image?: string | { src?: string }) {
  if (!image) return null;
  if (typeof image === "string") {
    return image;
  }
  return image?.src ?? null;
}

export function Avatar({
  user,
  className,
  size = "md",
  variant = "subtle",
  ...props
}: {
  user: User;
  className?: string;
  size: "2xs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "full";
  variant?: "solid" | "subtle" | "outline";
}) {
  const initials = React.useMemo(() => {
    if (!user?.given_name && !user?.family_name) return "";
    if (user?.given_name && user?.family_name) {
      return `${user.given_name[0]}${user.family_name[0]}`;
    } else if (user?.given_name) {
      return user.given_name[0] ?? "";
    }
    return user?.family_name?.[0] ?? "";
  }, [user?.given_name, user?.family_name]);
  const img = imgSrc(user?.profile_image_url);
  return (
    <AvatarPrimative.Root
      className={clsx("__avatar_root", styles.root, className)}
      data-size={size}
      data-variant={variant}
      data-component="Avatar$Brevity"
      {...props}
    >
      {img ? (
        <AvatarPrimative.Image
          data-avatar="image"
          className={clsx("__avatar_image", styles.image)}
          src={img}
          alt={`${user?.given_name} ${user?.family_name}`}
        />
      ) : null}
      <AvatarPrimative.Fallback
        data-avatar="fallback"
        className={clsx("__avatar_fallback", styles.fallback)}
        delayMs={img ? 600 : 0}
      >
        {initials || <UserIcon />}
      </AvatarPrimative.Fallback>
    </AvatarPrimative.Root>
  );
}

function UserIcon() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      className={styles.icon}
      fill="currentcolor"
      viewBox="0 -960 960 960"
    >
      <path d="M480-480q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 66-47 113t-113 47zM160-240v-32q0-34 17.5-62.5T224-378q62-31 126-46.5T480-440q66 0 130 15.5T736-378q29 15 46.5 43.5T800-272v32q0 33-23.5 56.5T720-160H240q-33 0-56.5-23.5T160-240zm80 0h480v-32q0-11-5.5-20T700-306q-54-27-109-40.5T480-360q-56 0-111 13.5T260-306q-9 5-14.5 14t-5.5 20v32zm240-320q33 0 56.5-23.5T560-640q0-33-23.5-56.5T480-720q-33 0-56.5 23.5T400-640q0 33 23.5 56.5T480-560zm0-80zm0 400z"></path>
    </svg>
  );
}
