import 'dart:io';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sizer/sizer.dart';

import '../../../my_app.dart';

class FileMessage extends StatefulWidget {
  const FileMessage({
    Key? key,
    required this.message,
    required this.fontSize,
    required this.visitorToken,
    required this.textColor,
    this.showNotification,
  }) : super(key: key);

  final Color textColor;
  final message;
  final String visitorToken;
  final double fontSize;
  final Function? showNotification;

  @override
  _FileMessageState createState() => _FileMessageState();
}

class _FileMessageState extends State<FileMessage> {
  Widget? currentState;
  double _progress = 0;

  Map<String, dynamic> result = {
    'isSuccess': false,
    'filePath': null,
    'error': null,
  };

  final Widget downloadIcon = Container(
    decoration: BoxDecoration(color: Color(0xff8A2BE2), shape: BoxShape.circle),
    child: Icon(
      Icons.arrow_downward_sharp,
      color: Colors.white,
    ),
  );
  //
  // final Widget loadingIcon = SizedBox(
  //     width: 5.0.w,
  //     height: 5.0.w,
  //     child: Center(
  //       child: CircularProgressIndicator(
  //           backgroundColor: Colors.white, strokeWidth: 2.0),
  //     ));

  @override
  void initState() {
    super.initState();
    currentState = downloadIcon;
  }

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

  @override
  Widget build(BuildContext context) {
    return (widget.message != null)
        ? Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      minWidth: MediaQuery.of(context).size.width / 1000,
                      // minWidth: constraints.maxWidth,
                      // minHeight: constraints.maxHeight
                    ),
                    child: IntrinsicWidth(
                      child: Text(
                        widget.message.file.name,
                        style: Theme.of(context).textTheme.bodyText1?.copyWith(
                              color: widget.textColor,
                              fontSize: widget.fontSize,
                            ),
                      ),
                    ),
                  ),
                ),
              ),
              Flexible(
                child: GestureDetector(
                  onTap: () async {
                    final storagePermissionStatus =
                        await Permission.storage.request();
                    var path = MyApp.preferences?.getDownloadPath();

                    if (Platform.isIOS) await Permission.notification.request();

                    if (storagePermissionStatus.isGranted) {
                      await Dio().download(
                          'https://rocket.najotapp.uz${widget.message.attachments[0].titleLink}',
                          '$path/${widget.message.file.name}',
                          options: Options(headers: {
                            'cookie':
                                'rc_uid=${widget.message.u.sId}; rc_rid=${widget.message.roomId}; rc_token=${widget.visitorToken}; rc_room_type=l',
                            'Accept-Encoding': ''
                          }),
                          onReceiveProgress: _onReceiveProgress);
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 10.0),
                    child: currentState,
                  ),
                ),
              )
            ],
          )
        : SizedBox();
  }

  Future<void> _onReceiveProgress(int received, int total) async {
    print("RECEIVE PROGRESS CALLED");
    print("TOTAL TOTAL: $total");

    var path = MyApp.preferences?.getDownloadPath();

    if (total != -1) {
      setState(() {
        _progress = received / total;
        if (_progress >= 1) {
          currentState = Container(
              decoration: BoxDecoration(
                  shape: BoxShape.circle, color: Color(0xff8A2BE2)),
              child: Icon(Icons.done, color: Colors.white));

          result['isSuccess'] = true;
          result['filePath'] = '$path/${widget.message.file.name}';
          // widget.showNotification!(result);
        } else {
          currentState = Container(
            width: 4.5.w,
            height: 4.5.w,
            margin: const EdgeInsets.all(2.8),
            child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xff8A2BE2)),
                value: _progress,
                backgroundColor: Colors.white,
                strokeWidth: 2.0),
          );
        }
        if (_progress == 1.0) {
          print("opening...");
          try {
            String paths = '$path/${widget.message.file.name}';
            print(paths);
            OpenFile.open(paths);
          } catch (ex) {
            print("open exception.. $ex");
          }
        }
        print(_progress);
      });
    } else {
      // if (response.statusMessage == 200) {
      //
      // }
    }
  }
}
