import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/colors.dart';
import '../../../controller/home/profile/invit_controller.dart';
import '../../../print.dart';

class ShareAppPage extends StatelessWidget {
  final InviteController controller = Get.put(InviteController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CupertinoColors.systemBackground,
      appBar: AppBar(
        backgroundColor: CupertinoColors.systemBackground,
        elevation: 0,
        title: Text(
          'Invite'.tr,
          style: const TextStyle(color: CupertinoColors.label),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: AppColor.blueColor),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: GetBuilder<InviteController>(
          builder: (controller) {
            return Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: _buildPassengerTab(context),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildPassengerTab(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: CupertinoColors.systemGrey6,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              Text(
                "Share this code with your friends and earn rewards when they use it!"
                    .tr,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: CupertinoColors.secondaryLabel,
                  fontSize: 13,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),
        _buildPhoneInput(),
        const SizedBox(height: 20),
        _buildActionButtonsPassengers(),
        const SizedBox(height: 20),
        const SizedBox(height: 20),
        _buildInvitationsListPassengers(context),
      ],
    );
  }

  // Widget _buildPhoneInput() {
  //   return Container(
  //     decoration: BoxDecoration(
  //       color: CupertinoColors.systemGrey6,
  //       borderRadius: BorderRadius.circular(8),
  //     ),
  //     child: Row(
  //       children: [
  //         Expanded(
  //           child: CupertinoTextField.borderless(
  //             controller: controller.invitePhoneController,
  //             placeholder: 'Enter phone'.tr,
  //             padding: const EdgeInsets.all(12),
  //             keyboardType: TextInputType.phone,
  //           ),
  //         ),
  //         CupertinoButton(
  //           child: const Icon(CupertinoIcons.person_badge_plus,
  //               color: AppColor.blueColor),
  //           onPressed: () async {
  //             await controller.pickContacts();
  //             if (controller.contacts.isNotEmpty) {
  //               if (box.read(BoxName.isSavedPhones) == null) {
  //                 controller.savePhoneToServer();
  //                 box.write(BoxName.isSavedPhones, true);
  //               }
  //               _showContactsDialog(Get.context!);
  //             }
  //           },
  //         ),
  //       ],
  //     ),
  //   );
  // }
  Widget _buildPhoneInput() {
    return Container(
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            child: CupertinoTextField.borderless(
              controller: controller.invitePhoneController,
              placeholder: 'Enter phone'.tr,
              padding: const EdgeInsets.all(12),
              keyboardType: TextInputType.phone,
            ),
          ),
          CupertinoButton(
            child: const Icon(CupertinoIcons.person_badge_plus,
                color: AppColor.blueColor),
            onPressed: () async {
              await controller.pickContacts();
              Log.print('contacts: ${controller.contacts}');
              if (controller.contacts.isNotEmpty) {
                _showContactsDialog(Get
                    .context!); // Show contacts dialog after loading contacts
              } else {
                Get.snackbar(
                  'No contacts available'.tr,
                  'Please add contacts to your phone.'.tr,
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtonsPassengers() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                onPressed: controller.sendInviteToPassenger,
                child: Text(
                  'Send Invite'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                child: Text(
                  'Show Invitations'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
                onPressed: () async {
                  controller.fetchDriverStatsPassengers();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInvitationsListPassengers(BuildContext context) {
    return SizedBox(
      height: Get.height * .4,
      child: controller.driverInvitationDataToPassengers.isEmpty
          ? Center(
              child: Text(
                "No invitation found yet!".tr,
                style: const TextStyle(
                  color: CupertinoColors.secondaryLabel,
                  fontSize: 17,
                ),
              ),
            )
          : ListView.builder(
              itemCount: controller.driverInvitationDataToPassengers.length,
              itemBuilder: (context, index) {
                return _buildInvitationItemPassengers(context, index);
              },
            ),
    );
  }

  Widget _buildInvitationItemPassengers(BuildContext context, int index) {
    // Extracting the data from the sample JSON-like structure
    var invitation = controller.driverInvitationDataToPassengers[index];

    int countOfInvitDriver =
        int.tryParse(invitation['countOfInvitDriver']?.toString() ?? '0') ?? 0;
    double progressValue = (countOfInvitDriver / 10.0).clamp(0.0, 1.0);

    return GestureDetector(
      onTap: () {
        controller.onSelectPassengerInvitation(index);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: CupertinoColors.systemGrey6,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              invitation['passengerName']
                  .toString(), // Handle null or missing data
              style: const TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: CupertinoColors.label,
              ),
            ),
            const SizedBox(height: 8),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: LinearProgressIndicator(
                value: progressValue,
                backgroundColor: CupertinoColors.systemGrey4,
                valueColor:
                    const AlwaysStoppedAnimation<Color>(AppColor.blueColor),
                minHeight: 6,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              '$countOfInvitDriver / 2 ${'Trip'.tr}', // Show trips completed
              style: const TextStyle(
                fontSize: 13,
                color: CupertinoColors.secondaryLabel,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPassengerStats(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Your Rewards".tr,
            style: const TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w600,
              color: CupertinoColors.label,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatItem(
            context,
            "Total Invites".tr,
            controller.driverInvitationDataToPassengers[0]['countOfInvitDriver']
                .toString(),
          ),
          _buildStatItem(
            context,
            "Active Users".tr,
            controller.driverInvitationDataToPassengers[0]['passengerName']
                .toString(),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(BuildContext context, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              color: CupertinoColors.label,
              fontSize: 15,
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              fontWeight: FontWeight.w600,
              color: AppColor.blueColor,
              fontSize: 15,
            ),
          ),
        ],
      ),
    );
  }

  void _showContactsDialog(BuildContext context) {
    Get.defaultDialog(
      title: 'Choose from contact'.tr,
      content: SizedBox(
        height: 400,
        width: 400,
        child: Column(
          children: [
            // Header with cancel and title
            // Container(
            //   padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            //   decoration: const BoxDecoration(
            //     borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            //     color: CupertinoColors.systemGrey6,
            //   ),
            //   child: Row(
            //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //     children: [
            //       CupertinoButton(
            //         padding: EdgeInsets.zero,
            //         child: Text(
            //           'Cancel'.tr,
            //           style: const TextStyle(color: CupertinoColors.systemBlue),
            //         ),
            //         onPressed: () => Navigator.pop(context),
            //       ),
            //       Container(
            //           child: Text('Choose from contact'.tr,
            //               style: AppStyle.title)),
            //       const SizedBox(width: 60), // Balance for Cancel button
            //     ],
            //   ),
            // ),

            // Contact list
            Expanded(
              child: ListView.builder(
                itemCount: controller.contactMaps.length,
                itemBuilder: (context, index) {
                  final contact = controller.contactMaps[index];
                  return CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      controller.selectPhone(contact['phones'].toString());
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 12),
                      decoration: BoxDecoration(
                        color: CupertinoColors.systemBackground,
                        border: Border(
                          bottom: BorderSide(
                            color: CupertinoColors.separator.withOpacity(0.5),
                          ),
                        ),
                      ),
                      child: Row(
                        children: [
                          // Display contact name and phone number
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  contact['name'],
                                  style: const TextStyle(
                                    color: CupertinoColors.label,
                                    fontSize: 17,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                                Text(
                                  (contact['phones'][0].toString()),
                                  style: const TextStyle(
                                    color: CupertinoColors.secondaryLabel,
                                    fontSize: 15,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          // Chevron icon for selection
                          const Icon(
                            CupertinoIcons.chevron_forward,
                            color: CupertinoColors.systemGrey2,
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
    // showCupertinoModalPopup(
    //   context: context,
    //   builder: (BuildContext context) => Container(
    //     height: 400,
    //     decoration: BoxDecoration(
    //       color: CupertinoColors.systemBackground,
    //       borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
    //       boxShadow: [
    //         BoxShadow(
    //           color: CupertinoColors.black.withOpacity(0.2),
    //           offset: const Offset(0, -4),
    //           blurRadius: 10,
    //         ),
    //       ],
    //     ),
    //     child: Column(
    //       children: [
    //         // Header with cancel and title
    //         Container(
    //           padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
    //           decoration: const BoxDecoration(
    //             borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
    //             color: CupertinoColors.systemGrey6,
    //           ),
    //           child: Row(
    //             mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //             children: [
    //               CupertinoButton(
    //                 padding: EdgeInsets.zero,
    //                 child: Text(
    //                   'Cancel'.tr,
    //                   style: const TextStyle(color: CupertinoColors.systemBlue),
    //                 ),
    //                 onPressed: () => Navigator.pop(context),
    //               ),
    //               Container(
    //                   child: Text('Choose from contact'.tr,
    //                       style: AppStyle.title)),
    //               const SizedBox(width: 60), // Balance for Cancel button
    //             ],
    //           ),
    //         ),

    //         // Contact list
    //         Expanded(
    //           child: ListView.builder(
    //             itemCount: controller.contactMaps.length,
    //             itemBuilder: (context, index) {
    //               final contact = controller.contactMaps[index];
    //               return CupertinoButton(
    //                 padding: EdgeInsets.zero,
    //                 onPressed: () {
    //                   controller.selectPhone(contact['phones'].toString());
    //                 },
    //                 child: Container(
    //                   padding: const EdgeInsets.symmetric(
    //                       horizontal: 16, vertical: 12),
    //                   decoration: BoxDecoration(
    //                     color: CupertinoColors.systemBackground,
    //                     border: Border(
    //                       bottom: BorderSide(
    //                         color: CupertinoColors.separator.withOpacity(0.5),
    //                       ),
    //                     ),
    //                   ),
    //                   child: Row(
    //                     children: [
    //                       // Display contact name and phone number
    //                       Expanded(
    //                         child: Column(
    //                           crossAxisAlignment: CrossAxisAlignment.start,
    //                           children: [
    //                             Text(
    //                               contact['name'],
    //                               style: const TextStyle(
    //                                 color: CupertinoColors.label,
    //                                 fontSize: 17,
    //                                 fontWeight: FontWeight.w500,
    //                               ),
    //                             ),
    //                             Text(
    //                               controller.formatPhoneNumber(
    //                                   contact['phones'][0].toString()),
    //                               style: const TextStyle(
    //                                 color: CupertinoColors.secondaryLabel,
    //                                 fontSize: 15,
    //                               ),
    //                             ),
    //                           ],
    //                         ),
    //                       ),
    //                       // Chevron icon for selection
    //                       const Icon(
    //                         CupertinoIcons.chevron_forward,
    //                         color: CupertinoColors.systemGrey2,
    //                       ),
    //                     ],
    //                   ),
    //                 ),
    //               );
    //             },
    //           ),
    //         ),
    //       ],
    //     ),
    //   ),
    // );
  }
}
