import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../app/routing/app_navigator.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/alert/data_alert_model.dart';
import '../../shared/widgets/custom_toast_message.dart';

void showPopupInviteFriendCode(BuildContext context, String qrString) {
  final width = MediaQuery.of(context).size.width;
  final qrKey = GlobalKey();

  Future<void> saveQrImage() async {
    if (kIsWeb) {
      showToastMessage('Chức năng lưu ảnh không hỗ trợ trên web.');
      return;
    }
    final boundary = qrKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
    if (boundary == null) {
      showToastMessage('Không thể lưu ảnh.');
      return;
    }
    final hasPermission = await _ensureMediaPermission();
    if (!hasPermission) {
      _showAlertNotPermission();
      return;
    }
    try {
      final ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
      final bytes = data?.buffer.asUint8List();
      if (bytes == null) {
        showToastMessage('Không thể lưu ảnh.');
        return;
      }
      final result = await ImageGallerySaver.saveImage(
        bytes,
        name: 'mypoint_invite_${DateTime.now().toString()}',
        quality: 100,
      );
      final success = (result['isSuccess'] ?? result['success'] ?? result['status']) == true;
      showToastMessage(success ? 'Đã lưu ảnh vào thư viện.' : 'Không thể lưu ảnh.');
    } catch (e) {
      showToastMessage('Không thể lưu ảnh.');
    }
  }

  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.white,
    shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
    builder: (_) {
      return SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      const Expanded(
                        child: Center(
                          child: Text(
                            'Rủ bạn nhập hội, nhận quà cả đôi!',
                            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Navigator.of(context).pop(),
                        child: const Icon(Icons.close, size: 20),
                      ),
                    ],
                  ),
                ),
                const Divider(height: 1),
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset('assets/images/ic_pipi_couple.png', height: 72),
                      const SizedBox(height: 16),
                      if (!kIsWeb) ...[
                        RepaintBoundary(
                          key: qrKey,
                          child: Container(
                            color: Colors.white,
                            child: QrImageView(
                              data: qrString,
                              version: QrVersions.auto,
                              size: width / 1.7,
                              embeddedImage: const AssetImage('assets/images/ic_logo.png'),
                              embeddedImageStyle: const QrEmbeddedImageStyle(size: Size(40, 40)),
                            ),
                          ),
                        ),
                        const SizedBox(height: 8),
                        InkWell(
                          borderRadius: BorderRadius.circular(24),
                          onTap: saveQrImage,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: const [
                                Icon(Icons.download_outlined, color: Colors.black54),
                                SizedBox(width: 4),
                                Text('Lưu ảnh'),
                              ],
                            ),
                          ),
                        ),
                      ] else ...[
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: QrImageView(
                            data: qrString,
                            version: QrVersions.auto,
                            size: width / 1.7,
                            embeddedImage: const AssetImage('assets/images/ic_logo.png'),
                            embeddedImageStyle: const QrEmbeddedImageStyle(size: Size(40, 40)),
                          ),
                        ),
                        const SizedBox(height: 8),
                      ],
                      const SizedBox(height: 8),
                      const Text('Mã giới thiệu:'),
                      Text(
                        qrString,
                        style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.red, fontSize: 18),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    },
  );
}

void _showAlertNotPermission() {
  final dataAlert = DataAlertModel(
    title: "Không có quyền truy cập",
    description: "Ứng dụng không có quyền lưu hình ảnh. Vui lòng vào cài đặt để cho phép quyền truy cập",
    localHeaderImage: "assets/images/ic_pipi_03.png",
    buttons: [
      AlertButton(
        text: "Cài Đặt",
        onPressed: () async {
          Get.back();
          openAppSettings();
        },
        bgColor: BaseColor.primary500,
        textColor: Colors.white,
      ),
      AlertButton(text: "Đóng", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
    ],
  );
  AppNavigator.showAlert(data: dataAlert);
}

Future<bool> _ensureMediaPermission() async {
  if (kIsWeb) return false;
  PermissionStatus status;
  if (defaultTargetPlatform == TargetPlatform.iOS) {
    status = await Permission.photosAddOnly.request();
    if (status.isGranted) return true;
    status = await Permission.photos.request();
    if (status.isGranted) return true;
  } else {
    status = await Permission.photos.request();
    if (status.isGranted) return true;
    status = await Permission.storage.request();
    if (status.isGranted || status.isLimited) return true;
  }
  return false;
}
