import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:grocery_app/src/common_widget/network_image.dart';
import 'package:grocery_app/src/data/myOrder.dart';
import 'package:grocery_app/src/logic/provider/order_provider.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class OrderDetailsScreen extends StatefulWidget {
  Datum order;

  OrderDetailsScreen({Key? key, required this.order}) : super(key: key);

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

class _OrderDetailsScreenState extends State<OrderDetailsScreen> {
  String convertUtcToIst(String utcTime) {
    DateTime utcDateTime = DateTime.parse(utcTime).toUtc();

    DateTime istDateTime =
        utcDateTime.add(const Duration(hours: 5, minutes: 30));

    String formattedDateTime =
        DateFormat("dd-MM-yyyy hh:mm a").format(istDateTime);

    return formattedDateTime;
  }

  Future<void> _refresh() async {
    Provider.of<OrderProvider>(context, listen: false).getMyOrder(context);
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      _fetchOrderDetails();
    });
  }

  Future<void> _fetchOrderDetails() async {
    // Get the updated order from Provider

    final homeProvider = Provider.of<OrderProvider>(context, listen: false);

    widget.order = homeProvider.orderList.firstWhere(
      (o) => o.id == widget.order.id,
      orElse: () => widget.order,
    );

    print("kdjhkjfh   ${widget.order}");

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Order Details')),
        body: RefreshIndicator(
          onRefresh: _refresh,
          child: Padding(
            padding: const EdgeInsets.all(2.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(widget.order.orderNumber,
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold)),
                        SizedBox(height: 5),
                        Text(widget.order.deliveryAddress!.addressLine ?? " ",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold)),
                        SizedBox(height: 5),
                        Text(
                            convertUtcToIst(widget.order.createdAt.toString())),
                        SizedBox(height: 5),
                        // Text(
                        //   "Status: ${_getStatusText(widget.order.orderStatus)}",
                        //   style: TextStyle(
                        //       color: Colors.blue, fontWeight: FontWeight.bold),
                        // ),
                        // _itemsList(),
                      ],
                    ),
                  ),
                ),
                _itemsList(),
                SizedBox(height: 20),
              ],
            ),
          ),
        ));
  }

  /// Order Information
  Widget _orderInfo() {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Container(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(widget.order.orderNumber,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              SizedBox(height: 5),
              Text(widget.order.deliveryAddress!.addressLine ?? " ",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              SizedBox(height: 5),
              Text(convertUtcToIst(widget.order.createdAt.toString())),
              SizedBox(height: 5),
              Text(
                "Status: ${_getStatusText(widget.order.orderStatus)}",
                style:
                    TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
              ),
              // _itemsList(),
            ],
          ),
        ),
      ),
    );
  }

  final List<String> statuses = [
    "PENDING",
    "PROCESSING",
    "SHIPPED",
    "DELIVERED"
  ];

  Widget _animatedShippingTimeline(orderItemStatus) {
    var currentStep = statuses.indexOf(orderItemStatus);

    return Row(
      mainAxisAlignment: MainAxisAlignment.start, // Align items properly
      children: [
        for (int i = 0; i < statuses.length; i++)
          _timelineStep(i, statuses[i], currentStep),
      ],
    );
  }

  Widget _timelineStep(int step, String status, currentStep) {
    bool isCompleted = step <= currentStep;

    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        AnimatedContainer(
          duration: Duration(milliseconds: 500),
          width: 15,
          height: 15,
          decoration: BoxDecoration(
            color: isCompleted ? Colors.green : Colors.grey,
            shape: BoxShape.circle,
          ),
          child: Icon(Icons.check, size: 12, color: Colors.white),
        ),
        SizedBox(width: 5),
        Text(
          status,
          style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
        ),
        if (step < statuses.length - 1) ...[
          SizedBox(width: 5),
          AnimatedContainer(
            duration: Duration(milliseconds: 500),
            width: 15,
            height: 3,
            color: isCompleted ? Colors.green : Colors.grey,
          ),
          SizedBox(width: 5),
        ],
      ],
    );
  }

//  PENDING PROCESSING  SHIPPED  DELIVERED  CANCELLED   RETURNED)

  String _getStatusTextForStep(orderStatus) {
    switch (orderStatus) {
      case 'PENDING':
        return "PENDING";
      case 'SHIPPED':
        return "SHIPPED";
      case 'PROCESSING':
        return "PROCESSING";
      case 'DELIVERED':
        return "DELIVERED";

      default:
        return "";
    }
  }

  String _getStatusText(orderStatus) {
    switch (orderStatus) {
      case 'PENDING':
        return "PENDING";
      case 'SHIPPED':
        return "SHIPPED";
      case 'DELIVERD':
        return "DELIVERD";
      default:
        return "";
    }
  }

  /// List of Ordered Items
  Widget _itemsList() {
    return Expanded(
      child: ListView.builder(
        itemCount: widget.order.orderItems!.length,
        itemBuilder: (context, index) {
          //  final item = items[index];
          var orderitem = widget.order.orderItems![index];

          print("ckgjhkfghlfg   ${orderitem.orderItemStatus}");
          return Card(
            margin: EdgeInsets.symmetric(vertical: 2),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      if (orderitem.orderItemStatus == "PENDING")
                        InkWell(
                          onTap: () async {
                            var status = await Provider.of<OrderProvider>(
                                    context,
                                    listen: false)
                                .updateStatus(
                                    context, "CANCELLED", orderitem.id);
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 5, vertical: 5),
                            decoration: BoxDecoration(
                              color: Colors.green.shade100,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: Text(" Cancel ",
                                style: TextStyle(color: Colors.black)),
                          ),
                        ),
                      Gap(5),
                      if (orderitem.orderItemStatus != "PENDING" &&
                          orderitem.orderItemStatus != "CANCELLED")
                        RichText(
                          text: TextSpan(
                            text: " ",
                            style: context.buttonTestStyle.copyWith(
                              color: context.appColor.blackColor,
                            ),
                            children: [
                              TextSpan(
                                text: "GET OTP",
                                style: context.buttonTestStyle.copyWith(
                                  color: Colors.blue,
                                  decoration: TextDecoration.underline,
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Provider.of<OrderProvider>(context,
                                            listen: false)
                                        .getAssignedOtp(context, orderitem.id);
                                  },
                              ),
                            ],
                          ),
                        ),
                      if (orderitem.orderItemStatus == "DELIVERED")
                        RichText(
                          text: TextSpan(
                            text: " ",
                            style: context.buttonTestStyle.copyWith(
                              color: context.appColor.blackColor,
                            ),
                            children: [
                              TextSpan(
                                text: "Give Feedback",
                                style: context.buttonTestStyle.copyWith(
                                  color: Colors.blue,
                                  decoration: TextDecoration.underline,
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {},
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                ),
                ListTile(
                  leading: Container(
                    width: 50,
                    height: 50,
                    child: AppNetworkImage(
                      height: MediaQuery.of(context).size.height * 0.08,
                      width: 48,
                      imageUrl: orderitem.productImage ?? "",
                      backGroundColor: Colors.transparent,
                    ),
                  ),
                  title: Text(orderitem.productName ?? ""),
                  subtitle: Text("Qty: ${orderitem.quantity.toString()}"),
                  trailing: Text("₹${orderitem.totalOrderItemPrice ?? ""}",
                      style: TextStyle(fontWeight: FontWeight.bold)),
                ),
                if (orderitem.orderItemStatus == "CANCELLED") ...{
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text("Order Cancelled",
                        style: TextStyle(
                            color: Colors.black, fontWeight: FontWeight.bold)),
                  )
                } else ...{
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: _animatedShippingTimeline(orderitem.orderItemStatus),
                  ),
                }
              ],
            ),
          );
        },
      ),
    );
  }

  // Widget _cancelButton() {
  //   return ElevatedButton(
  //     onPressed: currentStep < 2
  //         ? () {
  //             setState(() {
  //               currentStep = 2;
  //             });
  //           }
  //         : null,
  //     style: ElevatedButton.styleFrom(
  //       backgroundColor: Colors.red,
  //       disabledBackgroundColor: Colors.grey,
  //     ),
  //     child: Text("Cancel Order", style: TextStyle(color: Colors.white)),
  //   );
  // }
}
