import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/core/services/web/web_helper.dart';

class AvatarPickerSheet {
  static const List<String> localAvatars = [
    "avatar-1.png",
    "avatar-2.png",
    "avatar-3.png",
    "avatar-4.png",
    "avatar-5.png",
    "avatar-6.png",
  ];

  static String _avatarAssetPath(String filename) => "assets/images/$filename";

  static void show({
    required BuildContext context,
    required VoidCallback onCameraTap,
    required VoidCallback onGalleryTap,
    required ValueChanged<String> onAvatarSelected,
    String? selectedAvatar,
  }) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
      builder: (_) {
        return SafeArea(
          top: false,
          child: Padding(
            padding: const EdgeInsets.fromLTRB(24, 12, 24, 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Stack(
                  alignment: Alignment.center,
                  children: [
                    const Center(
                      child: Text(
                        "Ảnh đại diện",
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: GestureDetector(
                        onTap: () => Navigator.of(context).pop(),
                        child: const Icon(Icons.close, size: 20),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 36),
                Row(
                  children: [
                    _OptionButton(
                      icon: Icons.camera_alt,
                      label: "Chụp ảnh",
                      onTap: () {
                        Navigator.of(context).pop();
                        _requestImagePermission("camera");
                        onCameraTap();
                      },
                    ),
                    const SizedBox(width: 24),
                    _OptionButton(
                      icon: Icons.photo_library,
                      label: "Thư viện",
                      onTap: () {
                        Navigator.of(context).pop();
                        _requestImagePermission("gallery");
                        onGalleryTap();
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                const Text("Thư viện biểu cảm", style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
                const SizedBox(height: 8),
                LayoutBuilder(
                  builder: (context, constraints) {
                    const crossAxisCount = 3;
                    const spacing = 36.0;
                    final itemSize =
                        (constraints.maxWidth - (crossAxisCount - 1) * spacing) / crossAxisCount;
                    return GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: localAvatars.length,
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: crossAxisCount,
                        crossAxisSpacing: spacing,
                        mainAxisSpacing: spacing,
                        childAspectRatio: 1,
                      ),
                      itemBuilder: (context, index) {
                        final avatarFile = localAvatars[index];
                        final avatarPath = _avatarAssetPath(avatarFile);
                        final isSelected = avatarFile == selectedAvatar;
                        return GestureDetector(
                          onTap: () {
                            Navigator.of(context).pop();
                            onAvatarSelected(avatarFile);
                          },
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              ClipOval(
                                child: Image.asset(
                                  avatarPath,
                                  width: itemSize,
                                  height: itemSize,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              if (isSelected)
                                Container(
                                  width: itemSize,
                                  height: itemSize,
                                  decoration: BoxDecoration(
                                    color: Colors.black.withOpacity(0.35),
                                    shape: BoxShape.circle,
                                  ),
                                ),
                              if (isSelected) const Icon(Icons.check, color: Colors.white, size: 30),
                            ],
                          ),
                        );
                      },
                    );
                  },
                ),
                const SizedBox(height: 8),
              ],
            ),
          ),
        );
      },
    );
  }

  static void showCameraOptions({
    required BuildContext context,
    required VoidCallback onCamera,
    required VoidCallback onGallery,
  }) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
      builder: (_) {
        return SafeArea(
          top: false,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text("Chụp ảnh"),
                onTap: () {
                  Navigator.of(context).pop();
                  _requestImagePermission("camera");
                  onCamera();
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text("Chọn từ thư viện"),
                onTap: () {
                  Navigator.of(context).pop();
                  _requestImagePermission("gallery");
                  onGallery();
                },
              ),
              const SizedBox(height: 12),
            ],
          ),
        );
      },
    );
  }

  static Future<bool> _requestImagePermission(String type) async {
    final result = await webPermissionsRequest(type);
    final granted = _isPermissionGranted(result);
    if (!granted) {
      debugPrint("🚫 Permission denied: $type");
    }
    return granted;
  }

  static bool _isPermissionGranted(dynamic result) {
    if (result == null) {
      return true;
    }
    if (result is bool) {
      return result;
    }
    if (result is String) {
      final normalized = result.toLowerCase();
      return normalized == 'granted' ||
          normalized == 'allow' ||
          normalized == 'allowed' ||
          normalized == 'true' ||
          normalized == '1';
    }
    if (result is Map) {
      final status = result['status'] ?? result['state'] ?? result['result'];
      if (status is String) {
        final normalized = status.toLowerCase();
        if (normalized == 'granted' || normalized == 'allow' || normalized == 'allowed') {
          return true;
        }
        if (normalized == 'denied' || normalized == 'blocked') {
          return false;
        }
      }
      final granted = result['granted'] ?? result['allow'] ?? result['allowed'];
      if (granted is bool) {
        return granted;
      }
      if (granted is String) {
        final normalized = granted.toLowerCase();
        return normalized == 'true' || normalized == '1' || normalized == 'granted';
      }
    }
    return true;
  }
}

class _OptionButton extends StatelessWidget {
  const _OptionButton({
    required this.icon,
    required this.label,
    required this.onTap,
  });

  final IconData icon;
  final String label;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Text(label, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
          const SizedBox(height: 8),
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(color: Colors.grey.shade200, shape: BoxShape.circle),
            child: Icon(icon, color: Colors.grey, size: 24),
          ),
        ],
      ),
    );
  }
}
