import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/views/widgets/buttons/app_back_button.dart';
import 'package:test_sa/views/widgets/loaders/image_loader.dart';
import 'package:url_launcher/url_launcher.dart';

class FilesList extends StatelessWidget {
  final List<String> images;
  final EdgeInsets? padding;

  const FilesList({Key? key, this.images = const <String>[], this.padding}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.only(top: 8, bottom: 8),
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 6, mainAxisSpacing: 8, crossAxisSpacing: 8),
      itemCount: images.length,
      itemBuilder: (context, itemIndex) {
        if (!images[itemIndex].contains(".")) {
          return const Text("Bad\nFile");
        }
        var isImage = images[itemIndex].split(".").last.toLowerCase() == "png" || images[itemIndex].split(".").last.toLowerCase() == "jpg" || images[itemIndex].split(".").last.toLowerCase() == "jpeg";
        var isPdf = images[itemIndex].split(".").last.toLowerCase() == "pdf";
        var isExcel = images[itemIndex].split(".").last.toLowerCase() == "xlsx";

        return Container(
          decoration: ShapeDecoration(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              side: const BorderSide(width: 1, color: Color(0xFFEAF1F4)),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: (isImage
                ? (_isLocalUrl(images[itemIndex])
                    ? Image.file(File(images[itemIndex]))
                    : ImageLoader(
                        url: images[itemIndex],
                        boxFit: BoxFit.cover,
                        height: 48,
                        width: 48,
                      ))
                : Image.asset("assets/images/${isPdf ? "pdf" : isExcel ? "excel" : "doc"}.png")),
          ),
        ).onPress(() async {
          if (isImage) {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (_) => Scaffold(
                  body: SafeArea(
                    child: Stack(
                      children: [
                        // InteractiveViewer(child: Image(image: getImageObject(itemIndex))).center,
                        InteractiveViewer(child: getImageWidget(itemIndex)).center,
                        const ABackButton(),
                      ],
                    ),
                  ),
                ),
              ),
            );
          } else if (_isLocalUrl(images[itemIndex])) {
            OpenFile.open(images[itemIndex]);
          } else {
            try {
              if (!await launchUrl(Uri.parse(images[itemIndex]), mode: LaunchMode.externalApplication)) {
                Fluttertoast.showToast(msg: "UnExpected Error with file.");
                throw Exception('Could not launch ');
              }
            } catch (ex) {
              Fluttertoast.showToast(msg: "No Viewer found.");
            }
          }
        });
      },
    );

    // return ListView.separated(
    //     padding: padding ?? EdgeInsets.symmetric(horizontal: 32 * AppStyle.getScaleFactor(context)),
    //     scrollDirection: Axis.horizontal,
    //     itemCount: images?.length ?? 0,
    //     separatorBuilder: (context, itemIndex) => 8.width,
    //     itemBuilder: (context, itemIndex) {
    //       if (images[itemIndex] == null || !images[itemIndex].contains(".")) {
    //         return Text("Bad\nFile");
    //       }
    //       var isImage =
    //           images[itemIndex].split(".").last.toLowerCase() == "png" || images[itemIndex].split(".").last.toLowerCase() == "jpg" || images[itemIndex].split(".").last.toLowerCase() == "jpeg";
    //       var isPdf = images[itemIndex].split(".").last.toLowerCase() == "pdf";
    //       var isExcel = images[itemIndex].split(".").last.toLowerCase() == "xlsx";
    //
    //       return (isImage
    //               ? (_isLocalUrl(images[itemIndex])
    //                   ? Image.file(File(images[itemIndex]))
    //                   : ImageLoader(
    //                       url: images[itemIndex],
    //                       boxFit: BoxFit.cover,
    //                     ))
    //               : Image.asset("assets/images/${isPdf ? "pdf" : isExcel ? "excel" : "doc"}.png"))
    //           .onPress(() async {
    //         if (isImage) {
    //           Navigator.of(context).push(
    //             MaterialPageRoute(
    //               builder: (_) => Scaffold(
    //                 body: SafeArea(
    //                   child: Stack(
    //                     children: [
    //                       InteractiveViewer(child: Image(image: (_isLocalUrl(images[itemIndex]) ? FileImage(File(images[itemIndex])) : NetworkImage(images[itemIndex])))).center,
    //                       const ABackButton(),
    //                     ],
    //                   ),
    //                 ),
    //               ),
    //             ),
    //           );
    //         } else if (_isLocalUrl(images[itemIndex])) {
    //           OpenFile.open(images[itemIndex]);
    //         } else {
    //           try {
    //             if (!await launchUrl(Uri.parse(images[itemIndex]), mode: LaunchMode.externalApplication)) {
    //               Fluttertoast.showToast(msg: "UnExpected Error with file.");
    //               throw Exception('Could not launch ');
    //             }
    //           } catch (ex) {
    //             Fluttertoast.showToast(msg: "No Viewer found.");
    //           }
    //         }
    //       });
    //     });
  }

  Widget getImageWidget(int itemIndex) {
    if (_isLocalUrl(images[itemIndex])) {
      return Image.file(File(images[itemIndex]));
    }
    return ImageLoader(url: images[itemIndex]);
  }

  ImageProvider getImageObject(int itemIndex) {
    if (_isLocalUrl(images[itemIndex])) {
      return FileImage(File(images[itemIndex]));
    }
    return NetworkImage(images[itemIndex]);
  }

  ImageProvider getImage(bool isImage, bool isPdf, bool isExcel, File file) {
    if (isImage) {
      if (_isLocalUrl(file.path)) {
        return FileImage(file);
      }
      return NetworkImage(URLs.getFileUrl(file.path)!);
    }
    return AssetImage("assets/images/${isPdf ? "pdf" : isExcel ? "excel" : "doc"}.png");
  }

  bool _isLocalUrl(String url) {
    if (url.isEmpty != false) return false;
    return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\');
  }
}
