import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:trialOrderPro/app/routes.dart';
import 'package:trialOrderPro/data/model/customer_data_model.dart';
import 'package:trialOrderPro/modules/outside_fitset/controllers/outside_fitset_controller.dart';
import 'package:trialOrderPro/ui/dialogs/dialogs.dart';
import 'package:trialOrderPro/utils/constant/font_constant.dart';
import 'package:trialOrderPro/utils/constant/color_constant.dart';
import 'package:flutter/cupertino.dart';
import '../../../utils/local_storage/app_local_storage.dart';

class OutsideFitset extends StatefulWidget {
  @override
  State<OutsideFitset> createState() => _OutsideFitsetState();
}

class _OutsideFitsetState extends State<OutsideFitset> {
  final OutsideFitsetController controller = Get.put(OutsideFitsetController());
  AppLocalStorage appLocalStorage = AppLocalStorage();

  @override
  void initState() {
    super.initState();
    if (appLocalStorage.getOutSideFitSetDataCall() != 'completed') {
      controller.getOutsideFitLensDataFromAWSBucket();
    }
  }

  Future<void> manageCustomerInfo() async {
     await Get.toNamed(AppRoutesPath.customerListScreen);
     CustomerData? customerData = CustomerData.getCustomerDataFromStorage();
    if (customerData != null) {
      controller.isCustomerSelected.value = true;
      setState(() {});
    }
  }

  void customerSelectionDialog() {
    showCustomerSelectionDialog(
      context,
      (bool isProceed) {
        if (isProceed) {
          manageCustomerInfo();
        }
      },
    );
  }

  void _handleAddToCart() {
    //controller.addLensValueToCart();
    if (controller.isCustomerSelected.value) {
                     controller.addLensValueToCart();
                     } else {
                      customerSelectionDialog();
                       }
  }

  @override
  Widget build(BuildContext context) {
    CustomerData? customerData = CustomerData.getCustomerDataFromStorage();
    if (customerData != null) {
      controller.isCustomerSelected.value = true;    
    }
    return Scaffold(
      appBar: AppBar(
        scrolledUnderElevation: 0.0,
        title: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Container(
            alignment: Alignment.topLeft,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 5),
                Text(
                  "Individual Lens",
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                    fontFamily: FontType.Regular,
                    color: dark_midnight_blue,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  "Tap below to add Individual Trial Lenses",
                  style: TextStyle(
                    fontSize: 15,
                    fontFamily: FontType.Regular,
                    color: Colors.black,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          SizedBox(height: 50),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                flex: 3,
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 8.0),
                  child: Obx(() => GestureDetector(
                        onTap: () {
                          if (!controller.isCustomerSelected.value) {
                            customerSelectionDialog();
                          }
                        },
                        child: AbsorbPointer(
                          absorbing: !controller.isCustomerSelected.value,
                          child: DropdownButtonFormField<String>(
                            decoration: getDropdownDecoration(),
                            value: controller.selectedBrand!.value.isEmpty
                                ? null
                                : controller.selectedBrand!.value,
                            hint: Text('Select Brand Indication'),
                            onChanged: (newValue) async {
                              if (controller.isCustomerSelected.value) {
                                controller.selectedPower!.value = controller.selectedCylinder!.value = controller.selectedAdd!.value = controller.selectedAxis!.value = '';
                                controller.selectedBrand!.value = newValue!;
                                if (newValue.isNotEmpty) {
                                  await controller
                                      .updatePowersDataOnBrandsSelection(
                                          newValue); // Use await here
                                  setState(() {});
                                }
                                // Show the filters updated from Here ----------->>>>>>>>>>
                              }
                            },
                            items: controller.brands
                                .map<DropdownMenuItem<String>>((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value),
                              );
                            }).toList(),
                          ),
                        ),
                      )),
                ),
              ),
              Expanded(
                flex: 7,
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 8.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height * 0.4,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white,
                    ),
                    child: Stack(
                      children: <Widget>[
                        HeaderRow(),
                        Positioned.fill(
                          child: Row(
                            children: [
                              Flexible(
                                flex: 1,
                                child: Obx(() => PickerColumn(
                                      key: ValueKey(
                                          controller.resetTrigger.value),
                                //  data: [     
                                //          '+6.00', '+5.75', '+5.50', '+5.25', '+5.00', '+4.75', '+4.50', '+4.25',
                                //          '+4.00', '+3.75', '+3.50', '+3.25', '+3.00', '+2.75', '+2.50', '+2.25',
                                //          '+2.00', '+1.75', '+1.50', '+1.25', '+1.00', '+0.75', '+0.50', '+0.25', 
                                //          '0.00', 
                                //          '-0.25', '-0.50', '-0.75', '-1.00', '-1.25', '-1.50', '-1.75', 
                                //          '-2.00', '-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', 
                                //          '-4.00', '-4.25', '-4.50', '-4.75', '-5.00', '-5.25', '-5.50', '-5.75', 
                                //          '-6.00', '-6.25', '-6.50', '-6.75', '-7.00', '-7.25', '-7.50', '-7.75', 
                                //          '-8.00', '-8.25', '-8.50', '-8.75', '-9.00', '-9.25', '-9.50', '-9.75',
                                //          ],
                                data: controller.powersfilterata,
                                      title: "POWERS",
                                      onSelectedItemChanged: (value) {
                                          controller.selectedPower!.value = value;
                                      },
                                      isEnabled: controller.isPowerEnabled(),
                                      isCustomerSelected:
                                          controller.isCustomerSelected.value,
                                      showRightDivider: true,
                                    )),
                              ),
                              Flexible(
                                flex: 1,
                                child: Obx(() => PickerColumn(
                                      key: ValueKey(
                                          controller.resetTrigger.value),
                                      data: controller.cylindersfilterData,//['-0.75', '-1.25', '-1.75', '-2.25', '-2.75'],
                                      title: "CYLINDERS",
                                      onSelectedItemChanged: (value) {
                                        controller.selectedCylinder!.value =
                                            value;
                                      },
                                      isEnabled: controller.isCylinderEnabled(),
                                      isCustomerSelected:
                                          controller.isCustomerSelected.value,
                                      showRightDivider: true,
                                    )),
                              ),
                              Flexible(
                                flex: 1,
                                child: Obx(() => PickerColumn(
                                      key: ValueKey(
                                          controller.resetTrigger.value),
                                     data: controller.axisfilterData, // ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '110', '120', '130', '140', '150','160', '170', '180'],
                                      title: "AXIS",
                                      onSelectedItemChanged: (value) {
                                        controller.selectedAxis!.value = value;
                                      },
                                      isEnabled: controller.isAxisEnabled(),
                                      isCustomerSelected:
                                          controller.isCustomerSelected.value,
                                      showRightDivider: true,
                                    )),
                              ),
                              Flexible(
                                flex: 1,
                                child: Obx(() => PickerColumn(
                                      key: ValueKey(
                                          controller.resetTrigger.value),
                                      data: ['High', 'Low'],
                                      title: "ADD",
                                      onSelectedItemChanged: (value) {
                                        controller.selectedAdd!.value = value;
                                      },
                                      isEnabled: controller.isAddEnabled(),
                                      isCustomerSelected:
                                          controller.isCustomerSelected.value,
                                      showRightDivider: false,
                                    )),
                              ),
                            ],
                          ),
                        ),
                        Positioned(
                          child: Obx(
                            () => Visibility(
                              visible: controller.isLoading.value,
                              child: Align(
                                alignment: Alignment(-0.6, 0.0),
                                child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                                  decoration: BoxDecoration(
                                    color: Colors.black,
                                    borderRadius: BorderRadius.circular(8.0),
                                  ),
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: <Widget>[
                                      CupertinoActivityIndicator(
                                        radius: 25.0,
                                        color: Colors.white,
                                      ),
                                      SizedBox(height: 10),
                                      Text(
                                        'Please Wait...\n Loading Individual Trial Lenses Data!',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14.0,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
          buildSmallTable(),
          Expanded(child: Container()),
          Align(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  SizedBox(width: 16),
                 Obx(() => ElevatedButton(
                    onPressed: _handleAddToCart,
                    child: controller.isAddedToCart.value
                        ? Icon(Icons.check, color: Colors.white)
                        : Text(
                            'Add to Cart'.toUpperCase(),
                            style: TextStyle(color: Colors.white, fontSize: 15),
                          ),
                    style: ElevatedButton.styleFrom(
                      foregroundColor: Colors.white,
                      backgroundColor: controller.isAddedToCart.value ? Colors.green : Colors.black,
                      shadowColor: Colors.grey.shade900,
                      elevation: 10,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                    ),
                  ))
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildSmallTable() {
    double columnWidth = Get.size.width * 0.689;
    return Align(
      alignment: Alignment.topRight,
      child: SizedBox(
        width: columnWidth,
        child: Padding(
          padding: const EdgeInsets.only(right: 17),
          child: Container(
            margin: EdgeInsets.symmetric(vertical: 20),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: [
                HeaderRowSmall(),
                Obx(() => Row(
                      children: [
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              controller.isCustomerSelected.value
                                  ? controller.selectedBrand!.value
                                  : '',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              controller.isCustomerSelected.value
                                  ? controller.selectedPower!.value
                                  : '',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              (controller.isCustomerSelected.value &&
                                      controller.isCylinderEnabled())
                                  ? controller.selectedCylinder!.value
                                  : '',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              (controller.isCustomerSelected.value &&
                                      controller.isAxisEnabled())
                                  ? controller.selectedAxis!.value
                                  : '',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              (controller.isCustomerSelected.value &&
                                      controller.isAddEnabled())
                                  ? controller.selectedAdd!.value
                                  : '',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                      ],
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }

  InputDecoration getDropdownDecoration() {
    return InputDecoration(
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(30.0),
        borderSide: BorderSide(color: Colors.teal.shade200),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(30.0),
        borderSide: BorderSide(color: Colors.teal.shade200),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(30.0),
        borderSide: BorderSide(color: Colors.teal.shade200),
      ),
      filled: true,
      fillColor: Colors.teal.shade50,
      contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 0),
    );
  }
}

class HeaderRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
       decoration: BoxDecoration(
        color: Colors.teal.shade200,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8)),
      ),
      child: Row(
        children: const [
          Expanded(child: Text('POWERS', textAlign: TextAlign.center)),
          Expanded(child: Text('CYLINDERS', textAlign: TextAlign.center)),
          Expanded(child: Text('AXIS', textAlign: TextAlign.center)),
          Expanded(child: Text('ADD', textAlign: TextAlign.center)),
        ],
      ),
    );
  }
}

class HeaderRowSmall extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.teal.shade200,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8)),
      ),
      child: Row(
        children: const [
          Expanded(
              child: Text('BRAND INDICATION', textAlign: TextAlign.center)),
          Expanded(child: Text('POWERS', textAlign: TextAlign.center)),
          Expanded(child: Text('CYLINDERS', textAlign: TextAlign.center)),
          Expanded(child: Text('AXIS', textAlign: TextAlign.center)),
          Expanded(child: Text('ADD', textAlign: TextAlign.center)),
        ],
      ),
    );
  }
}

class PickerColumn extends StatefulWidget {
  final List<String> data;
  final String title;
  final Function(String) onSelectedItemChanged;
  final bool isEnabled;
  final bool isCustomerSelected;
  final bool showRightDivider;

  const PickerColumn({
    Key? key,
    required this.data,
    required this.title,
    required this.onSelectedItemChanged,
    required this.isEnabled,
    required this.isCustomerSelected,
    this.showRightDivider = false,
  }) : super(key: key);

  @override
  _PickerColumnState createState() => _PickerColumnState();
}

class _PickerColumnState extends State<PickerColumn> {
  late FixedExtentScrollController _controller;
  int _selectedIndex = 0;

  @override
  void initState() {
    super.initState();
    _controller = FixedExtentScrollController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double itemHeight = 60.0;
    final double highlightHeight = 28.0;

    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final double middleOfViewport = constraints.maxHeight / 2;
        final double topOfHighlightBar =
            middleOfViewport - (highlightHeight / 2);

        return Stack(
          children: [
            AbsorbPointer(
              absorbing: !widget.isEnabled || !widget.isCustomerSelected,
              child: Opacity(
                opacity: !widget.isEnabled
                    ? 0.0
                    : (widget.isCustomerSelected ? 1.0 : 0.5),
                child: ListWheelScrollView.useDelegate(
                  controller: _controller,
                  itemExtent: itemHeight,
                  physics: widget.isCustomerSelected
                      ? FixedExtentScrollPhysics()
                      : NeverScrollableScrollPhysics(),
                  onSelectedItemChanged: (index) {
                    if (widget.isCustomerSelected) {
                      setState(() {
                        _selectedIndex = index;
                      });
                      widget.onSelectedItemChanged(widget.data[index]);
                    }
                  },
                  childDelegate: ListWheelChildBuilderDelegate(
                    builder: (BuildContext context, int index) {
                      return Center(
                        child: Text(
                          widget.data[index],
                          style: TextStyle(
                            fontSize: 24,
                            color: _selectedIndex == index
                                ? Colors.teal
                                : Colors.black,
                          ),
                        ),
                      );
                    },
                    childCount: widget.data.length,
                  ),
                ),
              ),
            ),
            Positioned(
              top: topOfHighlightBar,
              left: 0,
              right: 0,
              child: Container(
                width: double.infinity,
                height: highlightHeight,
                decoration: BoxDecoration(
                  color: Colors.teal.shade200.withOpacity(0.5),
                ),
              ),
            ),
            if (widget.showRightDivider)
              Positioned(
                top: 0,
                bottom: 0,
                right: 0,
                child: VerticalDivider(
                  color: Colors.teal.shade200,
                  width: 1,
                  thickness: 3,
                ),
              ),
          ],
        );
      },
    );
  }
}


the scrolling values are moving above the the respective text like power,axis..