import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:trialOrderPro/utils/constant/color_constant.dart';
import 'package:trialOrderPro/utils/constant/font_constant.dart';
import 'package:trialOrderPro/utils/constant/path_constant.dart';
import 'package:trialOrderPro/modules/cart/controllers/aws_s3_controller.dart';
import 'package:flutter/cupertino.dart';

import '../../../app/routes.dart';
import '../../../data/homescreen/brand_data.dart';
import '../../../modules/brands/controllers/biotrue/arguement_controller.dart';
import '../../../modules/home/controllers/home_controller.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class Brand {
  final String name;
  bool isSelected;
  final String imageUrl;
  final List<Indication> indications;

  Brand({
    required this.name,
    required this.imageUrl,
    this.isSelected = false,
    required this.indications,
  });
}

class Indication {
  final String name;
  bool isSelected;
  final List<DrawerItem> drawers;

  Indication({
    required this.name,
    this.isSelected = false,
    required this.drawers,
  });
}

class DrawerItem {
  final String name;
  bool isSelected;

  DrawerItem({required this.name, this.isSelected = false});
}

// int selectedBrandIndex = 0;
// int selectedIndicationIndex = 0;
// String selectedIndicationName = '';

class BrandSelectionScreen extends StatelessWidget {
  final Function(Brand) onBrandSelected;
  final List<Brand> brands;
  final Function(Indication) onIndicationSelected;

  BrandSelectionScreen({
    required this.onBrandSelected,
    required this.brands,
    required this.onIndicationSelected,
  });


  final controller = Get.put(HomeController());

  Future<String> _getAppVersion() async {
    final PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }
  void onTapBrand(int index) {

    controller.selectedBrandIndex = index;
    // Update the selected indication
    controller.selectedIndicationIndex = 0; // You can set it to the first indication
    controller.selectedDrawerIndex = 0; // You can set it to the first indication
    controller.selectedIndicationName = brands[index].indications[0].name;

    // Deselect all other brands

    for (int i = 0; i < brands.length; i++) {
      brands[i].isSelected = i == index;
    }

    // Deselect all other indications except the first one for the selected brand
    for (int i = 0; i < brands[index].indications.length; i++) {
      brands[index].indications[i].isSelected = i == controller.selectedIndicationIndex;
    }

    // Deselect all other drawers except the first one for the selected brand
    for (int i = 0; i < brands[controller.selectedBrandIndex].indications[controller.selectedIndicationIndex].drawers.length; i++) {
      brands[controller.selectedBrandIndex].indications[controller.selectedIndicationIndex].drawers[i].isSelected = i == controller.selectedDrawerIndex;
    }

    // Call the callback function with the selected brand
    onBrandSelected(brands[index]);

    // Call the callback function with the first indication of the selected brand
    onIndicationSelected(brands[index].indications[0]);

    controller.update();

  }

  @override
 Widget build(BuildContext context) {
    resetBrandIndicationDrawerSelectionValue();

    return GetBuilder(
      init: controller,
      builder: (getXContext) {
        return FutureBuilder<String>(
          future: _getAppVersion(),
          builder: (context, snapshot) {
            final appVersion = snapshot.data ?? 'Unknown';
          return Material(
            child: Container(
              padding: EdgeInsets.only(left: 10, top: 8),
              //width: MediaQuery.of(context).size.width*0.23,
              //width: 294,
              color: blue_munsell,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 12),
                    child: Text(
                      AppLocalizations.of(context)?.home_screen_brands ?? '',
                      style: TextStyle(
                          fontSize: 22,
                          fontFamily: FontType.Bold,
                          color: Colors.white,
                          letterSpacing: 1),
                    ),
                  ),
                  Expanded(
                    child: ListView.builder(
                      itemCount: brands.length,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 5),
                          child: GestureDetector(
                            onTap: () {
                              onTapBrand(index);
                            },
                            child: BrandTab(
                              brand: brands[index],
                              imageUrl: brands[index].imageUrl,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
//    Padding(
//   padding: const EdgeInsets.symmetric(horizontal: 35, vertical: 12),
//   child: Row(
//     children: [
//       Image.asset(
//         'assets/image/alert.png', 
//         width: 24, 
//         height: 34,
//       ),
//       SizedBox(width: 8), 
//       Flexible(
//         child: RichText(
//           text: TextSpan(
//             style: TextStyle(
//               fontSize: 14,
//               fontFamily: FontType.Bold,
//               color: Colors.white,
//               letterSpacing: 1,
//               height: 1.2
//             ),
//             children: [
//               TextSpan(text: 'Current Limit: 100 Trials\n'),
//               TextSpan(text: 'per brand per indication'),
//             ],
//           ),
//         ),
//       ),
//     ],
//   ),
// ),


                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 12),
                    child: Center(
                      child: Text(
                        'V $appVersion',
                        style: TextStyle(
                            fontSize: 15,
                            fontFamily: FontType.Bold,
                            color: Colors.white,
                            letterSpacing: 1),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        });
      },
    );
  }

  resetBrandIndicationDrawerSelectionValue() {
    for (int i = 0; i < brands.length; i++) {
      brands[i].isSelected = i == controller.selectedBrandIndex;
    }

    // Deselect all other indications except the first one for the selected brand
    for (int i = 0; i < brands[controller.selectedBrandIndex].indications.length; i++) {
      brands[controller.selectedBrandIndex].indications[i].isSelected = i == controller.selectedIndicationIndex;
    }

    for (int i = 0; i < brands[controller.selectedBrandIndex].indications[controller.selectedIndicationIndex].drawers.length; i++) {
      brands[controller.selectedBrandIndex].indications[controller.selectedIndicationIndex].drawers[i].isSelected = i == controller.selectedDrawerIndex;
    }

    controller.selectedIndicationName = brands[controller.selectedBrandIndex].indications[0].name;


  }
}

class BrandTab extends StatelessWidget {
  final Brand brand;
  final String imageUrl;

  const BrandTab({
    required this.brand,
    required this.imageUrl,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: brand.isSelected
          ? EdgeInsets.only(left: 15, right: 0)
          : EdgeInsets.only(left: 0, right: 15),
      height: 95,
      padding: EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: brand.isSelected
            ? [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            offset: Offset(0, 6),
            blurRadius: 10,
            spreadRadius: 4,
          )
        ]
            : [],
      ),
      child: Padding(
        padding: const EdgeInsets.only(right: 10.0,left: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Expanded(
              child: Container(
                height: 50,
                child: ClipRRect(child: Image.asset(imageUrl)),
              ),
            ),
            Visibility(
              visible: brand.isSelected,
              child: Padding(
                padding: const EdgeInsets.only(left: 10.0),
                child: SvgPicture.asset(arrow_forward),
              ),
            ),
          ],
        ),
      ),
    );
  }
}



class IndicationScreen extends StatelessWidget {
  final Function(Indication) onIndicationSelected;
  final List<Indication> indications;
  final Function() onCustomerSelection;

  IndicationScreen({
    required this.onIndicationSelected,
    required this.indications,
    required this.onCustomerSelection,
  });

  final controller = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (getXContext) {
          return Material(
            child: Container(
              padding: EdgeInsets.only(left: 10, right: 10, top: 15),
              color: alice_blue,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: Text(
                      AppLocalizations.of(context)?.home_screen_indications ?? '',
                      style: TextStyle(
                        fontSize: 22,
                        fontFamily: FontType.Bold,
                        color: controller.customerInfo != null
                            ? homescreen_headings
                            : homescreen_headings_fade,
                      ),
                    ),
                  ),
                  Flexible(
                    child: ListView.builder(
                      itemCount: indications.length,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 8),
                          child: InkWell(
                            onTap: controller.customerInfo== null
                                ? () {
                              onCustomerSelection();
                            }
                                : null,
                            child: IgnorePointer(
                              ignoring: controller.customerInfo== null,
                              child: Opacity(
                                opacity:
                                controller.customerInfo== null ? 0.5 : 1.0,
                                child: GestureDetector(
                                  onTap: () {
                                    controller.selectedIndicationIndex = index;
                                    // Deselect all other indications
                                    for (int i = 0;
                                    i < indications.length;
                                    i++) {
                                      indications[i].isSelected =
                                          i == index;
                                    }

                                    controller.selectedDrawerIndex =0;
                                    // Deselect all other drawers except the first one for the selected brand
                                    for (int i = 0; i < indications[controller.selectedIndicationIndex].drawers.length; i++) {
                                      indications[controller.selectedIndicationIndex].drawers[i].isSelected = i == controller.selectedDrawerIndex;
                                    }

                                    // Call the callback function with the selected indication
                                    onIndicationSelected(
                                        indications[index]);
                                    controller.update();

                                  },
                                  child: IndicationTab(
                                    indication: indications[index],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }
}

class IndicationTab extends StatelessWidget {
  final Indication indication;

  const IndicationTab({
    required this.indication,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: indication.isSelected
          ? EdgeInsets.only(left: 15, right: 0)
          : EdgeInsets.only(left: 0, right: 15),
      height: 70,
      //padding: EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: indication.isSelected
            ? [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            offset: Offset(0, 9),
            blurRadius: 34,
            spreadRadius: 0,
          )
        ]
            : [],
      ),
      child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        Expanded(
          child: Text(
            indication.name,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontFamily: FontType.Bold,
              fontSize: 16,
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 8.0),
          child: Visibility(
            visible: indication.isSelected,
            child: SvgPicture.asset(arrow_forward),

          ),
        ),
      ]),
    );
  }
}



class DrawerScreen extends StatelessWidget {
  final List<DrawerItem> drawers;
  final Function() onCustomerSelection;
  final List<Brand> brands;

  DrawerScreen({
    required this.drawers,
    required this.onCustomerSelection,
    required this.brands,
  });

  final argumentsController = Get.find<ArgumentsController>();

  final controller = Get.put(HomeController());
  final awscontroller = Get.put(AwsController());
  List<String> selectedDrawers = [];

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (getXContext) {
          return Material(
            color: Colors.white,
            child: Stack(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 10, right: 10, top: 15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        child: Text(
                           AppLocalizations.of(context)?.home_screen_drawer ?? '',
                          style: TextStyle(
                            fontSize: 22,
                            fontFamily: FontType.Bold,
                            color: controller.customerInfo != null
                                ? homescreen_headings
                                : homescreen_headings_fade,
                          ),
                        ),
                      ),
                      Flexible(
                        child: ListView.builder(
                          itemCount: drawers.length,
                          itemBuilder: (context, index) {
                            bool isBrandIndexOneIndicationOne = (controller.selectedBrandIndex == 2 && controller.selectedIndicationIndex == 1) || controller.selectedBrandIndex == 3 || controller.selectedBrandIndex == 4;
                            bool shouldDisable = isBrandIndexOneIndicationOne;

                            return Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                              child: InkWell(
                                onTap: controller.customerInfo == null
                                    ? () {
                                        onCustomerSelection();
                                      }
                                    : null,
                                child: Opacity(
                                  opacity: controller.customerInfo == null ? 0.5 : 1.0,
                                  child: GestureDetector(
                                    onTap: controller.customerInfo == null
                                        ? null
                                        : () {
                                            controller.selectedDrawerIndex = index;

                                            for (int i = 0; i < drawers.length; i++) {
                                              drawers[i].isSelected = i == index;
                                            }
                                            controller.update();

                                            final selectedBrand = brands[controller.selectedBrandIndex];
                                            final relevantIndicationIndex = selectedBrand.indications.indexWhere((indication) => indication.drawers.any((drawer) => drawer.name == drawers[index].name));

                                            if (relevantIndicationIndex != -1) {
                                              controller.selectedIndicationIndex = relevantIndicationIndex;
                                              controller.selectedIndicationName = selectedBrand.indications[controller.selectedIndicationIndex].name;
                                            }

                                            final selectedIndication = selectedBrand.indications[controller.selectedIndicationIndex];
                                            final relevantDrawers = selectedIndication.drawers;
                                            final drawerNames = relevantDrawers.map((drawer) => drawer.name).toList();
                                            final initiallySelectedDrawer = drawers[index].name;

                                            argumentsController.initiallySelectedDrawer = RxString(initiallySelectedDrawer);
                                            argumentsController.drawerName.value = selectedIndication.name;
                                            argumentsController.selectedDrawers.assignAll(drawerNames);
                                            argumentsController.brandName.value = selectedBrand.name;
                                            argumentsController.indicationName.value = selectedIndication.name;

                                            final routeName = AppRoutesPath.drawerDetailScreenPrefix + drawerRouteMap[drawers[index].name]!;

                                            DataClass data = DataClass(isNavigated: false, data: argumentsController.initiallySelectedDrawer.value);
                                            Get.toNamed(routeName, arguments: data);
                                          },
                                    child: DrawerTab(
                                      drawer: drawers[index],
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
        Obx(
                  () {
                  return Visibility(
  visible: awscontroller.isbackupsyncLoading.value,
  child: Align(
    alignment: Alignment.centerLeft,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 16),
          child: CupertinoActivityIndicator(
            radius: 25.0,
            color: Colors.blue,
          ),
        ),
        SizedBox(height: 10.0),
        Container(
          color: Colors.black,
          padding: EdgeInsets.all(10.0),
          child: Text(
            AppLocalizations.of(context)?.app_drawer_data_sync_alert_message ?? '',
            
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 18.0, color: Colors.white),
          ),
        ),
      ],
    ),
  ),
);
                  },
                ),
              ],
            ),
          );
        });
  }
}

class DrawerTab extends StatelessWidget {
  final DrawerItem drawer;

  const DrawerTab({
    required this.drawer,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: drawer.isSelected
            ? EdgeInsets.only(left: 15, right: 0)
            : EdgeInsets.only(left: 0, right: 15),
        width: 681,
        height: 70,
        padding: EdgeInsets.all(15),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            //border: Border.all(color: drawer.isSelected ? Colors.blue : Colors.grey[300]!),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                offset: Offset(0, 3),
                blurRadius: 13,
                spreadRadius: 0,
              ),
            ]),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Expanded(
              child: Row(
                children: [
                  SvgPicture.asset(
                    colorFilter: ColorFilter.mode(Color(0xFF0C3864), BlendMode.srcIn),
                    'assets/icons_svg/drawer_icon.svg',
                  ),
                  SizedBox(
                    width: 20,
                  ),
                  Expanded(
                    child: Text(
                       drawer.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      softWrap: false,
                      style: TextStyle(
                        fontSize: 16,
                        fontFamily: FontType.Bold,
                        color: Colors.black,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SvgPicture.asset(arrow_forward),

          ],
        ));
  }
}

// class LineBreakText extends StatelessWidget {
//   final String text;
//   final TextStyle style;
//   final int maxCharsBeforeBreak;
//
//   LineBreakText({
//     required this.text,
//     required this.style,
//     required this.maxCharsBeforeBreak,
//   });
//
//   @override
//   Widget build(BuildContext context) {
//     if (text.length <= maxCharsBeforeBreak) {
//       return Text(
//         text,
//         style: style,
//       );
//     }
//
//     int breakIndex = maxCharsBeforeBreak;
//     while (breakIndex > 0 && !text[breakIndex].trim().isEmpty) {
//       breakIndex--;
//     }
//
//     String firstLine = text.substring(0, breakIndex).trim();
//     String secondLine = text.substring(breakIndex).trim();
//
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.start,
//       children: [
//         Text(
//           firstLine,
//           style: style,
//         ),
//         Visibility(
//           visible: secondLine.isNotEmpty,
//           child: Text(
//             secondLine,
//             style: style,
//           ),
//         ),
//       ],
//     );
//   }
// }

class DataClass {
  final String data;
  final bool isNavigated;
  DataClass({required this.data, this.isNavigated = false});
}


tthis is actually not showing at the cntre of the display:
return Visibility(
  visible: awscontroller.isbackupsyncLoading.value,
  child: Align(
    alignment: Alignment.centerLeft,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 16),
          child: CupertinoActivityIndicator(
            radius: 25.0,
            color: Colors.blue,
          ),
        ),
        SizedBox(height: 10.0),
        Container(
          color: Colors.black,
          padding: EdgeInsets.all(10.0),
          child: Text(
            AppLocalizations.of(context)?.app_drawer_data_sync_alert_message ?? '',
            
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 18.0, color: Colors.white),
          ),
        ),
      ],
    ),
  ),
);