import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:gap/gap.dart';
import 'package:image/image.dart' as img;
import 'package:krow/core/entity/event_entity.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart';

class EventQrPopup {
  static Future<void> show(BuildContext context, EventEntity item) async {
    var qrKey = GlobalKey();

    return showDialog<void>(
        context: context,
        builder: (context) {
          return Center(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
              decoration: KwBoxDecorations.white24,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 24, left: 24, right: 24),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'Event QR code',
                            style: AppTextStyles.headingH3.copyWith(height: 1),
                          ),
                          GestureDetector(
                            onTap: () {
                              Navigator.of(context).pop();
                            },
                            child: Assets.images.icons.x.svg(
                              width: 16,
                              height: 16,
                              colorFilter: const ColorFilter.mode(
                                AppColors.blackCaptionText,
                                BlendMode.srcIn,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    RepaintBoundary(
                      key: qrKey,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 24, right: 24),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Gap(8),
                            Text(
                              'The QR code below has been successfully generated for the ${item.name}. You can share this code with staff members to enable them to clock in.',
                              style: AppTextStyles.bodySmallReg
                                  .copyWith(color: AppColors.blackGray),
                            ),
                            const Gap(24),
                            QrImageView(
                              data: jsonEncode({
                                'type': 'event',
                                'birth': 'app',
                                'eventId': item.id
                              }),
                              version: QrVersions.auto,
                              size: MediaQuery.of(context).size.width - 56,
                            ),
                            const Gap(24),
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(
                          bottom: 24, left: 24, right: 24),
                      child: KwButton.primary(
                        label: 'Share QR Code',
                        onPressed: () async {
                          final params = ShareParams(
                            text: 'Qr code for ${item.name}',
                            files: [
                              XFile.fromData(
                                await removeAlphaAndReplaceTransparentWithWhite(
                                    qrKey.currentContext!.findRenderObject()
                                        as RenderRepaintBoundary),
                                name: 'event_qr.png',
                                mimeType: 'image/png',
                              )
                            ],
                          );
                          await SharePlus.instance.share(params);
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  static Future<Uint8List> removeAlphaAndReplaceTransparentWithWhite(
      RenderRepaintBoundary boundary) async {
    final image = await boundary.toImage(pixelRatio: 5.0);
    final byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
    final Uint8List rgba = byteData!.buffer.asUint8List();
    final int length = rgba.lengthInBytes;
    final Uint8List rgb = Uint8List(length ~/ 4 * 3);

    for (int i = 0, j = 0; i < length; i += 4, j += 3) {
      int r = rgba[i];
      int g = rgba[i + 1];
      int b = rgba[i + 2];
      int a = rgba[i + 3];

      if (a < 255) {
        // Replace transparent pixel with white
        r = 255;
        g = 255;
        b = 255;
      }
      rgb[j] = r;
      rgb[j + 1] = g;
      rgb[j + 2] = b;
    }

    final width = image.width;
    final height = image.height;
    final img.Image rgbImage = img.Image.fromBytes(
      width: width,
      height: height,
      bytes: rgb.buffer,
      numChannels: 3,
      format: img.Format.uint8,
    );
    return Uint8List.fromList(img.encodePng(rgbImage));
  }
}
