import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:grocery_app/src/common_widget/network_image.dart';
import 'package:grocery_app/src/core/routes/routes.dart';
import 'package:grocery_app/src/logic/provider/order_provider.dart';
import 'package:grocery_app/src/ui/data_notfound.dart';
import 'package:grocery_app/utils/constants/assets_constant.dart';
import 'package:grocery_app/utils/constants/color_constant.dart';
import 'package:grocery_app/utils/extensions/extensions.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class MyOrderScreen extends StatefulWidget {
  @override
  State<MyOrderScreen> createState() => _MyOrderScreenState();
}

class _MyOrderScreenState extends State<MyOrderScreen> {
  @override
  void initState() {
    Provider.of<OrderProvider>(context, listen: false).getMyOrder(context);
    super.initState();
  }

  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 {
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      Provider.of<OrderProvider>(context, listen: false).getMyOrder(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true,
          leading: Center(
            child: SizedBox(
              height: 20,
              width: 20,
              child: InkWell(
                  onTap: () {
                    context.clearAndPush(routePath: MyRoutes.BOTTOMNAV);
                  },
                  child: SvgPicture.asset(
                    APPASSETS.back,
                    height: 20,
                    width: 20,
                  )),
            ),
          ),
          title: const Text(
            "My Order",
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
        body: RefreshIndicator(
          onRefresh: _refresh,
          child:
              Consumer<OrderProvider>(builder: (context, orderProvider, child) {
            if (orderProvider.isloading) {
              return Center(child: CircularProgressIndicator());
            }

            if (orderProvider.orderList.isEmpty) {
              return Center(
                  child: DataNotFound(
                imagePath: 'assets/images/wishlist.jpg',
                message: "No Order Available!    ",
                //  width: 200.w,
                //  height: 200.h,
              ));
            }

            return Column(
              children: [
                Expanded(
                  child: ListView.builder(
                    itemCount: orderProvider.orderList.length,
                    itemBuilder: (context, index) {
                      final order = orderProvider.orderList[index];

                      return InkWell(
                        onTap: () {
                          context.pushNamed(MyRoutes.ORDERDETAILS,
                              extra: order);
                          //context.push(MyRoutes.ORDERDETAILS);
                        },
                        child: Card(
                          margin:
                              EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Center(
                                      child: Container(
                                        width: 50,
                                        height: 50,
                                        decoration: BoxDecoration(
                                          color: APPCOLOR.bgGrey,
                                          borderRadius:
                                              BorderRadius.circular(15),
                                        ),
                                        child: Stack(
                                          alignment: Alignment.center,
                                          children: [
                                            AppNetworkImage(
                                              height: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.08,
                                              width: 48,
                                              imageUrl: order.orderItems!.first
                                                  .productImage,
                                              backGroundColor:
                                                  Colors.transparent,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    SizedBox(width: 5),
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(order.orderNumber,
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold)),
                                        Text(order.paymentStatus ?? "",
                                            style:
                                                TextStyle(color: Colors.grey)),
                                        Text(
                                            order.totalItems.toString() +
                                                " items",
                                            style:
                                                TextStyle(color: Colors.grey)),
                                      ],
                                    ),
                                    Spacer(),

                                    // Container(
                                    //   padding: EdgeInsets.symmetric(
                                    //       horizontal: 5, vertical: 5),
                                    //   decoration: BoxDecoration(
                                    //     color: Colors.green.shade100,
                                    //     borderRadius: BorderRadius.circular(10),
                                    //   ),
                                    //   child: Text(order.orderStatus,
                                    //       style: TextStyle(color: Colors.green)),
                                    // ),
                                  ],
                                ),
                                SizedBox(height: 10),
                                Text(
                                    convertUtcToIst(order.updatedAt.toString()),
                                    style: TextStyle(color: Colors.grey)),
                                SizedBox(height: 5),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text("\$" + order.finalTotal,
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold)),
                                    Row(
                                      children: [
                                        // ElevatedButton(
                                        //   onPressed: () {},
                                        //   style: ElevatedButton.styleFrom(
                                        //     backgroundColor: Colors.white,
                                        //     side: BorderSide(color: Colors.green),
                                        //     shape: RoundedRectangleBorder(
                                        //       borderRadius:
                                        //           BorderRadius.circular(10),
                                        //     ),
                                        //   ),
                                        //   child: Row(
                                        //     children: [
                                        //       // Icon(Icons.message,
                                        //       //     color: Colors.green),
                                        //       // SizedBox(width: 5),
                                        //       // Text('Message',
                                        //       //     style: TextStyle(
                                        //       //         color: Colors.green)),
                                        //     ],
                                        //   ),
                                        // ),
                                        SizedBox(width: 10),
                                        ElevatedButton(
                                          onPressed: () {
                                            print("lkdhgkjdfgj");
                                            _makePhoneCall(order
                                                .stores!.first.vendor!.phone);
                                          },
                                          style: ElevatedButton.styleFrom(
                                            backgroundColor: Colors.green,
                                            shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(10),
                                            ),
                                          ),
                                          child: Row(
                                            children: [
                                              Icon(Icons.call,
                                                  color: Colors.white),
                                              SizedBox(width: 5),
                                              Text('Call',
                                                  style: TextStyle(
                                                      color: Colors.white)),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
          }),
        ));
  }

  Future<void> _makePhoneCall(String number) async {
    try {
      final Uri phoneUri = Uri(scheme: 'tel', path: number);
      if (await canLaunchUrl(phoneUri)) {
        await launchUrl(phoneUri);
      } else {
        throw 'Could not launch $phoneUri';
      }
    } catch (e) {
      print("Error launching phone call: $e");
    }
  }
}
