import 'dart:convert';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/attachment_options.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_android/image_picker_android.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';

final ImagePicker picker = ImagePicker();
final ImagePickerPlatform _pickerPlatform = ImagePickerPlatform.instance;

class ImageOptions {
  static void showImageOptionsNew(
    BuildContext context,
    bool showFilesOption,
    Function(String, File) image, {
    String? title,
    Future<bool> Function()? checkCameraPermission,
    Future<bool> Function()? checkGalleryPermission,
  }) {
    showCommonBottomSheetWithoutHeight(
      context,
      title: title ?? LocaleKeys.profilePicture.tr(context: context),
      child: AttachmentOptions(
        showFilesOption: showFilesOption,
        onCameraTap: () async {
          // Check camera permission if callback provided
          if (checkCameraPermission != null) {
            final hasPermission = await checkCameraPermission();
            if (!hasPermission) {
              return; // Permission denied, don't proceed
            }
          }

          Navigator.pop(context); // Close bottom sheet

          if (Platform.isAndroid) {
            cameraImageAndroid(image);
          } else {
            XFile? pickedFile = await picker.pickImage(source: ImageSource.camera, imageQuality: 20);
            if (pickedFile == null) return;

            File _image = File(pickedFile.path);
            String fileName = _image.path;
            var bytes = File(fileName).readAsBytesSync();
            String base64Encode = base64.encode(bytes);
            image(base64Encode, _image);
          }
        },
        onGalleryTap: () async {
          // Check gallery permission if callback provided
          if (checkGalleryPermission != null) {
            final hasPermission = await checkGalleryPermission();
            if (!hasPermission) {
              return; // Permission denied, don't proceed
            }
          }

          Navigator.pop(context); // Close bottom sheet

          if (Platform.isAndroid) {
            galleryImageAndroid(image);
          } else {
            XFile? pickedFile = await picker.pickImage(source: ImageSource.gallery, imageQuality: 20);
            if (pickedFile == null) return;

            File _image = File(pickedFile.path);
            String fileName = _image.path;
            var bytes = File(fileName).readAsBytesSync();
            String base64Encode = base64.encode(bytes);
            image(base64Encode, _image);
          }
        },
        onFilesTap: () async {
          FilePickerResult? result = await FilePicker.platform.pickFiles(
            type: FileType.custom,
            allowedExtensions: [
              'jpg',
              'jpeg',
              'pdf',
              'txt',
              'docx',
              'doc',
              'pptx',
              'xlsx',
              'png',
              'rar',
              'zip',
            ],
          );
          if (result == null) return;
          List<File> files = result.paths.map((path) => File(path!)).toList();
          image(result.files.first.path.toString(), files.first);
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
    );
    // showMyBottomSheet(
    //   context,
    //   callBackFunc: () {},
    //   child: AttachmentOptions(
    //     showFilesOption: showFilesOption,
    //     onCameraTap: () async {
    //       if (Platform.isAndroid) {
    //         cameraImageAndroid(image);
    //       } else {
    //         File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 20))?.path ?? "");
    //         // XFile? media = await picker.pickMedia();
    //         String? fileName = _image.path;
    //         var bytes = File(fileName!).readAsBytesSync();
    //         String base64Encode = base64.encode(bytes);
    //         if (base64Encode != null) {
    //           image(base64Encode, _image);
    //         }
    //       }
    //     },
    //     onGalleryTap: () async {
    //       if (Platform.isAndroid) {
    //         galleryImageAndroid(image);
    //       } else {
    //         File _image = File((await picker.pickMedia())?.path ?? "");
    //         String fileName = _image.path;
    //         var bytes = File(fileName).readAsBytesSync();
    //         String base64Encode = base64.encode(bytes);
    //         if (base64Encode != null) {
    //           image(base64Encode, _image);
    //         }
    //       }
    //     },
    //     onFilesTap: () async {
    //       FilePickerResult? result = await FilePicker.platform.pickFiles(
    //         type: FileType.custom,
    //         allowedExtensions: [
    //           'jpg',
    //           'jpeg ',
    //           'pdf',
    //           'txt',
    //           'docx',
    //           'doc',
    //           'pptx',
    //           'xlsx',
    //           'png',
    //           'rar',
    //           'zip',
    //         ],
    //       );
    //       List<File> files = result!.paths.map((path) => File(path!)).toList();
    //       image(result.files.first.path.toString(), files.first);
    //     },
    //   ),
    // );
  }

// static void showImageOptions(BuildContext context, Function(String, File) image) {
//   showModalBottomSheet(
//       backgroundColor: Colors.transparent,
//       context: context,
//       builder: (BuildContext bc) {
//         return _BottomSheet(
//           children: <Widget>[
//             _BottomSheetItem(
//               title: "Select File Source",
//               onTap: () {},
//               icon: Icons.file_present,
//               color: MyColors.black,
//             ),
//             _BottomSheetItem(
//               title: "Gallery",
//               icon: Icons.image,
//               onTap: () async {
//                 if (Platform.isAndroid) {
//                   galleryImageAndroid(image);
//                 } else {
//                   File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 10))?.path ?? "");
//                   String fileName = _image.path;
//                   var bytes = File(fileName).readAsBytesSync();
//                   String base64Encode = base64.encode(bytes);
//                   if (base64Encode != null) {
//                     image(base64Encode, _image);
//                   }
//                 }
//               },
//             ),
//             _BottomSheetItem(
//               title: "Camera",
//               icon: Icons.camera_alt,
//               onTap: () async {
//                 if (Platform.isAndroid) {
//                   cameraImageAndroid(image);
//                 } else {
//                   File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 10))?.path ?? "");
//                   String fileName = _image.path;
//                   var bytes = File(fileName).readAsBytesSync();
//                   String base64Encode = base64.encode(bytes);
//                   if (base64Encode != null) {
//                     image(base64Encode, _image);
//                   }
//                 }
//               },
//             ),
//             _BottomSheetItem(
//               title: "Cancel",
//               onTap: () {},
//               icon: Icons.cancel,
//               color: MyColors.redColor,
//             )
//           ],
//         );
//       });
// }
}

void galleryImageAndroid(Function(String, File) image) async {
  // Enable Android Photo Picker if available
  if (_pickerPlatform is ImagePickerAndroid) {
    (_pickerPlatform as ImagePickerAndroid).useAndroidPhotoPicker = true;
  }

  try {
    final XFile? pickedFile =
        await _pickerPlatform.getImageFromSource(source: ImageSource.gallery, options: const ImagePickerOptions(imageQuality: 20));

    if (pickedFile == null) return;

    File _image = File(pickedFile.path);
    String fileName = _image.path;
    var bytes = File(fileName).readAsBytesSync();
    String base64Encode = base64.encode(bytes);
    image(base64Encode, _image);
  } catch (e) {
    print('Error picking image: $e');
  }
}

void cameraImageAndroid(Function(String, File) image) async {
  if (_pickerPlatform is ImagePickerAndroid) {
    (_pickerPlatform as ImagePickerAndroid).useAndroidPhotoPicker = true;
  }

  try {
    final XFile? pickedFile = await _pickerPlatform.getImageFromSource(
      source: ImageSource.camera,
      options: const ImagePickerOptions(imageQuality: 20),
    );

    if (pickedFile == null) return;

    File _image = File(pickedFile.path);
    String fileName = _image.path;
    var bytes = File(fileName).readAsBytesSync();
    String base64Encode = base64.encode(bytes);
    image(base64Encode, _image);
  } catch (e) {
    print('Error taking picture: $e');
  }
}

class _BottomSheet extends StatelessWidget {
  final List<Widget> children;

  const _BottomSheet({Key? key, required this.children}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12.0),
      decoration: BoxDecoration(
          color: Theme.of(context).scaffoldBackgroundColor,
          borderRadius: const BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0))),
      child: SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(color: Theme.of(context).dividerColor, borderRadius: BorderRadius.circular(3.0)),
              width: 40.0,
              height: 6.0,
            ),
            ...children
          ],
        ),
      ),
    );
  }
}

class _BottomSheetItem extends StatelessWidget {
  final Function onTap;
  final IconData icon;
  final String title;
  final Color? color;

  _BottomSheetItem({Key? key, required this.onTap, required this.title, required this.icon, this.color}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final resolvedColor = color ?? AppColors.mainPurple;
    return InkWell(
      onTap: () {
        if (onTap != null) {
          Navigator.pop(context);
          onTap();
        }
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 18.0, vertical: 18.0),
        child: Row(
          children: <Widget>[
            if (icon != null)
              Icon(
                icon,
                color: resolvedColor,
                size: 18.0,
              ),
            if (icon != null) const SizedBox(width: 24.0),
            title.toText17(),
          ],
        ),
      ),
    );
  }
}
