import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:fluttericon/entypo_icons.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/constraints/api_path.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class ChatFullPhoto extends StatefulWidget {
  final String chatId;
  final String imageContent;
  final bool isTempData;

  const ChatFullPhoto({
    Key key,
    @required this.imageContent,
    this.isTempData = true,
    @required this.chatId,
  }) : super(key: key);
  @override
  _ChatFullPhotoState createState() => _ChatFullPhotoState();
}

class _ChatFullPhotoState extends State<ChatFullPhoto> {
  ReceivePort _port = ReceivePort();
  Uint8List bytes;
  double _downloadProgress = 0;
  String sendPort = "downloader_full_image_send_port";

  @override
  void initState() {
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    // bytes = base64.decode(widget.imageBase64);
    super.initState();
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "รูปภาพ",
        actions: <Widget>[
          // ProfileAvatar(disableEditProfile: true),
        ],
      ),
      body: ProgressHUD(
        child: Builder(
          builder: (context) {
            final progressModal = ProgressHUD.of(context);

            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (_downloadProgress == 100) {
                progressModal.dismiss();
                setState(() {
                  _downloadProgress = 0.0;
                });

                _alertDownloaded();
              }
            });

            Widget imageChild;
            if (widget.isTempData != null && widget.isTempData) {
              Uint8List bytes = base64.decode(widget.imageContent);
              imageChild = Image.memory(
                bytes,
                fit: BoxFit.fitWidth,
              );
            } else {
              imageChild = CachedNetworkImage(
                // imageUrl: widget.imageContent,
                imageUrl: "${APIPath.chatDownloadFile}?Id=${widget.chatId}&AuthenKey=${ShareDataUtil.getAuthenKey()}",
                progressIndicatorBuilder: (context, url, downloadProgress) => Container(
                  width: 25,
                  height: 25,
                  child: CircularProgressIndicator(
                    value: downloadProgress.progress,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[400]),
                  ),
                ),
                errorWidget: (context, url, error) => Icon(Icons.error),
                fit: BoxFit.fill,
              );
            }
            return Container(
              color: Colors.black,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Container(
                      height: deviceSize.height - 60,
                      color: Colors.white,
                      alignment: Alignment.center,
                      child: SingleChildScrollView(
                        child: imageChild,
                      ),
                    ),
                  ),
                  if (!widget.isTempData)
                    Align(
                      alignment: Alignment.bottomCenter,
                      child: Container(
                        width: double.infinity,
                        height: 60,
                        color: Colors.black,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 10),
                              child: IconButton(
                                icon: Icon(
                                  Entypo.download,
                                  color: Colors.white,
                                ),
                                onPressed: () async {
                                  String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';

                                  final savedDir = Directory(localPath);
                                  bool hasExisted = await savedDir.exists();
                                  if (!hasExisted) {
                                    savedDir.create();
                                  }

                                  progressModal.showWithText('กำลังดาวน์โหลด...');

                                  await FlutterDownloader.enqueue(
                                    url: "${APIPath.chatDownloadFile}?Id=${widget.chatId}&AuthenKey=${ShareDataUtil.getAuthenKey()}",
                                    savedDir: localPath,
                                    showNotification: true,
                                    openFileFromNotification: true,
                                  );
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(_port.sendPort, sendPort);

    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) async {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      double progress = data[2] * 1.0;

      setState(() {
        _downloadProgress = progress;
      });
    });
  }

  _alertDownloaded() {
    return SweetAlert.show(
      context,
      subtitle: "ดาวน์โหลดไฟล์สำเร็จ",
      style: SweetAlertStyle.success,
      showCancelButton: false,
      // cancelButtonText: "ปิด",
      confirmButtonText: "ปิด",
      onPress: (bool isConfirm) {
        if (isConfirm) {
          // openFile();
        }

        return true;
      },
    );
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping(sendPort);
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_full_image_send_port');
    send.send([id, status, progress]);
  }
}
