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/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/loaders/image_loader.dart';
import 'package:url_launcher/url_launcher.dart';

class MultiFilesPickerItem extends StatelessWidget {
  final File file;
  final bool enabled;
  final Function(File) onRemoveTap;
  final VoidCallback? onRemove;
  final bool showAsListView;
  final String? documentType;

  const MultiFilesPickerItem({
    Key? key,
    required this.file,
    required this.enabled,
    required this.onRemoveTap,
    this.onRemove,
    this.documentType,
    this.showAsListView = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    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 (showAsListView) {
      return Row(
        children: [
          Container(
            width: 48.toScreenWidth,
            height: 48.toScreenWidth,
            decoration: BoxDecoration(
              color: AppColor.neutral90,
              border: Border.all(width: 1, color: context.isDark ? AppColor.neutral30 : AppColor.neutral30),
              image: DecorationImage(
                image: getImage(isImage, isPdf, isExcel, file),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          8.width,
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Flexible(
                    child: EllipsizedText(
                      file.path.split("/").last,
                      style: AppTextStyles.bodyText.copyWith(color: AppColor.labelTextStyleColor(context)),
                      type: EllipsisType.start, // or EllipsisType.middle
                    ),
                  ),
                  8.width,
                  if (enabled)
                    IconButton(
                      padding: EdgeInsets.zero,
                      icon: const Icon(Icons.clear),
                      iconSize: 18,
                      style: IconButton.styleFrom(elevation: 2, tapTargetSize: MaterialTapTargetSize.shrinkWrap, backgroundColor: AppColor.red30, foregroundColor: Colors.white),
                      visualDensity: VisualDensity.compact,
                      constraints: const BoxConstraints(),
                      onPressed: () {
                        onRemoveTap(file);
                        if (onRemove != null) {
                          onRemove!();
                        }
                      },
                    ),
                ],
              ),
              4.height,
              RichText(
                text: TextSpan(
                  text: documentType == null ? 'Asset Guide | ' : '$documentType | ',
                  style: AppTextStyles.bodyText.copyWith(color: AppColor.lightTextColor(context)),
                  children: <TextSpan>[
                    TextSpan(
                      text: 'View',
                      recognizer: TapGestureRecognizer()
                        ..onTap = () async {
                          if (isImage) {
                            context.fullScreenImageViewer(_isLocalUrl(file.path)
                                ? Image.file(file)
                                : ImageLoader(
                                    url: URLs.getFileUrl(file.path),
                                    boxFit: BoxFit.cover,
                                  ));
                          } else if (_isLocalUrl(file.path)) {
                            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');
                            }
                          }
                        },
                      style: AppTextStyles.bodyText.copyWith(color: AppColor.primary10, decoration: TextDecoration.underline),
                    ),
                  ],
                ),
              ),
            ],
          ).expanded
        ],
      );
    }

    return SizedBox(
      width: 60.toScreenWidth,
      height: 60.toScreenWidth,
      child: Stack(
        alignment: AlignmentDirectional.topEnd,
        children: [
          Container(
            margin: EdgeInsetsDirectional.only(top: 4.toScreenHeight, end: 6.toScreenWidth),
            decoration: BoxDecoration(
              color: AppColor.neutral90,
              border: Border.all(width: 1, color: context.isDark ? AppColor.neutral30 : AppColor.neutral30),
              image: DecorationImage(
                image: getImage(isImage, isPdf, isExcel, file),
                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.circular(8),
            ),
            child: MaterialButton(
              padding: EdgeInsets.zero,
              onPressed: () async {
                if (isImage) {
                  context.fullScreenImageViewer(_isLocalUrl(file.path)
                      ? Image.file(file)
                      : ImageLoader(
                          url: URLs.getFileUrl(file.path),
                          boxFit: BoxFit.cover,
                        ));
                } else if (_isLocalUrl(file.path)) {
                  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');
                  }
                }
              },
            ),
          ),
          if (enabled)
            IconButton(
              padding: EdgeInsets.zero,
              icon: const Icon(Icons.clear),
              iconSize: 18,
              style: IconButton.styleFrom(elevation: 2, tapTargetSize: MaterialTapTargetSize.shrinkWrap, backgroundColor: AppColor.red30, foregroundColor: Colors.white),
              visualDensity: VisualDensity.compact,
              constraints: const BoxConstraints(),
              onPressed: () {
                onRemoveTap(file);
                if (onRemove != null) {
                  onRemove!();
                }
              },
            )
        ],
      ),
    );
  }

  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(':\\');
  }
}
