"use client"

import * as React from "react"
import Image from "next/image"
import { getFileUrl } from "@/api/client"
import { cn } from "@/lib/utils"
import { UserAvatarProps } from "@/types/ui";

export function UserAvatar({ 
    avatar, 
    name, 
    className, 
    imageClassName, 
    fallbackClassName, 
    size = "md" 
}: UserAvatarProps) {
    const rawUrl = typeof avatar === 'string' ? avatar : (avatar as { url?: string })?.url
    const url = getFileUrl(rawUrl)
    const [error, setError] = React.useState(false)
    
    React.useEffect(() => {
        setError(false)
    }, [url])

    const initials = name
        ? name.trim().split(/\s+/).map(w => w[0]).join("").slice(0, 2).toUpperCase()
        : "?"

    const sizeClasses = {
        sm: "h-8 w-8 text-[10px]",
        md: "h-10 w-10 text-[12px]",
        lg: "h-20 w-20 text-2xl"
    }

    const imageSizes =
        size === "sm" ? "32px" : size === "lg" ? "80px" : "40px"
    const unoptimized =
        !!url &&
        (url.startsWith("blob:") ||
            url.startsWith("data:"))

    return (
        <div className={cn(
            "relative flex shrink-0 overflow-hidden items-center justify-center rounded-full bg-linear-to-br from-[#6C63FF] to-[#9B8FFF] text-white font-extrabold font-['Lexend']",
            sizeClasses[size],
            className
        )}>
            {url && !error ? (
                <Image
                    src={url}
                    alt={name ?? ""}
                    fill
                    sizes={imageSizes}
                    unoptimized={unoptimized}
                    className={cn("object-cover", imageClassName)}
                    onError={() => setError(true)}
                />
            ) : (
                <div className={cn("flex h-full w-full items-center justify-center", fallbackClassName)}>
                    {initials}
                </div>
            )}
        </div>
    )
}
