import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.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/models/generic_attachment_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';

class ChatFilePicker extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        "Attach File".heading4(context),
        12.height,
        GridView(
          padding: const EdgeInsets.all(0),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 12, mainAxisSpacing: 12),
          children: <Widget>[
            gridItem(context, Icons.camera_enhance_rounded, context.translation.pickFromCamera).onPress(() async {
              await fromMediaPicker(context, ImageSource.camera);
            }),
            gridItem(context, Icons.image_rounded, context.translation.pickFromGallery).onPress(() async {
              await fromMediaPicker(context, ImageSource.gallery);
            }),
            gridItem(context, Icons.file_present_rounded, context.translation.pickFromFiles).onPress(() async {
              await fromFilePicker(context);
            }),
          ],
        ),
        12.height,
      ],
    ).paddingAll(21);
  }

  fromMediaPicker(BuildContext context, ImageSource imageSource) async {
    XFile? pickedFile = await ImagePicker().pickImage(source: imageSource, imageQuality: 70, maxWidth: 800, maxHeight: 800);
    if (pickedFile != null) {
      //Has UI issues here  top buttons not clickable smoothly
      CroppedFile? croppedFile = await ImageCropper().cropImage(
        sourcePath: pickedFile.path,
        // aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: 'ATOMS',
            toolbarColor: Colors.white,
            toolbarWidgetColor: context.settingProvider.theme == "dark" ? AppColor.neutral10 : AppColor.neutral50,
            initAspectRatio: CropAspectRatioPreset.square,
            lockAspectRatio: false,
          ),
          IOSUiSettings(title: 'ATOMS'),
        ],
      );
      if (croppedFile != null) {
        Navigator.pop(context, File(croppedFile.path));
        return;
      }
    }
    Navigator.pop(context);
  }

  fromFilePicker(BuildContext context) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xlsx', 'pptx', 'txt'],
    );
    if ((result?.paths ?? []).isNotEmpty) {
      Navigator.pop(context, File(result!.paths.first!));
    } else {
      Navigator.pop(context);
    }
  }

  Widget gridItem(BuildContext context, IconData iconData, String title) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColor.borderColor(context), width: 2),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Icon(iconData, color: AppColor.icon2Color(context), size: 36),
          title.bodyText2(context).custom(color: AppColor.labelTextStyleColor(context), fontSize: context.isTablet() ? 10.toScreenWidth : null),
        ],
      ),
    );
  }

// static Future<File?> selectFile(BuildContext context) async {
//   ImageSource source = (await showModalBottomSheet(
//       context: context,
//       shape: const RoundedRectangleBorder(
//         borderRadius: BorderRadius.vertical(
//           top: Radius.circular(20),
//         ),
//       ),
//       clipBehavior: Clip.antiAliasWithSaveLayer,
//       builder: (BuildContext context) => ChatFilePicker())) as ImageSource;
//
//   final pickedFile = await ImagePicker().pickImage(source: source, imageQuality: 70, maxWidth: 800, maxHeight: 800);
// }
}

// class AttachmentPicker extends StatefulWidget {
//   final String label;
//   final bool error;
//   final List<GenericAttachmentModel> attachment;
//
//   final bool enabled, onlyImages;
//   double? buttonHeight;
//   Widget? buttonIcon;
//   Color? buttonColor;
//   final Function(List<GenericAttachmentModel>)? onChange;
//   final bool showAsGrid;
//
//   AttachmentPicker(
//       {Key? key,
//       this.attachment = const <GenericAttachmentModel>[],
//       required this.label,
//       this.error = false,
//       this.buttonHeight,
//       this.buttonIcon,
//       this.enabled = true,
//       this.onlyImages = false,
//       this.onChange,
//       this.showAsGrid = false,
//       this.buttonColor})
//       : super(key: key);
//
//   @override
//   State<AttachmentPicker> createState() => _AttachmentPickerState();
// }
//
// class _AttachmentPickerState extends State<AttachmentPicker> {
//   @override
//   Widget build(BuildContext context) {
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.start,
//       children: [
//         AppDashedButton(
//             title: widget.label,
//             height: widget.buttonHeight,
//             buttonColor: widget.buttonColor,
//             icon: widget.buttonIcon,
//             onPressed: (widget.enabled == false)
//                 ? () {}
//                 : widget.showAsGrid
//                     ? showFileSourceSheet
//                     : onFilePicker),
//         16.height,
//         if (widget.attachment.isNotEmpty)
//           Wrap(
//             spacing: 8.toScreenWidth,
//             children: List.generate(
//               widget.attachment.length,
//               (index) {
//                 File image = File(widget.attachment[index].name!);
//                 return MultiFilesPickerItem(
//                   file: image,
//                   enabled: widget.enabled,
//                   onRemoveTap: (image) {
//                     if (!widget.enabled) {
//                       return;
//                     }
//                     widget.attachment.removeAt(index);
//                     if (widget.onChange != null) {
//                       widget.onChange!(widget.attachment);
//                     }
//                     setState(() {});
//                   },
//                 );
//               },
//             ),
//           ),
//       ],
//     );
//   }
//
//   fromFilePicker() async {
//     FilePickerResult? result = await FilePicker.platform.pickFiles(
//       type: FileType.custom,
//       allowMultiple: true,
//       allowedExtensions: widget.onlyImages ? ['jpg', 'jpeg', 'png'] : ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'xlsx', 'pptx'],
//     );
//     if (result != null) {
//       for (var path in result.paths) {
//         widget.attachment.add(GenericAttachmentModel(id: 0, name: File(path!).path));
//       }
//       if (widget.onChange != null) {
//         widget.onChange!(widget.attachment);
//       }
//       setState(() {});
//     }
//   }
//
//   void showFileSourceSheet() async {
//     // if (widget.attachment.length >= 5) {
//     //   Fluttertoast.showToast(msg: context.translation.maxImagesNumberIs5);
//     //   return;
//     // }
//
//     ImageSource source = (await showModalBottomSheet(
//       context: context,
//       shape: const RoundedRectangleBorder(
//         borderRadius: BorderRadius.vertical(
//           top: Radius.circular(20),
//         ),
//       ),
//       clipBehavior: Clip.antiAliasWithSaveLayer,
//       builder: (BuildContext context) => Column(
//         mainAxisSize: MainAxisSize.min,
//         crossAxisAlignment: CrossAxisAlignment.start,
//         children: [
//           "Attach File".heading4(context),
//           12.height,
//           GridView(
//             padding: const EdgeInsets.all(0),
//             shrinkWrap: true,
//             physics: const NeverScrollableScrollPhysics(),
//             gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 12, mainAxisSpacing: 12),
//             children: <Widget>[
//               gridItem(Icons.camera_enhance_rounded, context.translation.pickFromCamera).onPress(() => Navigator.of(context).pop(ImageSource.camera)),
//               gridItem(Icons.image_rounded, context.translation.pickFromGallery).onPress(() => Navigator.of(context).pop(ImageSource.gallery)),
//               gridItem(Icons.file_present_rounded, context.translation.pickFromFiles).onPress(() async {
//                 await fromFilePicker();
//                 Navigator.pop(context);
//               }),
//             ],
//           ),
//           12.height,
//         ],
//       ).paddingAll(21),
//     )) as ImageSource;
//
//     final pickedFile = await ImagePicker().pickImage(source: source, imageQuality: 70, maxWidth: 800, maxHeight: 800);
//
//     if (pickedFile != null) {
//       File fileImage = File(pickedFile.path);
//       widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path));
//       if (widget.onChange != null) {
//         widget.onChange!(widget.attachment);
//       }
//       setState(() {});
//     }
//   }
//
//   Widget gridItem(IconData iconData, String title) {
//     return Container(
//       padding: const EdgeInsets.all(12),
//       decoration: BoxDecoration(
//         color: Colors.white,
//         borderRadius: BorderRadius.circular(12),
//         border: Border.all(color: const Color(0xffF1F1F1), width: 1),
//       ),
//       child: Column(
//         crossAxisAlignment: CrossAxisAlignment.start,
//         mainAxisAlignment: MainAxisAlignment.spaceBetween,
//         children: [
//           Icon(iconData, color: const Color(0xff7D859A), size: 36),
//           Text(
//             title,
//             style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
//           ),
//         ],
//       ),
//     );
//   }
//
//   onFilePicker() async {
//     //TODO removed on request by Backend as they don't have anyissue with large number of files
//     // if (widget.attachment.length >= 5) {
//     //   Fluttertoast.showToast(msg: context.translation.maxImagesNumberIs5);
//     //   return;
//     // }
//     ImageSource? source = await showModalBottomSheet<ImageSource>(
//       context: context,
//       builder: (BuildContext context) {
//         Widget listCard({required String icon, required String label, required VoidCallback onTap}) {
//           return Container(
//             padding: const EdgeInsets.all(12),
//             decoration: BoxDecoration(
//               color: AppColor.background(context),
//               // color: Colors.white,
//               borderRadius: BorderRadius.circular(12),
//               border: Border.all(color: const Color(0xffF1F1F1), width: 1),
//             ),
//             child: Column(
//               crossAxisAlignment: CrossAxisAlignment.start,
//               mainAxisAlignment: MainAxisAlignment.spaceBetween,
//               children: [
//                 icon.toSvgAsset(color: AppColor.iconColor(context), width: 36, height: 36),
//                 // Icon(iconData, color: const Color(0xff7D859A), size: 36),
//                 Text(
//                   label,
//                   style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
//                 ),
//               ],
//             ),
//           ).onPress(onTap);
//         }
//
//         return SafeArea(
//           top: false,
//           child: Container(
//             width: double.infinity,
//             color: AppColor.background(context),
//             child: Column(
//               mainAxisSize: MainAxisSize.min,
//               crossAxisAlignment: CrossAxisAlignment.start,
//               children: [
//                 "Attach File".heading4(context),
//                 12.height,
//                 GridView(
//                   padding: const EdgeInsets.all(0),
//                   shrinkWrap: true,
//                   physics: const NeverScrollableScrollPhysics(),
//                   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 12, mainAxisSpacing: 12),
//                   children: <Widget>[
//                     listCard(
//                       icon: 'camera_icon',
//                       label: '${context.translation.open}\n${context.translation.camera}',
//                       onTap: () {
//                         Navigator.of(context).pop(ImageSource.camera);
//                       },
//                     ),
//                     listCard(
//                       icon: 'gallery_icon',
//                       label: '${context.translation.open}\n${context.translation.gallery}',
//                       onTap: () {
//                         Navigator.of(context).pop(ImageSource.gallery);
//                       },
//                     ),
//                     listCard(
//                       icon: 'file_icon',
//                       label: '${context.translation.open}\n${context.translation.files}',
//                       onTap: () async {
//                         await fromFilePicker();
//                         Navigator.pop(context);
//                       },
//                     ),
//                   ],
//                 ),
//                 // Container(
//                 //   padding: const EdgeInsets.all(16.0),
//                 //   child: Row(
//                 //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                 //     children: <Widget>[
//                 //       listCard(
//                 //         icon: 'camera_icon',
//                 //         label: '${context.translation.open}\n${context.translation.camera}',
//                 //         onTap: () {
//                 //           Navigator.of(context).pop(ImageSource.camera);
//                 //         },
//                 //       ),
//                 //       listCard(
//                 //         icon: 'gallery_icon',
//                 //         label: '${context.translation.open}\n${context.translation.gallery}',
//                 //         onTap: () {
//                 //           Navigator.of(context).pop(ImageSource.gallery);
//                 //         },
//                 //       ),
//                 //       listCard(
//                 //         icon: 'file_icon',
//                 //         label: '${context.translation.open}\n${context.translation.files}',
//                 //         onTap: () async {
//                 //           await fromFilePicker();
//                 //           Navigator.pop(context);
//                 //         },
//                 //       ),
//                 //     ],
//                 //   ),
//                 // ),
//               ],
//             ).paddingAll(16),
//           ),
//         );
//       },
//     );
//     // ImageSource source = await showDialog(
//     //   context: context,
//     //   builder: (dialogContext) => CupertinoAlertDialog(
//     //     actions: <Widget>[
//     //       TextButton(
//     //         child: Text(context.translation.pickFromCamera),
//     //         onPressed: () {
//     //           Navigator.of(dialogContext).pop(ImageSource.camera);
//     //         },
//     //       ),
//     //       TextButton(
//     //         child: Text(context.translation.pickFromGallery),
//     //         onPressed: () {
//     //           Navigator.of(dialogContext).pop(ImageSource.gallery);
//     //         },
//     //       ),
//     //       TextButton(
//     //         child: Text(context.translation.pickFromFiles),
//     //         onPressed: () async {
//     //           await fromFilePicker();
//     //           Navigator.pop(context);
//     //         },
//     //       ),
//     //     ],
//     //   ),
//     // );
//     if (source == null) return;
//
//     final pickedFile = await ImagePicker().pickImage(source: source, imageQuality: 70, maxWidth: 800, maxHeight: 800);
//
//     if (pickedFile != null) {
//       File fileImage = File(pickedFile.path);
//       widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path));
//       if (widget.onChange != null) {
//         widget.onChange!(widget.attachment);
//       }
//       setState(() {});
//     }
//
//     setState(() {});
//   }
// }
