import 'dart:ffi';
import 'package:cheminova/controller/get_order_placed_controller.dart';
import 'package:cheminova/models/added_by_model.dart';
import 'package:cheminova/models/category_model.dart';
import 'package:cheminova/utils/show_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../controller/cart_controller.dart';
import '../../controller/place_order_controller.dart';
import '../../controller/place_order_service.dart';
import '../../controller/product_controller.dart';
import '../../controller/product_service.dart';
import '../../models/brand_model.dart';
import '../../models/oder_place_model.dart';
import '../../models/product_model1.dart';
import '../../widgets/my_drawer.dart';
import '../../widgets/product_card.dart';
import 'order_confermation_screen.dart';

class CheckoutScreen extends StatefulWidget {
  final Product? productModel;

  PlacedOrderModel? placeOrder;
   List<Product>? selectedProducts;
  CheckoutScreen({super.key, this.productModel, this.placeOrder,this.selectedProducts});

  @override
  State<CheckoutScreen> createState() => _CheckoutScreenState();
}

class _CheckoutScreenState extends State<CheckoutScreen> {
  final CartController _cartController = Get.put(CartController());
  final ProductService _productService = ProductService();
  final ProductController _productController = Get.put(ProductController());
  final OrderPlacedController _orderPlacedController =
  Get.put(OrderPlacedController());
  final GetPlacedOrderController _getPlacedOrderController = Get.put(GetPlacedOrderController());

  int currentPage = 1;
  String _groupValue = "cheque";

  final List<String> _addressList = [
    'Home - 123 Street, City',
    'Office - 456 Avenue, City',
    'Warehouse - 789 Blvd, City',
  ];

  String? _selectedShippingAddress;
  String? _selectedBillingAddress;

  @override
  void initState() {
    super.initState();
    // _getOrder();
    _loadSelectedAddress();
    _loadSelectedPaymentMode();

    if (_addressList.isNotEmpty) {
      _selectedShippingAddress = _addressList.first;
      _selectedBillingAddress = _addressList.first;
    }
  }

  void _saveSelectedAddress() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('selectedShippingAddress', _selectedShippingAddress!);
    await prefs.setString('selectedBillingAddress', _selectedBillingAddress!);
  }

  void _onShippingAddressChanged(String? value) {
    setState(() {
      _selectedShippingAddress = value;
    });
    _saveSelectedAddress();
  }

  void _onBillingAddressChanged(String? value) {
    setState(() {
      _selectedBillingAddress = value;
    });
    _saveSelectedAddress();
  }

  void _loadSelectedAddress() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _selectedShippingAddress =
          prefs.getString('selectedShippingAddress') ?? _addressList.first;
      _selectedBillingAddress =
          prefs.getString('selectedBillingAddress') ?? _addressList.first;
    });
  }

  void _onPaymentModeChanged(String? value) {
    setState(() {
      _groupValue = value!;
    });
    _saveSelectedPaymentMode();
  }

  void _saveSelectedPaymentMode() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('selectedPaymentMode', _groupValue);
  }

  void _loadSelectedPaymentMode() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _groupValue = prefs.getString('selectedPaymentMode') ?? 'cheque';
    });
  }

  // void _getOrder(){
  // final details =  _getPlacedOrderController.getOrder(widget.productModel!.id);
  // print("dffgfg,$details");
  // }
  void _onPlaceOrder() async {
    try {
      // Map the cart items (Product) to OrderItem objects
      List<OrderItem> orderItems = _cartController.selectedProducts.map<OrderItem>((product) {
        return OrderItem(
          id: product.id,
          name: product.name,
          price: product.price.toDouble(),
          sku: product.sku,
          gst: product.gst.toDouble(),
          hsnCode: product.hsnCode,
          description: product.description,
          productStatus: product.productStatus,
          image: [],
          createdAt: product.createdAt,
          updatedAt: product.createdAt,
          count: product.quantity,

          //category:product.category,
          category:Category(id: product.category.id, categoryName: product.category.categoryName),
          // brand:product.brand,
          brand:Brand(id: product.brand.id, brandName: product.brand.brandName),
          v: 0, addedBy: product.addedBy,
        );
      }).toList();

      // Update the placedOrder1 value
      _orderPlacedController.placedOrder1.value= PlacedOrderModel(
        paymentMode: _groupValue,
        shipTo: _selectedShippingAddress!,
        billTo: _selectedBillingAddress!,
        orderItems: orderItems,
        gstTotal: _cartController.gstTotal.value,
        grandTotal: _cartController.grandTotal.value,
        subtotal: _cartController.subtotal.value,
      );

      await _orderPlacedController.placeOrder();

      if (_orderPlacedController.isLoading.value) {
        showSnackbar("Order Placed Successfully");
        Get.to(() => OrderConfermationScreen(
          placedOrder: _orderPlacedController.placedOrder1.value,
        ));
      }
    } catch (e) {
      print("PlaceOrderScreen error: $e");
    }
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Builder(
          builder: (context) {
            return GestureDetector(
              onTap: () => Scaffold.of(context).openDrawer(),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: SvgPicture.asset(
                  'assets/svg/menu.svg',
                ),
              ),
            );
          },
        ),
        actions: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Padding(
              padding: EdgeInsets.all(Get.width * 0.02),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg',
              ),
            ),
          ),
        ],
        title: const Text("Checkout"),
      ),
      drawer:  MyDrawer(),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: Column(
              children: [
                SizedBox(height: Get.height * 0.02),
                Card(
                  margin: EdgeInsets.symmetric(horizontal: Get.width * 0.05),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(19),
                    side: const BorderSide(color: Color(0xFFFDFDFD)),
                  ),
                  color: const Color(0xFFB4D1E5).withOpacity(0.9),
                  child: Padding(
                    padding: EdgeInsets.all(Get.width * 0.04),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: Get.width * 0.04),
                          child: Text(
                            'Shipping Information',
                            style: GoogleFonts.roboto(
                              fontSize: Get.width * 0.04,
                              fontWeight: FontWeight.w500,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        SizedBox(height: 5,),
                        DropdownButtonFormField<String>(
                          decoration: InputDecoration(
                            labelText: 'Shipping Address:',
                            hintText: 'Select Shipping Address',
                            border: OutlineInputBorder(),
                          ),
                          value: _selectedShippingAddress,
                          items: _addressList.map((String address) {
                            return DropdownMenuItem<String>(
                              value: address,
                              child: Text(address),
                            );
                          }).toList(),
                          onChanged: _onShippingAddressChanged,
                        ),
                        SizedBox(height: Get.height * 0.02),
                        DropdownButtonFormField<String>(
                          decoration: InputDecoration(
                            labelText: 'Billing Address:',
                            hintText: 'Select Billing Address',
                            border: OutlineInputBorder(),
                          ),
                          value: _selectedBillingAddress,
                          items: _addressList.map((String address) {
                            return DropdownMenuItem<String>(
                              value: address,
                              child: Text(address),
                            );
                          }).toList(),
                          onChanged: _onBillingAddressChanged,
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: Get.width * 0.04),
                          child: Text(
                            'Payment Information',
                            style: GoogleFonts.roboto(
                              fontSize: Get.width * 0.04,
                              fontWeight: FontWeight.w500,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Card(
                          child: ListView(
                            padding: EdgeInsets.zero,
                            shrinkWrap: true,
                            children: [
                              SizedBox(
                                height: Get.height * 0.035,
                                child: RadioListTile(
                                  title: const Text("Cheque"),
                                  contentPadding: EdgeInsets.zero,
                                  value: "cheque",
                                  groupValue: _groupValue,
                                  onChanged: _onPaymentModeChanged,
                                ),
                              ),
                              SizedBox(
                                height: Get.height * 0.035,
                                child: RadioListTile(
                                  title: const Text("Online transfer"),
                                  contentPadding: EdgeInsets.zero,
                                  value: "online-transfer",
                                  groupValue: _groupValue,
                                  onChanged: _onPaymentModeChanged,
                                ),
                              ),
                              SizedBox(
                                child: RadioListTile(
                                  title: const Text("Credit"),
                                  contentPadding: EdgeInsets.zero,
                                  value: "credit",
                                  groupValue: _groupValue,
                                  onChanged: _onPaymentModeChanged,
                                ),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: Get.width * 0.04),
                          child: Text(
                            'Order Summary',
                            style: GoogleFonts.roboto(
                              fontSize: Get.width * 0.04,
                              fontWeight: FontWeight.w500,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Card(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                height: Get.height * 0.22,
                                child: Padding(
                                  padding: EdgeInsets.all(Get.width * 0.02),
                                  child: ListView.builder(
                                    itemCount:  _cartController.selectedProducts.length,
                                    itemBuilder: (context, index) {
                                      final cartItem =
                                      _cartController.cartList[index];
                                      return   ProductCard(
                                        productModel:_cartController.selectedProducts[index] ,
                                        isCheckout: true,
                                        quantity: _cartController.cartList[0].quantity,


                                        //   ListTile(
                                        //   title: Text(cartItem.name ?? 'N/A'),
                                        //   subtitle: Text(
                                        //       'Quantity: ${cartItem.quantity}'),
                                        //   trailing: Text(
                                        //       'Price: \₹${cartItem.price.toStringAsFixed(2)}'),
                                        // );
                                      );},
                                  ),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.all(Get.width * 0.02),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('Subtotal',style: TextStyle(fontWeight: FontWeight.bold)),
                                        Text('₹${_cartController.subtotal.value.toStringAsFixed(2)}'),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('GST',style: TextStyle(fontWeight: FontWeight.bold)),
                                        Text('₹${_cartController.gstTotal.value.toStringAsFixed(2)}'),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('Total Amount',style: TextStyle(fontWeight: FontWeight.bold)),
                                        Text('₹${_cartController.grandTotal.value.toStringAsFixed(2)}'),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),

                      ],
                    ),
                  ),
                ),
                SizedBox(height: 10.0,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: _onPlaceOrder,
                      style: ElevatedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: const Color(0xFF00784C),
                        padding: EdgeInsets.symmetric(
                            horizontal: Get.width * 0.20,
                            vertical: Get.height * 0.02),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      child: const Text("Place Order"),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}