import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:image_size_getter/image_size_getter.dart';
import 'package:open_file/open_file.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:road24_mobile/data/repository/ChatRepository.dart';
import 'package:sizer/sizer.dart';
import 'package:flutter/material.dart';

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

enum MessageBubbleSide { center, left, right }

enum AttachmentType { file, image, text }

class FileType {
  static List<String> imageFormats = ['jpg', 'jpeg', 'png'];
}

class MessageBubble extends StatelessWidget {
  final Function? showNotification;
  final MessageBubbleSide side;
  final message;
  final messageParameters;
  final Color? textColor;
  final double? fontSize;
  final Color? color;
  final AttachmentType? fileType;
  final ChatRepository repo;

  const MessageBubble({
    Key? key,
    this.side = MessageBubbleSide.center,
    required this.message,
    required this.repo,
    this.textColor,
    this.fontSize,
    this.color,
    this.fileType,
    this.messageParameters,
    this.showNotification,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // var repo = ChatRepository();
    final String userID = messageParameters?.u?.sId;
    final String? visitorToken = repo.getTokenFromVariable();
    final String roomID =
        (messageParameters != null) ? messageParameters.roomId : "0";
    String messageText = message;
    bool isImage = false;

    if (fileType == AttachmentType.text) {
      messageText = message.toString().replaceFirst(RegExp(r"^\s+"), "");
      messageText = message.toString().replaceFirst(RegExp(r"\s+$"), "");
    } else {
      if (FileType.imageFormats
          .contains(message.toString().split('.').last.toLowerCase())) {
        ///IF this is image file, it will show preview for this message
        isImage = true;
      } else {
        ///IF this is NOT image file, then it will show name of the file only
        isImage = false;
      }
    }
    if (visitorToken != null)
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: Align(
          alignment: _bubbleAlignment(),
          child: Container(
            constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width * .7,
            ),
            padding: isImage ? const EdgeInsets.all(0.0) : _bubblePadding(),
            decoration: BoxDecoration(
              borderRadius: _bubbleBorderRadius(),
              color: isImage ? Colors.transparent : color,
            ),
            child: fileType == AttachmentType.text
                ? Text(
                    messageText,
                    style: Theme.of(context).textTheme.bodyText1?.copyWith(
                          color: textColor,
                          fontSize: fontSize,
                        ),
                    textAlign: TextAlign.center,
                  )
                : isImage
                    ? ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child: SizedBox(
                          width: 45.0.w,
                          child: InkWell(
                            onTap: () async {
                              var path = MyApp.preferences?.getDownloadPath();
                              await Dio().download(
                                'https://rocket.najotapp.uz$message',
                                '$path/${messageParameters.file.name}',
                                options: Options(headers: {
                                  'cookie':
                                      'rc_uid=$userID; rc_rid=$roomID; rc_token=$visitorToken; rc_room_type=l',
                                  'Accept-Encoding': ''
                                }),
                              );

                              OpenFile.open(
                                  "$path/${messageParameters.file.name}");
                            },
                            child: Image.network(
                                'https://rocket.najotapp.uz$message',
                                headers: {
                                  'cookie':
                                      'rc_uid=$userID; rc_rid=$roomID; rc_token=$visitorToken; rc_room_type=l',
                                }),
                          ),
                        ),
                      )
                    : FileMessage(
                        message: messageParameters,
                        textColor: textColor!,
                        fontSize: fontSize!,
                        visitorToken: visitorToken,
                        showNotification: showNotification,
                      ),
          ),
        ),
      );
    return SizedBox();
  }

  showImage(context, String path, userID, roomID, visitorToken) async {
    print("token:  $visitorToken");
    print("userid:  $userID");
    print("roomid:  $roomID");
    var file = File(path);
    ByteBuffer bytes =
        (await NetworkAssetBundle(Uri.parse(path)).load(path)).buffer;
    double initialForFirst =
        100.0.w / ImageSizeGetter.getSize(MemoryInput.byteBuffer(bytes)).width;
    Navigator.push(context, MaterialPageRoute(builder: (_) {
      return SafeArea(
        child: Stack(
          children: [
            PhotoViewGallery(
              pageOptions: <PhotoViewGalleryPageOptions>[
                PhotoViewGalleryPageOptions(
                  imageProvider: Image.file(file) as ImageProvider,
                  heroAttributes: const PhotoViewHeroAttributes(tag: "tag1"),
                  maxScale: initialForFirst + 0.1,
                  minScale: initialForFirst,
                  initialScale: initialForFirst,
                  basePosition: Alignment.center,
                ),
                PhotoViewGalleryPageOptions(
                  imageProvider: CachedNetworkImageProvider(path),
                  heroAttributes: const PhotoViewHeroAttributes(tag: "tag2"),
                  maxScale: initialForFirst + 0.1,
                  minScale: initialForFirst,
                  initialScale: initialForFirst,
                ),
              ],
              loadingBuilder: (context, progress) => Center(
                child: Container(
                  width: 20.0,
                  height: 20.0,
                  child: CircularProgressIndicator(),
                ),
              ),
              backgroundDecoration: BoxDecoration(),
              pageController: PageController(initialPage: 0),
            ),
          ],
        ),
      );
    }));
  }

  Alignment _bubbleAlignment() {
    if (side == MessageBubbleSide.left) {
      return Alignment.centerLeft;
    } else if (side == MessageBubbleSide.right) {
      return Alignment.centerRight;
    } else if (side == MessageBubbleSide.center) {
      return Alignment.center;
    } else {
      return Alignment.center;
    }
  }

  BorderRadius _bubbleBorderRadius() {
    return BorderRadius.circular(10.0);
  }

  EdgeInsets _bubblePadding() {
    if (side == MessageBubbleSide.center) {
      return const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0);
    } else {
      return const EdgeInsets.symmetric(horizontal: 12.0, vertical: 12.0);
    }
  }
}
