import 'dart:io';

import 'package:ellipsized_text/ellipsized_text.dart';
import 'package:flutter/gestures.dart';
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/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/new_views/app_style/app_color.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 List<String> types;
  final EdgeInsets? padding;
  final bool showAsListView;
  final bool showDownloadButton;
  final double? itemGap;
  final Widget? separator;

  const FilesList({Key? key, this.separator, this.images = const <String>[], this.types = const <String>[], this.padding, this.showAsListView = false, this.showDownloadButton = false, this.itemGap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return showAsListView
        ? ListView.separated(
            shrinkWrap: true,
            padding: padding ?? EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (cxt, 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 Row(
                spacing: 8,
                children: [
                  Container(
                    width: 48.toScreenWidth,
                    height: 48.toScreenWidth,
                    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")),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      EllipsizedText(
                        images[itemIndex].split("/").last,
                        style: AppTextStyles.bodyText.copyWith(color: AppColor.textStyleColor(context)),
                        type: EllipsisType.start, // or EllipsisType.middle
                      ),
                      2.height,
                      RichText(
                        text: TextSpan(
                          text: '${types.isEmpty ? "Asset Guide" : types[itemIndex]} | ',
                          style: AppTextStyles.tinyFont.copyWith(color: AppColor.labelTextStyleColor(context)),
                          children: <TextSpan>[
                            TextSpan(
                              text: 'View',
                              recognizer: TapGestureRecognizer()
                                ..onTap = () async {
                                  if (isImage) {
                                    context.fullScreenImageViewer(getImageWidget(itemIndex));
                                  } 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.");
                                    }
                                  }
                                },
                              style: AppTextStyles.bodyText.copyWith(color: AppColor.primary10, decoration: TextDecoration.underline),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ).expanded,
                  if (showDownloadButton)
                    IconButton(
                      icon: "download".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)),
                      padding: EdgeInsets.zero,
                      visualDensity: VisualDensity.compact,
                      tooltip: "Download",
                      onPressed: () async {
                        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.");
                        }
                        // if (Utils.isLocalFile(images[itemIndex])) {
                        //   await OpenFile.open(images[itemIndex]);
                        // } else {
                        //   await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true);
                        // }
                      },
                    ),
                ],
              );
            },
            separatorBuilder: (cxt, index) => separator ?? SizedBox(height: itemGap ?? 8.toScreenHeight),
            itemCount: images.length)
        : GridView.builder(
            padding: 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) {
                  context.fullScreenImageViewer(getImageWidget(itemIndex));
                } 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(':\\');
  }
}
