import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart';
import 'package:Intaleq/views/widgets/mycircular.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../../constant/colors.dart';
import '../../../controller/functions/launch.dart';
import '../../../controller/home/profile/order_history_controller.dart';

// --- الويدجت الرئيسية بالتصميم الجديد ---
class OrderHistory extends StatelessWidget {
  const OrderHistory({super.key});

  @override
  Widget build(BuildContext context) {
    // نفس منطق استدعاء الكنترولر
    Get.put(OrderHistoryController());

    return MyScafolld(
      title: 'Order History'.tr,
      isleading: true,
      body: [
        GetBuilder<OrderHistoryController>(
          builder: (controller) {
            // --- نفس منطق التحميل والحالة الفارغة ---
            if (controller.isloading) {
              return const MyCircularProgressIndicator();
            }
            if (controller.orderHistoryListPassenger.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.map_outlined,
                        size: 80, color: AppColor.writeColor.withOpacity(0.4)),
                    const SizedBox(height: 16),
                    Text('No trip history found'.tr,
                        style: AppStyle.headTitle2),
                    Text("Your past trips will appear here.".tr,
                        style: AppStyle.subtitle),
                  ],
                ),
              );
            }
            // --- استخدام ListView.separated لفصل البطاقات ---
            return ListView.separated(
              padding: const EdgeInsets.all(16.0),
              itemCount: controller.orderHistoryListPassenger.length,
              separatorBuilder: (context, index) => const SizedBox(height: 16),
              itemBuilder: (BuildContext context, int index) {
                final ride = controller.orderHistoryListPassenger[index];
                // --- استدعاء ويدجت البطاقة الجديدة ---
                return _buildHistoryCard(context, ride);
              },
            );
          },
        )
      ],
    );
  }

  // --- ويدجت بناء بطاقة الرحلة ---
  Widget _buildHistoryCard(BuildContext context, Map<String, dynamic> ride) {
    // --- نفس منطق حساب إحداثيات الخريطة ---
    final LatLng startLocation = LatLng(
      double.parse(ride['start_location'].toString().split(',')[0]),
      double.parse(ride['start_location'].toString().split(',')[1]),
    );
    final LatLng endLocation = LatLng(
      double.parse(ride['end_location'].toString().split(',')[0]),
      double.parse(ride['end_location'].toString().split(',')[1]),
    );
    final LatLngBounds bounds = LatLngBounds(
      northeast: LatLng(
        startLocation.latitude > endLocation.latitude
            ? startLocation.latitude
            : endLocation.latitude,
        startLocation.longitude > endLocation.longitude
            ? startLocation.longitude
            : endLocation.longitude,
      ),
      southwest: LatLng(
        startLocation.latitude < endLocation.latitude
            ? startLocation.latitude
            : endLocation.latitude,
        startLocation.longitude < endLocation.longitude
            ? startLocation.longitude
            : endLocation.longitude,
      ),
    );

    return InkWell(
      // --- نفس دالة onTap القديمة ---
      onTap: () {
        String mapUrl =
            'https://www.google.com/maps/dir/${ride['start_location']}/${ride['end_location']}/';
        showInBrowser(mapUrl);
      },
      borderRadius: BorderRadius.circular(16),
      child: Container(
        decoration: BoxDecoration(
          color: AppColor.secondaryColor,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.15),
              blurRadius: 8,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // --- 1. قسم الخريطة ---
            ClipRRect(
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(16),
                topRight: Radius.circular(16),
              ),
              child: SizedBox(
                height: 150, // ارتفاع ثابت للخريطة
                child: AbsorbPointer(
                  // لمنع التفاعل المباشر مع الخريطة داخل القائمة
                  child: GoogleMap(
                    initialCameraPosition:
                        CameraPosition(target: startLocation, zoom: 12),
                    // --- نفس منطق الخريطة والخطوط ---
                    onMapCreated: (GoogleMapController controller) {
                      controller.animateCamera(
                          CameraUpdate.newLatLngBounds(bounds, 60));
                    },
                    polylines: {
                      Polyline(
                        polylineId: const PolylineId('route'),
                        points: [startLocation, endLocation],
                        color: AppColor.primaryColor,
                        width: 4,
                      ),
                    },
                    markers: {
                      Marker(
                          markerId: const MarkerId('start'),
                          position: startLocation),
                      Marker(
                          markerId: const MarkerId('end'),
                          position: endLocation),
                    },
                    mapToolbarEnabled: false,
                    zoomControlsEnabled: false,
                  ),
                ),
              ),
            ),
            // --- 2. قسم تفاصيل الرحلة ---
            Padding(
              padding: const EdgeInsets.all(12.0),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '${ride['date']} - ${ride['time']}',
                        style: AppStyle.subtitle.copyWith(
                            color: AppColor.writeColor.withOpacity(0.7)),
                      ),
                      // --- ويدجت جديدة لعرض حالة الرحلة ---
                      _buildStatusChip(ride['status']),
                    ],
                  ),
                  const Divider(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('Total Price'.tr,
                          style: AppStyle.title.copyWith(fontSize: 16)),
                      Text(
                        '${ride['price']} ${'SYP'.tr}',
                        style: AppStyle.headTitle.copyWith(
                            fontSize: 20, color: AppColor.primaryColor),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // --- ويدجت مساعدة لعرض حالة الرحلة بشكل أنيق ---
  Widget _buildStatusChip(String status) {
    Color chipColor;
    IconData chipIcon;

    // --- نفس منطق تحديد اللون ---
    if (status == 'Canceled'.tr) {
      chipColor = AppColor.redColor;
      chipIcon = Icons.cancel_outlined;
    } else if (status == 'Finished'.tr) {
      chipColor = AppColor.greenColor;
      chipIcon = Icons.check_circle_outline;
    } else {
      chipColor = AppColor.yellowColor;
      chipIcon = Icons.hourglass_empty_rounded;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: chipColor.withOpacity(0.15),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(chipIcon, color: chipColor, size: 16),
          const SizedBox(width: 6),
          Text(
            status,
            style: AppStyle.subtitle.copyWith(
                color: chipColor, fontWeight: FontWeight.bold, fontSize: 12),
          ),
        ],
      ),
    );
  }
}
