"use client";
import { useState, useRef } from 'react';
import { useUpdateAvatar } from '@/hooks/useUpdateProfile';
import Image from 'next/image';
import { Camera } from 'lucide-react';

export default function AvatarUpload({ currentAvatar, onUpload }) {
    const fileInputRef = useRef();

    const { mutate: updateAvatar, isLoading, isError, error } = useUpdateAvatar()


    const handleUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        updateAvatar(file, {
            onSuccess: (avatar) => {
                console.log('Avatar updated successfully:', avatar);
                onUpload(avatar.avatarUrl);
            }
        });
    };

    return (
        <div className="flex flex-col items-center">
            <div className="relative w-32 h-32 rounded-full overflow-hidden border-2 border-gray-200 group">
                {currentAvatar ? (
                    <img
                        src={currentAvatar}
                        alt="Profile Avatar"
                        width={128}
                        height={128}
                        className="w-full h-full object-cover"
                    />
                ) : (
                    <div className="w-full h-full bg-gray-300 flex items-center justify-center">
                        <span className="text-gray-500 text-2xl">No Avatar</span>
                    </div>
                )}

                {/* Camera Icon Overlay */}
                <div
                    onClick={() => fileInputRef.current.click()}
                    className="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 cursor-pointer"
                >
                    <Camera className="text-white w-6 h-6" />
                </div>
            </div>

            <input
                type="file"
                ref={fileInputRef}
                onChange={handleUpload}
                accept="image/jpeg, image/png, image/gif"
                className="hidden"
            />

            {isLoading && (
                <p className="mt-2 text-sm text-blue-500">Uploading...</p>
            )}

            {error && (
                <p className="mt-2 text-red-500 text-sm">{error}</p>
            )}
        </div>
    );
}