// lib/views/navigation_view.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:ui';

import 'navigation_controller.dart'; // For BackdropFilter

// استخدام نفس مسار الاستيراد الذي قدمته

class NavigationView extends StatelessWidget {
  const NavigationView({super.key});

  @override
  Widget build(BuildContext context) {
    final NavigationController controller = Get.put(NavigationController());

    return Scaffold(
      body: GetBuilder<NavigationController>(
        builder: (_) => Stack(
          children: [
            // --- الخريطة ---
            GoogleMap(
              onMapCreated: controller.onMapCreated,
              // --- السطر المضاف والمهم هنا ---
              onLongPress: controller.onMapLongPressed,
              initialCameraPosition: CameraPosition(
                target: controller.myLocation ??
                    const LatLng(33.5138, 36.2765), // Default to Damascus
                zoom: 16.0,
              ),
              markers: controller.markers,
              polylines: controller.polylines,
              myLocationEnabled: false,
              myLocationButtonEnabled: false,
              compassEnabled: false,
              zoomControlsEnabled: false,
              // تعديل الـ padding لإعطاء مساحة للعناصر العلوية والسفلية
              padding: EdgeInsets.only(
                  bottom: controller.currentInstruction.isNotEmpty ? 130 : 0,
                  top: 140),
            ),

            // --- واجهة البحث ونتائجه ---
            _buildSearchUI(controller),

            // --- إرشادات الملاحة المطورة ---
            if (controller.currentInstruction.isNotEmpty)
              _buildNavigationInstruction(controller),

            // --- أزرار التحكم على الخريطة ---
            _buildMapControls(controller),

            // --- مؤشر التحميل ---
            if (controller.isLoading)
              Container(
                color: Colors.black.withOpacity(0.5),
                child: const Center(
                    child: CircularProgressIndicator(color: Colors.white)),
              ),
          ],
        ),
      ),
    );
  }

  // --- ويدجت خاصة بواجهة البحث ---
  Widget _buildSearchUI(NavigationController controller) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(15.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.15),
                      blurRadius: 10,
                      offset: const Offset(0, 5),
                    ),
                  ],
                ),
                child: TextField(
                  controller: controller.placeDestinationController,
                  onChanged: (val) {
                    controller.onSearchChanged(val);
                  },
                  decoration: InputDecoration(
                    hintText: 'إلى أين تريد الذهاب؟',
                    prefixIcon: const Icon(Icons.search, color: Colors.grey),
                    suffixIcon: controller
                            .placeDestinationController.text.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              controller.placeDestinationController.clear();
                              controller.placesDestination = [];
                              controller.update();
                            },
                          )
                        : (controller.polylines.isNotEmpty
                            ? IconButton(
                                icon:
                                    const Icon(Icons.close, color: Colors.red),
                                tooltip: 'إلغاء المسار',
                                onPressed: () => controller.clearRoute(),
                              )
                            : null),
                    border: InputBorder.none,
                    contentPadding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 15),
                  ),
                ),
              ),
              const SizedBox(height: 8),
              if (controller.placesDestination.isNotEmpty)
                ClipRRect(
                  borderRadius: BorderRadius.circular(15.0),
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
                    child: Container(
                      constraints: const BoxConstraints(maxHeight: 220),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.85),
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                      child: ListView.builder(
                        padding: EdgeInsets.zero,
                        shrinkWrap: true,
                        itemCount: controller.placesDestination.length,
                        itemBuilder: (context, index) {
                          final place = controller.placesDestination[index];
                          return ListTile(
                            title: Text(place['name'] ?? 'اسم غير معروف',
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold)),
                            subtitle: Text(place['address'] ?? '',
                                maxLines: 1, overflow: TextOverflow.ellipsis),
                            leading: const Icon(Icons.location_on_outlined,
                                color: Colors.blue),
                            onTap: () => controller.selectDestination(place),
                          );
                        },
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  // --- ويدجت خاصة بأزرار التحكم ---
  Widget _buildMapControls(NavigationController controller) {
    return Positioned(
      bottom: controller.currentInstruction.isNotEmpty ? 150 : 20,
      right: 12,
      child: Column(
        children: [
          if (controller.polylines.isNotEmpty) ...[
            FloatingActionButton(
              heroTag: 'rerouteBtn',
              mini: true,
              backgroundColor: Colors.white,
              tooltip: 'إعادة حساب المسار',
              onPressed: () => controller.recalculateRoute(),
              child: const Icon(Icons.sync_alt, color: Colors.blue),
            ),
            const SizedBox(height: 10),
          ],
          FloatingActionButton(
            heroTag: 'gpsBtn',
            mini: true,
            backgroundColor: Colors.white,
            onPressed: () {
              if (controller.myLocation != null) {
                controller.animateCameraToPosition(
                  controller.myLocation!,
                  bearing: controller.heading,
                  zoom: 18.5,
                );
              }
            },
            child: const Icon(Icons.gps_fixed, color: Colors.black54),
          ),
        ],
      ),
    );
  }

  // --- ويدجت خاصة بإرشادات الطريق المطورة ---
  Widget _buildNavigationInstruction(NavigationController controller) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.blue.shade900, Colors.blue.shade600],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 15,
              offset: const Offset(0, -5),
            ),
          ],
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(16, 16, 16, 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // --- الصف العلوي: السرعة والمسافة ---
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    controller.distanceToNextStep,
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 28,
                        fontWeight: FontWeight.bold),
                  ),
                  Row(
                    children: [
                      Text(
                        controller.currentSpeed.toStringAsFixed(0),
                        style: const TextStyle(
                            color: Colors.white,
                            fontSize: 28,
                            fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(width: 4),
                      const Text(
                        "كم/س",
                        style: TextStyle(color: Colors.white70, fontSize: 14),
                      ),
                    ],
                  ),
                ],
              ),
              const Divider(color: Colors.white38, height: 20, thickness: 0.8),
              // --- الصف السفلي: الإرشاد القادم ---
              Row(
                children: [
                  const Icon(Icons.navigation_rounded,
                      color: Colors.white, size: 32),
                  const SizedBox(width: 15),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text("الخطوة التالية",
                            style:
                                TextStyle(color: Colors.white70, fontSize: 12)),
                        Text(
                          controller.nextInstruction.isNotEmpty
                              ? controller.nextInstruction
                              : controller.currentInstruction,
                          style: const TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.bold),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
