import 'dart:io';

import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_pos/GlobalComponents/button_global.dart';
import 'package:mobile_pos/Provider/profile_provider.dart';
import 'package:mobile_pos/currency.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';
import 'package:path/path.dart' as path;

import '../../constant.dart';
import '../../model/personal_information_model.dart';

class PrintingInvoiceScreen extends ConsumerStatefulWidget {
  const PrintingInvoiceScreen({super.key});

  @override
  ConsumerState<PrintingInvoiceScreen> createState() => _PrintingInvoiceScreenState();
}

class _PrintingInvoiceScreenState extends ConsumerState<PrintingInvoiceScreen> {
  TextEditingController addressController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController gstOrTinController = TextEditingController();
  final Map<String, String> invoiceSizeOptions = {
    '3 Inch (80 mm)': '3 inch 80mm',
    '2 Inch (58 mm)': '2 inch 58mm',
  };

  bool printing = false;
  final ImagePicker _picker = ImagePicker();
  XFile? pickedImage;
  File? imageFile;
  final GlobalKey<FormState> _formKey = GlobalKey();
  String? selectedThermalPrinter;
  bool _isUpdating = false;
  final String _defaultProfilePicUrl =
      'https://firebasestorage.googleapis.com/v0/b/maanpos.appspot.com/o/Profile%20Picture%2Fblank-profile-picture-973460_1280.webp?alt=media&token=3578c1e0-7278-4c03-8b56-dd007a9befd3';

  @override
  void initState() {
    super.initState();
    printing = isPrintEnable;

    final profileData = ref.read(profileDetailsProvider);
    if (profileData.value != null) {
      _initializeFields(profileData.value!);
    } else {
      profileData.when(
        data: (data) => _initializeFields(data),
        error: (error, stackTrace) {
          // Handle error if needed
        },
        loading: () {
          // Show loading if needed
        },
      );
    }
  }

  void _initializeFields(PersonalInformationModel data) {
    setState(() {
      nameController.text = data.companyName ?? '';
      phoneController.text = data.phoneNumber ?? '';
      addressController.text = data.countryName ?? '';
      gstOrTinController.text = data.gstOrTinNameType ?? '';
      selectedThermalPrinter = data.thermalPrinterPrintSize ?? '3_inch_80mm';
    });
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      pickedImage = await _picker.pickImage(source: source);
      if (pickedImage != null) {
        setState(() {
          imageFile = File(pickedImage!.path);
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to pick image: ${e.toString()}')),
        );
      }
    }
  }

  Future<void> _updateProfile() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isUpdating = true);

    try {
      final profileData = ref.read(profileDetailsProvider).value;
      if (profileData == null) return;

      // Upload image if selected
      String? imageUrl;
      if (imageFile != null) {
        imageUrl = await _uploadImage(imageFile!);
      }

      // Create updated model
      final updatedModel = PersonalInformationModel(
        // id: profileData.id,
        phoneNumber: phoneController.text.trim(),
        companyName: nameController.text.trim(),
        pictureUrl: imageUrl ?? profileData.pictureUrl ?? _defaultProfilePicUrl,
        businessCategory: profileData.businessCategory,
        language: profileData.language,
        countryName: addressController.text.trim(),
        saleInvoiceCounter: profileData.saleInvoiceCounter,
        purchaseInvoiceCounter: profileData.purchaseInvoiceCounter,
        dueInvoiceCounter: profileData.dueInvoiceCounter,
        shopOpeningBalance: profileData.shopOpeningBalance,
        remainingShopBalance: profileData.remainingShopBalance,
        currency: profileData.currency,
        gstOrTinNameType: gstOrTinController.text.trim(),
        thermalPrinterPrintSize: selectedThermalPrinter,
        gst: profileData.gst,
      );

      // Update in Firebase
      await FirebaseDatabase.instance
          .ref('$constUserId/Personal Information')
          .update(updatedModel.toJson());

      // Update local preferences
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('isPrintEnable', printing);
      isPrintEnable = printing;

      // Refresh provider
      ref.refresh(profileDetailsProvider);

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Profile updated successfully')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to update profile: ${e.toString()}')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isUpdating = false);
      }
    }
  }

  Future<String> _uploadImage(File image) async {
    try {
      final fileName = path.basename(image.path);
      final ref = FirebaseStorage.instance
          .ref()
          .child('Profile Picture')
          .child(constUserId)
          .child(fileName);

      await ref.putFile(image);
      return await ref.getDownloadURL();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to upload image: ${e.toString()}')),
        );
      }
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final _lang = lang.S.of(context);

    return Scaffold(
      backgroundColor: kWhite,
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.black),
        title: const Text('Print Invoice'),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0.0,
      ),
      body: Padding(
        padding: const EdgeInsets.all(15.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Invoice Logo', style: theme.textTheme.bodyLarge),
              const SizedBox(height: 10),
              Center(
                child: GestureDetector(
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return Dialog(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.0),
                          ),
                          child: Container(
                            height: 200.0,
                            width: MediaQuery.of(context).size.width - 80,
                            child: Center(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      Navigator.pop(context);
                                      _pickImage(ImageSource.gallery);
                                    },
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        const Icon(Icons.photo_library_rounded,
                                            size: 60.0, color: kMainColor),
                                        Text('Gallery',
                                            style: theme.textTheme.titleMedium
                                                ?.copyWith(color: kGreyTextColor)),
                                      ],
                                    ),
                                  ),
                                  const SizedBox(width: 40.0),
                                  GestureDetector(
                                    onTap: () {
                                      Navigator.pop(context);
                                      _pickImage(ImageSource.camera);
                                    },
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        const Icon(Icons.camera,
                                            size: 60.0, color: kGreyTextColor),
                                        Text('Camera',
                                            style: theme.textTheme.titleMedium
                                                ?.copyWith(color: kGreyTextColor)),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                  child: Stack(
                    children: [
                      Container(
                        height: 120,
                        width: 120,
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black54, width: 1),
                          borderRadius: const BorderRadius.all(Radius.circular(120)),
                          image: _getDecorationImage(),
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        right: 0,
                        child: Container(
                          height: 35,
                          width: 35,
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.white, width: 2),
                            borderRadius: const BorderRadius.all(Radius.circular(120)),
                            color: kMainColor,
                          ),
                          child:
                              const Icon(Icons.camera_alt_outlined, size: 20, color: Colors.white),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 20.0),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    AppTextField(
                      controller: nameController,
                      validator: (value) =>
                          value?.isEmpty ?? true ? 'Please enter a valid business name' : null,
                      textFieldType: TextFieldType.NAME,
                      decoration: kInputDecoration.copyWith(
                        labelText: 'Business Name',
                        border: const OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 15),
                    AppTextField(
                      controller: phoneController,
                      validator: (value) => null,
                      textFieldType: TextFieldType.PHONE,
                      decoration: kInputDecoration.copyWith(
                        labelText: _lang.phone,
                        border: const OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 15),
                    TextFormField(
                      controller: addressController,
                      validator: (value) => null,
                      decoration: kInputDecoration.copyWith(
                        labelText: _lang.address,
                        border: const OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 15),
                    TextFormField(
                      validator: (value) => null,
                      controller: gstOrTinController,
                      decoration: kInputDecoration.copyWith(
                        labelText: 'GST/TIN',
                        hintText: 'Enter GST/TIN Name',
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 15),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(_lang.printingOption, style: theme.textTheme.titleMedium),
                  SizedBox(
                    width: 44,
                    height: 22,
                    child: Transform.scale(
                      scale: 0.8,
                      child: Switch.adaptive(
                        activeTrackColor: kMainColor,
                        value: printing,
                        onChanged: (bool value) => setState(() => printing = value),
                      ),
                    ),
                  )
                ],
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                visualDensity: const VisualDensity(vertical: -4, horizontal: -4),
                title: Text(
                  'Thermal Printer Page Size',
                  style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w500),
                ),
                trailing: SizedBox(
                  width: 105,
                  child: DropdownButtonHideUnderline(
                    child: DropdownButton<String>(
                      isExpanded: true,
                      padding: EdgeInsets.zero,
                      items: invoiceSizeOptions.entries.map((entry) {
                        return DropdownMenuItem<String>(
                          value: entry.key,
                          child: Text(
                            entry.value,
                            style:
                                theme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w500),
                          ),
                        );
                      }).toList(),
                      value: selectedThermalPrinter ?? '3_inch_80mm',
                      onChanged: (String? value) {
                        setState(() {
                          selectedThermalPrinter = value;
                        });
                      },
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ButtonGlobalWithoutIcon(
          buttontext: _isUpdating ? 'Saving...' : 'Save',
          buttonDecoration: kButtonDecoration.copyWith(color: kMainColor),
          onPressed: _isUpdating ? null : _updateProfile,
          buttonTextColor: Colors.white,
        ),
      ),
    );
  }

  DecorationImage? _getDecorationImage() {
    if (imageFile != null) {
      return DecorationImage(image: FileImage(imageFile!), fit: BoxFit.cover);
    } else if (ref.read(profileDetailsProvider).value?.pictureUrl != null) {
      return DecorationImage(
        image: NetworkImage(ref.read(profileDetailsProvider).value!.pictureUrl!),
        fit: BoxFit.cover,
      );
    } else {
      return DecorationImage(
        image: NetworkImage(_defaultProfilePicUrl),
        fit: BoxFit.cover,
      );
    }
  }
}

// class PrintingInvoiceScreen extends ConsumerStatefulWidget {
//   const PrintingInvoiceScreen({super.key});
//
//   @override
//   ConsumerState<PrintingInvoiceScreen> createState() => _PrintingInvoiceScreenState();
// }
//
// class _PrintingInvoiceScreenState extends ConsumerState<PrintingInvoiceScreen> {
//   TextEditingController addressController = TextEditingController();
//   TextEditingController phoneController = TextEditingController();
//   TextEditingController nameController = TextEditingController();
//   final Map<String, String> invoiceSizeOptions = {
//     '3_inch_80mm': '3 inch 80mm',
//     '2_inch_58mm': '2 inch 58mm',
//   };
//   @override
//   void initState() {
//     // TODO: implement initState
//     super.initState();
//
//     print(isPrintEnable);
//     printing = isPrintEnable;
//     ref.read(profileDetailsProvider).when(
//           data: (data) {
//             nameController.text = data.companyName ?? '';
//             phoneController.text = data.phoneNumber ?? '';
//             addressController.text = data.countryName ?? '';
//             selectedThermalPrinter = data.thermalPrinterPrintSize;
//           },
//           error: (error, stackTrace) {},
//           loading: () {},
//         );
//   }
//
//   bool printing = false;
//
//   final ImagePicker _picker = ImagePicker();
//   XFile? pickedImage;
//   File imageFile = File('No File');
//
//   final GlobalKey<FormState> _formKey = GlobalKey();
//
//   String? selectedThermalPrinter;
//
//   @override
//   Widget build(BuildContext context) {
//     final theme = Theme.of(context);
//     final _lang = lang.S.of(context);
//     return Scaffold(
//       backgroundColor: kWhite,
//       appBar: AppBar(
//         iconTheme: const IconThemeData(color: Colors.black),
//         title: Text(
//           'Print Invoice',
//         ),
//         centerTitle: true,
//         backgroundColor: Colors.white,
//         elevation: 0.0,
//       ),
//       bottomNavigationBar: Padding(
//         padding: const EdgeInsets.all(10.0),
//         child: ElevatedButton.icon(
//           icon: const Icon(
//             Icons.arrow_forward,
//             color: Colors.white,
//           ),
//           label: Text('Save'),
//           onPressed: () async {
//             if (_formKey.currentState!.validate()) {
//               final businessRepository = profileRepo.getDetails();
//               final isProfileUpdated = await businessRepository.updateProfile(
//                 id: ref.watch(profileDetailsProvider).value?.id.toString() ?? '',
//                 name: nameController.text,
//                 categoryId: ref.watch(profileDetailsProvider).value?.businessCategory?.id.toString() ?? '',
//                 address: addressController.text,
//                 invoiceLogo: pickedImage != null ? File(pickedImage!.path) : null,
//                 phone: phoneController.text,
//                 ref: ref,
//                 invoiceSize: selectedThermalPrinter,
//                 context: context,
//                 fromInvoiceLogo: true,
//               );
//
//               if (isProfileUpdated) {
//                 final prefs = await SharedPreferences.getInstance();
//                 await prefs.setBool('isPrintEnable', printing);
//                 isPrintEnable = printing;
//                 ref.refresh(profileDetailsProvider);
//                 // ref.refresh(businessSettingProvider);
//                 Navigator.pop(context);
//               }
//             }
//           },
//         ),
//       ),
//       body: Padding(
//         padding: const EdgeInsets.all(15.0),
//         child: Column(
//           spacing: 10,
//           children: [
//             Row(
//               children: [
//                 Text(
//                   'Invoice Logo',
//                   style: theme.textTheme.bodyLarge?.copyWith(),
//                 ),
//               ],
//             ),
//
//             ///__________Image_section________________________________________
//             GestureDetector(
//               onTap: () {
//                 showDialog(
//                     context: context,
//                     builder: (BuildContext context) {
//                       return Dialog(
//                         shape: RoundedRectangleBorder(
//                           borderRadius: BorderRadius.circular(12.0),
//                         ),
//                         // ignore: sized_box_for_whitespace
//                         child: Container(
//                           height: 200.0,
//                           width: MediaQuery.of(context).size.width - 80,
//                           child: Center(
//                             child: Row(
//                               mainAxisAlignment: MainAxisAlignment.center,
//                               children: [
//                                 GestureDetector(
//                                   onTap: () async {
//                                     pickedImage = await _picker.pickImage(source: ImageSource.gallery);
//
//                                     setState(() {
//                                       imageFile = File(pickedImage!.path);
//                                     });
//
//                                     Navigator.pop(context);
//                                   },
//                                   child: Column(
//                                     mainAxisAlignment: MainAxisAlignment.center,
//                                     children: [
//                                       const Icon(
//                                         Icons.photo_library_rounded,
//                                         size: 60.0,
//                                         color: kMainColor,
//                                       ),
//                                       Text(
//                                         'Gallary',
//                                         // 'Gallery',
//                                         style: theme.textTheme.titleMedium?.copyWith(
//                                           color: kGreyTextColor,
//                                         ),
//                                       ),
//                                     ],
//                                   ),
//                                 ),
//                                 const SizedBox(
//                                   width: 40.0,
//                                 ),
//                                 GestureDetector(
//                                   onTap: () async {
//                                     pickedImage = await _picker.pickImage(source: ImageSource.camera);
//                                     setState(() {
//                                       imageFile = File(pickedImage!.path);
//                                     });
//                                     Future.delayed(const Duration(milliseconds: 100), () {
//                                       Navigator.pop(context);
//                                     });
//                                   },
//                                   child: Column(
//                                     mainAxisAlignment: MainAxisAlignment.center,
//                                     children: [
//                                       const Icon(
//                                         Icons.camera,
//                                         size: 60.0,
//                                         color: kGreyTextColor,
//                                       ),
//                                       Text(
//                                         lang.S.of(context).camera,
//                                         // 'Camera',
//                                         style: theme.textTheme.titleMedium?.copyWith(
//                                           color: kGreyTextColor,
//                                         ),
//                                       ),
//                                     ],
//                                   ),
//                                 ),
//                               ],
//                             ),
//                           ),
//                         ),
//                       );
//                     });
//               },
//               child: Stack(
//                 children: [
//                   Container(
//                     height: 120,
//                     width: 120,
//                     decoration: BoxDecoration(
//                       border: Border.all(color: Colors.black54, width: 1),
//                       borderRadius: const BorderRadius.all(Radius.circular(120)),
//                       image: pickedImage == null
//                           ? ref.watch(profileDetailsProvider).value?.thermalPrinterPrintSize == null
//                               ? const DecorationImage(
//                                   image: AssetImage('images/sblogo.png'),
//                                   fit: BoxFit.cover,
//                                 )
//                               : DecorationImage(
//                                   image: NetworkImage(ApiConfig.domain + ref.watch(businessInfoProvider).value!.invoiceLogo.toString()),
//                                   fit: BoxFit.cover,
//                                 )
//                           : DecorationImage(
//                               image: FileImage(imageFile),
//                               fit: BoxFit.cover,
//                             ),
//                     ),
//                   ),
//                   Positioned(
//                     bottom: 0,
//                     right: 0,
//                     child: Container(
//                       height: 35,
//                       width: 35,
//                       decoration: BoxDecoration(
//                         border: Border.all(color: Colors.white, width: 2),
//                         borderRadius: const BorderRadius.all(Radius.circular(120)),
//                         color: kMainColor,
//                       ),
//                       child: const Icon(
//                         Icons.camera_alt_outlined,
//                         size: 20,
//                         color: Colors.white,
//                       ),
//                     ),
//                   )
//                 ],
//               ),
//             ),
//             const SizedBox(height: 20.0),
//             Form(
//               key: _formKey,
//               child: Column(
//                 spacing: 25,
//                 children: [
//                   AppTextField(
//                     controller: nameController, // Optional
//                     validator: (value) {
//                       if (value == null || value.isEmpty) {
//                         //return 'Please enter a valid business name';
//                         return 'Please enter a valid business name';
//                       }
//                       return null;
//                     },
//                     textFieldType: TextFieldType.NAME,
//                     decoration: kInputDecoration.copyWith(
//                       labelText: 'Business Name',
//                       border: const OutlineInputBorder(),
//                     ),
//                   ),
//                   AppTextField(
//                     controller: phoneController,
//                     validator: (value) {
//                       return null;
//                     },
//                     textFieldType: TextFieldType.PHONE,
//                     decoration: kInputDecoration.copyWith(
//                       labelText: lang.S.of(context).phone,
//                       border: const OutlineInputBorder(),
//                     ),
//                   ),
//                   AppTextField(
//                     controller: addressController,
//                     validator: (value) {
//                       return null;
//                     },
//                     textFieldType: TextFieldType.NAME,
//                     decoration: kInputDecoration.copyWith(
//                       labelText: lang.S.of(context).address,
//                       border: const OutlineInputBorder(),
//                     ),
//                   ),
//                 ],
//               ),
//             ),
//
//             SizedBox(height: 5),
//             Row(
//               mainAxisAlignment: MainAxisAlignment.spaceBetween,
//               children: [
//                 Text(_lang.printingOption, style: theme.textTheme.titleMedium),
//                 SizedBox(
//                   width: 44,
//                   height: 22,
//                   child: Transform.scale(
//                     scale: 0.8,
//                     child: Switch.adaptive(
//                       activeTrackColor: kMainColor,
//                       value: printing,
//                       onChanged: (bool value) async {
//                         setState(() => printing = value);
//                       },
//                     ),
//                   ),
//                 )
//               ],
//             ),
//             ListTile(
//               contentPadding: EdgeInsets.zero,
//               visualDensity: VisualDensity(vertical: -4, horizontal: -4),
//               title: Text(
//                 'Thermal Printer Page Size',
//                 style: theme.textTheme.titleMedium?.copyWith(
//                   fontWeight: FontWeight.w500,
//                 ),
//               ),
//               trailing: SizedBox(
//                 width: 105,
//                 child: DropdownButtonHideUnderline(
//                   child: DropdownButton(
//                       // isDense: true,
//                       isExpanded: true,
//                       padding: EdgeInsets.zero,
//                       items: invoiceSizeOptions.entries.map((entry) {
//                         return DropdownMenuItem(
//                             value: entry.key,
//                             child: Text(
//                               entry.value,
//                               style: theme.textTheme.bodySmall?.copyWith(
//                                 fontWeight: FontWeight.w500,
//                               ),
//                             ));
//                       }).toList(),
//                       value: selectedThermalPrinter ?? '2_inch_58mm',
//                       onChanged: (String? value) {
//                         setState(() {
//                           selectedThermalPrinter = value;
//                         });
//                       }),
//                 ),
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
// }
