'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    getAvatarInitials,
    getAvatarColor,
} from '../../utils/inboxUtils';

interface AvatarProps {
    chat: any;
    size?: number;
    className?: string;
}

export default function Avatar({ chat, size = 46, className = '' }: AvatarProps) {
    const [showInitials, setShowInitials] = useState(false);
    const [isLoaded, setIsLoaded] = useState(false);

    // chat.avatar_url é preenchido upstream (useNewInboxBridge, phonebook,
    // ContactPicker) com a URL do proxy SÓ quando o banco confirma que existe
    // foto. Null aqui = sem foto → Avatar pula a requisição e mostra iniciais.
    const imageUrl = chat?.avatar_url || null;

    useEffect(() => {
        setIsLoaded(false);
        setShowInitials(!imageUrl);
    }, [chat?.remote_jid, imageUrl]);

    const currentUrl = useMemo(() => {
        if (showInitials || !imageUrl) return null;
        return imageUrl;
    }, [showInitials, imageUrl]);

    const handleImageError = () => {
        setShowInitials(true);
    };

    const initials = useMemo(() => getAvatarInitials(chat), [chat]);
    const bgColor = useMemo(() => getAvatarColor(chat?.remote_jid || chat?.phone || chat?.displayName || 'anon'), [chat]);

    return (
        <div
            className={`relative flex-shrink-0 rounded-full overflow-hidden bg-gray-100 flex items-center justify-center border border-black/5 ${className}`}
            style={{ width: size, height: size }}
        >
            <AnimatePresence mode="wait">
                {!showInitials && currentUrl ? (
                    <motion.img
                        key={currentUrl}
                        src={currentUrl}
                        alt=""
                        loading="lazy"
                        decoding="async"
                        initial={{ opacity: 0 }}
                        animate={{ opacity: isLoaded ? 1 : 0 }}
                        transition={{ duration: 0.3 }}
                        onLoad={() => setIsLoaded(true)}
                        onError={handleImageError}
                        className="w-full h-full object-cover"
                    />
                ) : (
                    <motion.div
                        key="initials"
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        className="w-full h-full flex items-center justify-center text-white font-semibold"
                        style={{ backgroundColor: bgColor, fontSize: size * 0.4 }}
                    >
                        {initials}
                    </motion.div>
                )}
            </AnimatePresence>

            {/* Skeleton / Placeholder while loading first image */}
            {!isLoaded && !showInitials && (
                <div className="absolute inset-0 bg-gray-200 animate-pulse" />
            )}
        </div>
    );
}
