import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/providers/local_user_provider.dart';
import 'package:em2rp/views/widgets/image/profile_picture.dart';

class ProfilePictureSelector extends StatefulWidget {
  const ProfilePictureSelector({super.key});

  @override
  State<ProfilePictureSelector> createState() => _ProfilePictureSelectorState();
}

class _ProfilePictureSelectorState extends State<ProfilePictureSelector> {
  bool _isHovering = false;

  Future<void> _pickAndUploadImage() async {
    if (!context.mounted) return;
    final provider = Provider.of<LocalUserProvider>(context, listen: false);
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null && context.mounted) {
      await provider.changeProfilePicture(image);
    }
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<LocalUserProvider>(context);
    final String userId = userProvider.uid ?? '';

    return MouseRegion(
      onEnter: (_) => setState(() => _isHovering = true),
      onExit: (_) => setState(() => _isHovering = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: _pickAndUploadImage,
        child: Stack(
          alignment: Alignment.center,
          children: [
            ProfilePictureWidget(userId: userId, radius: 80),
            if (_isHovering)
              Container(
                width: 160,
                height: 160,
                decoration: const BoxDecoration(
                  color: Colors.black54,
                  shape: BoxShape.circle,
                ),
                child: const Center(
                  child: Icon(
                    Icons.edit,
                    size: 36,
                    color: Colors.white,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
