import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:glowwheels/helpers/shopid_helper.dart';
import 'package:glowwheels/provider/order_provider.dart';
import 'package:glowwheels/provider/serviceboy_provider.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:glowwheels/models/order_model.dart';
import 'package:provider/provider.dart';
import 'package:glowwheels/models/serviceboy_model.dart';
import 'assign_serviceboy_dialog.dart';

class OrderCard extends StatefulWidget {
  final Order order;

  OrderCard({required this.order});

  @override
  State<OrderCard> createState() => _OrderCardState();
}

class _OrderCardState extends State<OrderCard> {
  ServiceBoy? assignedBoy;
  late String shopId = '';
  bool isLoading = false;
  late String orderStatus=widget.order.status;

  @override
  void initState() {
    assignedBoy = widget.order.assignedServiceBoy;
    super.initState();

  }



  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      margin: EdgeInsets.all(12),
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("Order Details", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
            SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                widget.order.service.vehicle.image.isNotEmpty
                    ? Image.network(
                  widget.order.service.vehicle.image,
                  width: 100,
                  height: 100,
                  fit: BoxFit.contain,
                )
                    : SizedBox(
                  width: 100,
                  height: 100,
                  child: Center(child: Icon(Icons.image_not_supported)),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: Column(
                    children: [
                      _buildRow("Customer Name", widget.order.user.name),
                      _buildRow("Mobile Number", widget.order.user.phone.toString()),
                      _buildRow("Service Type", widget.order.service.serviceType),
                      _buildRow("Service", widget.order.service.serviceName),
                      _buildRow("Price", widget.order.service.price.toString()),
                      _buildRow("Service Time", widget.order.timeSlot),
                      _buildRow("Service Date", widget.order.date),
                      (widget.order.address!=null)?_buildRow("Location", widget.order.address!):SizedBox(),

                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 12),
            Center(
              child: Text(
                widget.order.service.manufacture.manufacture +
                    " " +
                    widget.order.service.model.model,
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
            Divider(height: 28),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  onTap: () async {
                    String? newStatus;
                    String? dialogMessage;

                    if (orderStatus == "pending") {
                      newStatus = "confirmed";
                      dialogMessage = "Are you sure you want to change the status to Confirmed?";
                    } else if (orderStatus == "confirmed" && assignedBoy!=null) {
                      newStatus = "completed";
                      dialogMessage = "Are you sure you want to change the status to Completed?";
                    }

                    if (newStatus != null && dialogMessage != null) {
                      final confirm = await showDialog<bool>(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: const Text("Confirm Status Change"),
                          content: Text(dialogMessage!),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: const Text("Cancel"),
                            ),
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(true),
                              child: const Text("OK"),
                            ),
                          ],
                        ),
                      );

                      if (confirm == true) {
                        try {
                          setState(() => isLoading = true);
                          final orderProvider = Provider.of<OrdersProvider>(context, listen: false);
                          await orderProvider.updateOrderStatus(
                            orderId: widget.order.id,
                            status: newStatus,
                          );

                          setState(() {
                            orderStatus = newStatus!;
                          });

                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text("Order status updated to $newStatus")),
                          );
                        } catch (e) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text("Failed to update status: $e")),
                          );
                        } finally {
                          setState(() => isLoading = false);
                        }
                      }
                    }
                  },
                  child: Text(
                    orderStatus,
                    style: TextStyle(
                      color:orderStatus == "confirmed" || orderStatus == "completed"
                          ? Colors.green
                          : orderStatus == "pending"
                          ? Colors.orange
                          : Colors.red,
                      fontWeight: FontWeight.bold,
                      fontSize: 16,

                         // Visual cue for clickable
                    ),
                  ),
                ),


                if (assignedBoy == null &&
                    orderStatus.toLowerCase() == "confirmed")
                  ElevatedButton(
                    onPressed: isLoading
                        ? null
                        : () async {
                      setState(() {
                        isLoading = true;
                      });

                      final serviceBoyProvider =
                      Provider.of<ServiceBoyProvider>(context, listen: false);

                      final shopId = getShopId(context);
                      await serviceBoyProvider.fetchServiceBoys(shopId!);

                      final selected = await showDialog<ServiceBoy>(
                        context: context,
                        builder: (_) => AssignServiceBoyDialog(
                          serviceBoys: serviceBoyProvider.serviceBoys,
                          orderId: widget.order.id,
                        ),
                      );

                      if (selected != null) {
                        setState(() {
                          assignedBoy = selected;
                        });
                      }

                      setState(() {
                        isLoading = false;
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFF1B1464),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30)),
                    ),
                    child: isLoading
                        ? SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      ),
                    )
                        : Text(
                      "Assign",
                      style: GoogleFonts.inter(
                          fontSize: 12,
                          color: Colors.white,
                          fontWeight: FontWeight.w500),
                    ),
                  )
                else if (orderStatus.toLowerCase() == "pending")
                  ElevatedButton(
                    onPressed: () async{

                        final confirm = await showDialog<bool>(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: const Text("Confirm Status Change"),
                            content: Text("Are you sure you want to cancel the order?"!),
                            actions: [
                              TextButton(
                                onPressed: () => Navigator.of(context).pop(false),
                                child: const Text("Cancel"),
                              ),
                              TextButton(
                                onPressed: () => Navigator.of(context).pop(true),
                                child: const Text("OK"),
                              ),
                            ],
                          ),
                        );

                        if (confirm == true) {
                          try {
                            setState(() => isLoading = true);
                            final orderProvider = Provider.of<OrdersProvider>(context, listen: false);
                            await orderProvider.updateOrderStatus(
                              orderId: widget.order.id,
                              status: "cancelled by admin",
                            );

                            setState(() {
                              orderStatus = "cancelled by admin";
                            });

                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text("Order status updated to cancelled by admin")),
                            );
                          } catch (e) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text("Failed to update status: $e")),
                            );
                          } finally {
                            setState(() => isLoading = false);
                          }
                        }

                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
                    ),
                    child: Text(
                      "Cancel",
                      style: GoogleFonts.inter(
                          fontSize: 12, color: Colors.white, fontWeight: FontWeight.w500),
                    ),
                  )
                else if (orderStatus.toLowerCase() == "completed")
                    SizedBox()
                  else if (orderStatus.toLowerCase() == "cancelled by admin")
                      SizedBox()
                else if (assignedBoy != null)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("Assigned to: ${assignedBoy!.name}",
                            style: const TextStyle(fontWeight: FontWeight.bold)),
                        Text("Phone: ${assignedBoy!.phone}"),
                      ],
                    )


              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 3),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Text(label,
                style: GoogleFonts.inter(
                    fontSize: 10, color: Colors.black, fontWeight: FontWeight.w500)),
          ),
          Expanded(
            flex: 3,
            child: Text(value,
                style: GoogleFonts.inter(
                    fontSize: 10, color: Colors.black, fontWeight: FontWeight.w500)),
          ),
        ],
      ),
    );
  }
}
