import 'dart:convert';
import 'dart:io';
import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/models/dialog_models.dart';
import 'package:aman_kassa_flutter/core/route_names.dart';
import 'package:aman_kassa_flutter/core/services/dialog_service.dart';
import 'package:aman_kassa_flutter/core/services/navigator_service.dart';
import 'package:aman_kassa_flutter/shared/app_colors.dart';
import 'package:aman_kassa_flutter/shared/ui_helpers.dart';
import 'package:aman_kassa_flutter/widgets/fields/busy_button_icon.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:url_launcher/url_launcher.dart';

class ImageShowContainer extends StatelessWidget {
  final ImageShowModel data;

  ImageShowContainer(this.data);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //backgroundColor: fillColor,
        title: Text(data.title),
      ),
      body: ListView(
        children: <Widget>[imageFromBase64String(data.data)],
      ),
      floatingActionButton: MyFloatingActionButton(data),
    );
  }
}

Padding imageFromBase64String(String base64String) {
  return Padding(
    padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
    child: Image.memory(base64Decode(base64String)),
  );
}

class ImageShowModel {
  final String data;
  final String title;
  final String url;

  ImageShowModel({this.data, this.title, this.url});
}

class MyFloatingActionButton extends StatefulWidget {
  final ImageShowModel data;
  MyFloatingActionButton(this.data);
  @override
  _MyFloatingActionButtonState createState() => _MyFloatingActionButtonState();
}

class _MyFloatingActionButtonState extends State<MyFloatingActionButton> {
  bool showFab = true;
  DialogService _dialog = locator<DialogService>();
  NavigatorService _navigatorService = locator<NavigatorService>();

  @override
  Widget build(BuildContext context) {
    return showFab
        ? FloatingActionButton(
            child: Icon(Icons.share),
            onPressed: () {
              var bottomSheetController = showBottomSheet(
                  context: context,
                  builder: (bottomSheetContext) => Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                          boxShadow: [
                            BoxShadow(
                                blurRadius: 10,
                                color: Colors.grey[300],
                                spreadRadius: 5)
                          ]),
                      height: 260,
                      child: Column(
                        children: <Widget>[
                          verticalSpaceSmall,
                          BusyButtonIcon(
                            title: 'WhatsApp',
                            onPressed: callWhatsApp,
                            mainColor: greenColor,
                            icon: MdiIcons.whatsapp,
                            enabled: widget.data.url != null,
                          ),
                          verticalSpaceSmall,
                          BusyButtonIcon(
                            title: 'QR-код чека',
                            onPressed: qrGenerate,
                            mainColor: primaryColor,
                            icon: MdiIcons.qrcode,
                            enabled: widget.data.url != null,
                          ),
                          verticalSpaceSmall,
                          BusyButtonIcon(
                            title: 'Поделиться',
                            onPressed: shareFile,
                            mainColor: yellowColor,
                            icon: Icons.share,
                          ),
                        ],
                      )));
              showFoatingActionButton(false);
              bottomSheetController.closed.then((value) {
                showFoatingActionButton(true);
              });
            },
          )
        : Container();
  }

  void shareFile() async {
    try {
      await Share.file('Aman Kassa', 'aman_kassa_check.png',
          base64Decode(widget.data.data), 'image/png');
    } catch (e) {
      print('error: $e');
    }
  }

  void qrGenerate() async {
    _navigatorService.push(QrViewRoute,
        arguments:
            ImageShowModel(data: widget.data.url, title: 'Спасибо за покупку'));
  }

  void callWhatsApp() async {
    DialogResponse response = await _dialog.showConfirmationDialogInput(
        description: 'Номер телефона',
        cancelTitle: 'Отмена',
        confirmationTitle: 'Отправить',
        formatType: 'phone');
    if (response.confirmed) {
      String phoneNumber = response.responseText;
      String msg = "Спасибо за покупку! \r\n ${widget.data.url} ";
      launchWhatsApp(phone: phoneNumber, message: msg);
    }
  }

  void launchWhatsApp({
    @required String phone,
    @required String message,
  }) async {
    String url() {
      if (Platform.isIOS) {
        return "whatsapp://wa.me/$phone/?text=${Uri.encodeFull(message)}";
      } else {
        return "whatsapp://send?phone=$phone&text=${Uri.encodeFull(message)}";
      }
    }

    print(url());
    if (await canLaunch(url())) {
      await launch(url());
    } else {
      _dialog.showDialog(description: 'Отсутсвует приложение WhatsApp');
    }
  }

  void showFoatingActionButton(bool value) {
    setState(() {
      showFab = value;
    });
  }
}
