import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:intl/intl.dart';

import '../../../Globalwidgets/textwidget.dart';
import '../../../Helper/Constants/Colorconstants.dart';
import '../../../Model/Response/Summary/Getsummarysresponse.dart';
import '../../../Model/Response/products/product_info.dart';
import '../orderDetails.dart';

class OrderDetailsPage extends StatelessWidget {
  final DeliveriesDetails orderDetails;
  final List<ProductDetails> productDetails;

  const OrderDetailsPage({
    super.key,
    required this.productDetails,
    required this.orderDetails,
  });

  // to replace "null" with empty text
  String safe(String? v) {
    if (v == null || v == "null") return "";
    return v;
  }

  // to avoid crash when parsing date
  DateTime safeParseDate(String? date) {
    if (date == null || date.isEmpty || date == "null") {
      return DateTime.now();
    }
    try {
      return DateTime.parse(date);
    } catch (e) {
      print("Invalid date received: $date");
      return DateTime.now();
    }
  }

  bool isValidLatLng(double lat, double lng) {
    return lat != 0.0 && lng != 0.0;
  }

  @override
  Widget build(BuildContext context) {
    double totalAmount = 0;
    double totalTax = 0;

    for (var product in productDetails) {
      totalAmount += product.productsumprice ?? 0.0;
      totalTax += product.taxamount ?? 0.0;
    }

    final totalWithTax = totalAmount + totalTax;

    final DateTime dateTime = safeParseDate(orderDetails.deliverydate);
    final String formattedDate = DateFormat('dd-MM-yy').format(dateTime);
    final String formattedTime = DateFormat('hh:mm a').format(dateTime);

    final pickupLat = double.tryParse(safe(orderDetails.pickuplat)) ?? 0.0;
    final pickupLng = double.tryParse(safe(orderDetails.pickuplon)) ?? 0.0;
    final deliveryLat = double.tryParse(safe(orderDetails.deliverylat)) ?? 0.0;
    final deliveryLng = double.tryParse(safe(orderDetails.deliverylong)) ?? 0.0;

    final bool showMap = isValidLatLng(pickupLat, pickupLng) &&
        isValidLatLng(deliveryLat, deliveryLng);

    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: true,
          title: TextWidget(
            text: 'Order Details',
            fontSize: 20,
            fontWeight: FontWeight.w700,
          ),
          backgroundColor: ColorConstants.secondaryColor,
          leading: InkWell(
              onTap: () {
                Get.back();
              },
              child: Icon(
                Icons.arrow_back,
                color: ColorConstants.blackColor,
              )),
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _sectionCard(
                icon: Icons.receipt_long,
                title: "Order Info",
                children: [
                  _infoRow("Order ID", safe(orderDetails.orderid)),
                  _infoRow("Date", formattedDate),
                  _infoRow("Time", formattedTime),
                ],
              ),
              const SizedBox(height: 12),
              _sectionCard(
                icon: Icons.shopping_cart,
                title: "Products",
                children: [
                  ...productDetails.map((product) => Padding(
                    padding: const EdgeInsets.symmetric(vertical: 6),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                            child: Text(
                                "${safe(product.productname)} x${product.orderqty}")),
                        Text(
                          "₹${((product.price ?? 0) * (product.orderqty ?? 0)).toStringAsFixed(0)}",
                          style: const TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                  )),
                  const Divider(height: 24),
                  _infoRow("Amount", "₹${totalAmount.toStringAsFixed(2)}",
                      isForProducts: true),
                  _infoRow("Tax", "₹${totalTax.toStringAsFixed(2)}",
                      isForProducts: true),
                  _infoRow("Total", "₹${totalWithTax.toStringAsFixed(2)}",
                      isForProducts: true),
                ],
              ),
              const SizedBox(height: 12),
              _sectionCard(
                icon: Icons.person,
                title: "Customer",
                children: [
                  _infoRow("Name", safe(orderDetails.deliverycustomer)),
                  _infoRow("Address", safe(orderDetails.deliveryaddress)),
                  _infoRow("Phone", safe(orderDetails.deliverycontactno)),
                ],
              ),
              const SizedBox(height: 12),
              Visibility(
                visible: safe(orderDetails.ridername).isNotEmpty,
                child: _sectionCard(
                  icon: Icons.delivery_dining,
                  title: "Rider",
                  children: [
                    _infoRow("Name", safe(orderDetails.ridername)),
                    _infoRow("Phone", safe(orderDetails.ridercontact)),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                height: 200,
                child: OrderStatusTimeline(
                  stages: [
                    Stage(
                      label: "Accepted",
                      icon: Icons.check,
                      completed: safe(orderDetails.starttime).isNotEmpty,
                      time: convertTo12HourFormat(safe(orderDetails.starttime)),
                    ),
                    Stage(
                      label: "Arrived",
                      icon: Icons.location_on,
                      completed: safe(orderDetails.arrivaltime).isNotEmpty,
                      time: convertTo12HourFormat(safe(orderDetails.arrivaltime)),
                    ),
                    Stage(
                      label: "Picked",
                      icon: Icons.shopping_bag,
                      completed: safe(orderDetails.pickuptime).isNotEmpty,
                      time: convertTo12HourFormat(safe(orderDetails.pickuptime)),
                    ),
                    Stage(
                      label: "Delivered",
                      icon: Icons.delivery_dining,
                      completed: safe(orderDetails.deliverytime).isNotEmpty,
                      time: convertTo12HourFormat(safe(orderDetails.deliverytime)),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 12),

              // Only show map if lat/lng are valid (not 0.0)
              if (showMap)
                SizedBox(
                  height: 300,
                  child: MapWithPolyLines(
                    startLatLng: LatLng(pickupLat, pickupLng),
                    endLatLng: LatLng(deliveryLat, deliveryLng),
                  ),
                )
              else
                Container(
                  height: 80,
                  alignment: Alignment.center,
                  child: Text("Map not available"),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _sectionCard({
    required IconData icon,
    required String title,
    String? Amount,
    String? TaxAmount,
    String? Total,
    required List<Widget> children,
  }) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: ColorConstants.secondaryColor,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, size: 20, color: ColorConstants.primaryColor),
              const SizedBox(width: 8),
              Text(title,
                  style: const TextStyle(
                      fontWeight: FontWeight.w600, fontSize: 16)),
            ],
          ),
          const Divider(),
          ...children,
        ],
      ),
    );
  }

  Widget _infoRow(String label, String value, {bool? isForProducts}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              label,
              style: const TextStyle(color: Colors.black54),
            ),
          ),
          (isForProducts ?? false) ? Spacer() : const SizedBox(width: 8),
          (isForProducts ?? false)
              ? Text(
            value,
            style: const TextStyle(fontWeight: FontWeight.w500),
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
          )
              : Expanded(
            child: Text(
              value,
              style: const TextStyle(fontWeight: FontWeight.w500),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  showBottomSheet(BuildContext context, {required VoidCallback onAccept}) {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
        ),
        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.all(16.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Center(
                  child: Container(
                    width: 40,
                    height: 5,
                    margin: EdgeInsets.symmetric(vertical: 8.0),
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2.5),
                    ),
                  ),
                ),
                SizedBox(height: 16.0),
                Text(
                  'Confirm Order',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 16.0),
                Text(
                  'Accept this order and assign a rider?',
                  style: TextStyle(fontSize: 16),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 24.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.grey[300],
                          foregroundColor: Colors.black,
                          padding: EdgeInsets.symmetric(vertical: 16.0),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0),
                          ),
                        ),
                        child: TextWidget(text: 'Cancel'),
                      ),
                    ),
                    SizedBox(width: 16.0),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          onAccept();
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: ColorConstants.primaryColor,
                          padding: EdgeInsets.symmetric(vertical: 16.0),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0),
                          ),
                        ),
                        child: TextWidget(
                          text: 'Accept',
                          color: ColorConstants.secondaryColor,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16.0),
              ],
            ),
          );
        });
  }
}

// ──────────────────────────────────────────────────────────
// MAP WITH POLYLINES — SAFE (NO CRASH)
// ──────────────────────────────────────────────────────────

class MapWithPolyLines extends StatelessWidget {
  final LatLng startLatLng;
  final LatLng endLatLng;

  const MapWithPolyLines({
    super.key,
    required this.startLatLng,
    required this.endLatLng,
  });

  Set<Polyline> _createPolylines() {
    final polylineCoordinates = [
      startLatLng,
      endLatLng,
    ];

    return {
      Polyline(
        polylineId: const PolylineId('route1'),
        visible: true,
        points: polylineCoordinates,
        color: Colors.blue,
        width: 5,
      ),
    };
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: ColorConstants.secondaryColor,
        borderRadius: BorderRadius.circular(12),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: GoogleMap(
          initialCameraPosition: CameraPosition(
            target: startLatLng,
            zoom: 13.0,
          ),
          onMapCreated: (GoogleMapController controller) {},
          polylines: _createPolylines(),
          markers: {
            Marker(
              markerId: const MarkerId("start"),
              position: startLatLng,
            ),
            Marker(
              markerId: const MarkerId("end"),
              position: endLatLng,
            ),
          },
        ),
      ),
    );
  }
}
