import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/cx_module/chat/chat_api_client.dart';
import 'package:test_sa/modules/cx_module/chat/chat_provider.dart';
import 'package:test_sa/modules/cx_module/chat/model/get_single_user_chat_list_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/app_style/app_text_style.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker_item.dart';
import 'package:test_sa/views/widgets/sound/sound_player.dart';

class ChatFileViewer extends StatelessWidget {
  String downloadUrl;
  FileTypeResponse fileTypeResponse;

  ChatFileViewer(this.downloadUrl, this.fileTypeResponse, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<File?>(
        future: checkFileInLocalStorage(),
        builder: (BuildContext context, AsyncSnapshot<File?> snapshot) {
          if (snapshot.connectionState != ConnectionState.waiting && snapshot.hasData) {}

          if (fileTypeResponse!.fileKind.toString().toLowerCase() == "audio") {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Container(
                width: 48,
                height: 48,
                decoration: ShapeDecoration(
                  color: AppColor.background(context),
                  shape: RoundedRectangleBorder(
                    side: BorderSide(width: 1, color: (context.isDark ? AppColor.neutral20 : AppColor.neutral30)),
                    borderRadius: BorderRadius.circular(32),
                  ),
                ),
                child: CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 2).center,
              );
            }
            if (snapshot.data == null) {
              return Text("Failed to load", style: AppTextStyle.tiny.copyWith(color: context.isDark ? AppColor.red50 : AppColor.red60));
            }
            return ASoundPlayer(audio: snapshot.data!.path);
          }
          return Container(
            width: 180,
            height: 180,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.withOpacity(.5), width: 1),
              image: snapshot.hasData ? DecorationImage(fit: BoxFit.contain, image: getImage(snapshot.data!)) : null,
            ),
            child: snapshot.connectionState == ConnectionState.waiting
                ? const SizedBox(
                    height: 24,
                    width: 24,
                    child: CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 2),
                  ).center
                : snapshot.hasData
                    ? getFile(context, snapshot.data!)
                    : const Icon(Icons.broken_image_rounded),
          );
        });
  }

  Widget getFile(BuildContext context, File file) {
    bool isImage = file.path.split(".").last.toLowerCase() == "png" || file.path.split(".").last.toLowerCase() == "jpg" || file.path.split(".").last.toLowerCase() == "jpeg";
    bool isPdf = file.path.split(".").last.toLowerCase() == "pdf";
    bool isExcel = file.path.split(".").last.toLowerCase() == "xlsx";

    return MaterialButton(
      padding: EdgeInsets.zero,
      onPressed: () async {
        if (isImage) {
          context.fullScreenImageViewer(Image.file(file));
        } else {
          OpenFile.open(file.path);
        }
        // else {
        //   // if (!await launchUrl(Uri.parse(URLs.getFileUrl(file.path)!), mode: LaunchMode.externalApplication)) {
        //   //   Fluttertoast.showToast(msg: "UnExpected Error with file.");
        //   //   throw Exception('Could not launch');
        //   // }
        // }
      },
    );
  }

  ImageProvider getImage(File file) {
    bool isImage = file.path.split(".").last.toLowerCase() == "png" || file.path.split(".").last.toLowerCase() == "jpg" || file.path.split(".").last.toLowerCase() == "jpeg";
    bool isPdf = file.path.split(".").last.toLowerCase() == "pdf";
    bool isExcel = file.path.split(".").last.toLowerCase() == "xlsx";

    if (isImage) {
      return FileImage(file);
    }
    return AssetImage("assets/images/${isPdf ? "pdf" : isExcel ? "excel" : "doc"}.png");
  }

  Future<File?> checkFileInLocalStorage() async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = '${tempDir.path}/${fileTypeResponse.fileName}';
    File tempFile = File(tempPath);
    bool exists = await tempFile.exists();
    if (exists) {
      return tempFile;
    } else {
      return downloadFile();
    }
  }

  Future<File?> downloadFile() async {
    try {
      // print("downloadUrl:$downloadUrl");
      return await ChatApiClient()
          .downloadFileWithHttp(downloadUrl, fileName: fileTypeResponse.fileName, fileTypeDescription: fileTypeResponse.fileTypeDescription ?? "", fileSource: fileTypeResponse.fileTypeId!);
    } catch (ex) {
      print("downloadFile:$ex");
      return null;
    }
  }
}
