import type { JSX } from "react"

import { FunctionComponent, memo, useEffect, useState } from "react"

import cs from "classnames"
import Image from "next/image"
import avatarPlaceholder from "@shared/assets/placeholder.png"

import { IAvatarProps } from "./Avatar.d"
import styles from "./Avatar.module.scss"

const isValidImageSrc = (src: string): boolean => {
	if (src.startsWith("/") || src.startsWith("http://") || src.startsWith("https://")) {
		return true
	}
	try {
		new URL(src)
		return true
	} catch {
		return false
	}
}

const avatarProperties = {
	xxxlarge: {
		width: 1024,
		height: 1024,
	},
	xxlarge: {
		width: 512,
		height: 512,
	},
	xlarge: {
		width: 512,
		height: 512,
	},
	large: {
		width: 256,
		height: 256,
	},
	medium: {
		width: 128,
		height: 128,
	},
	small: {
		width: 64,
		height: 64,
	},
}

export const Avatar: FunctionComponent<IAvatarProps> = memo(
	({
		size = "large",
		variant = "circle",
		url,
		active = false,
	}): JSX.Element => {
		const [loaded, setLoaded] = useState(false)
		const validUrl = url && isValidImageSrc(url) ? url : undefined
		const [imgURL, setImgURL] = useState(validUrl || avatarPlaceholder.src)

		useEffect(() => {
			if (validUrl) {
				setImgURL(validUrl)
				setLoaded(false)
			}
		}, [validUrl])
		return (
			<div className={cs(styles.root, styles[size])}>
				{validUrl ? (
					<>
						<Image
							priority
							loading="eager"
							className={cs(styles.img, styles[size], styles[variant], {
								[styles.loading]: !loaded,
							})}
							onError={(e) => {
								e.preventDefault()
								setImgURL(avatarPlaceholder.src)
							}}
							onLoad={() => setLoaded(true)}
							alt="avatar"
							src={imgURL}
							{...avatarProperties[size]}
						/>
						<div
							className={cs(styles.icon, {
								[styles.active]: active,
							})}
						/>
					</>
				) : (
					<Image
						priority
						loading="eager"
						className={cs(styles.img, styles[size], styles[variant], {
							[styles.loading]: !loaded,
						})}
						alt="avatar"
						src={imgURL}
						{...avatarProperties[size]}
					/>
				)}
			</div>
		)
	},
)
