<template>
  <div class="min-h-screen bg-gray-50">
    <Navbar />

    <div class="max-w-7xl mx-auto px-4 py-8">
      <div class="mb-6">
        <h2 class="text-3xl font-bold text-gray-800">Checkout</h2>
        <p class="text-gray-600">Complete your order</p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- Left Side - Forms -->
        <div class="lg:col-span-2 space-y-6">
          <!-- Delivery Address -->
          <div class="bg-white rounded-xl shadow-sm p-6">
            <div class="flex items-center gap-3 mb-6">
              <div class="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
              </div>
              <h3 class="text-xl font-bold text-gray-800">Delivery Address</h3>
            </div>

            <div class="space-y-4">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Full Name</label>
                  <input v-model="address.name" type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="John Doe">
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
                  <input v-model="address.phone" type="tel" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="077 123 4567">
                </div>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Address</label>
                <input v-model="address.line1" type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="Enter your full address">
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">City</label>
                <input v-model="address.city" type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="Colombo">
              </div>

              <!-- Map Picker -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Pin Your Location on Map</label>
                <div class="relative h-64 bg-gray-200 rounded-lg overflow-hidden border-2 border-gray-300">
                  <div id="map" class="w-full h-full"></div>
                  <button @click.stop="useCurrentLocation" class="absolute top-3 right-3 bg-white p-2 rounded-lg shadow-lg hover:bg-gray-50 transition z-10">
                    <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                    </svg>
                  </button>
                </div>
                <p class="text-xs text-gray-500 mt-2">📍 Click on the map to pin your exact delivery location</p>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Instructions (Optional)</label>
                <textarea v-model="address.instructions" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="Any special instructions for delivery..."></textarea>
              </div>
            </div>
          </div>

          <!-- Payment Method -->
          <div class="bg-white rounded-xl shadow-sm p-6">
            <div class="flex items-center gap-3 mb-6">
              <div class="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/>
                </svg>
              </div>
              <h3 class="text-xl font-bold text-gray-800">Payment Method</h3>
            </div>

            <div class="space-y-3">
              <label class="flex items-center gap-4 p-4 border-2 rounded-lg cursor-pointer hover:bg-gray-50 transition" :class="paymentMethod === 'cash' ? 'border-orange-500 bg-orange-50' : 'border-gray-200'">
                <input v-model="paymentMethod" type="radio" value="cash" class="w-5 h-5 text-orange-600">
                <div class="flex-1">
                  <p class="font-semibold text-gray-800">Cash on Delivery</p>
                  <p class="text-sm text-gray-600">Pay when you receive your order</p>
                </div>
                <span class="text-2xl">💵</span>
              </label>

              <label class="flex items-center gap-4 p-4 border-2 rounded-lg cursor-not-allowed opacity-50" :class="'border-gray-200 bg-gray-50'">
                <input type="radio" value="card" class="w-5 h-5 text-orange-600" disabled>
                <div class="flex-1">
                  <p class="font-semibold text-gray-800">Credit/Debit Card</p>
                  <p class="text-sm text-gray-600">Coming soon</p>
                </div>
                <span class="text-2xl">💳</span>
              </label>

              <label class="flex items-center gap-4 p-4 border-2 rounded-lg cursor-not-allowed opacity-50" :class="'border-gray-200 bg-gray-50'">
                <input type="radio" value="wallet" class="w-5 h-5 text-orange-600" disabled>
                <div class="flex-1">
                  <p class="font-semibold text-gray-800">Digital Wallet</p>
                  <p class="text-sm text-gray-600">Coming soon</p>
                </div>
                <span class="text-2xl">👛</span>
              </label>
            </div>
          </div>

          <!-- Order Notes -->
          <div class="bg-white rounded-xl shadow-sm p-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">Order Notes (Optional)</h3>
            <textarea v-model="orderNotes" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="Any special requests for the restaurant..."></textarea>
          </div>
        </div>

        <!-- Right Side - Order Summary -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-xl shadow-sm p-6 sticky top-24">
            <h3 class="text-xl font-bold text-gray-800 mb-6">Order Summary</h3>

            <!-- Cart Items -->
            <div class="space-y-3 mb-6 max-h-64 overflow-y-auto">
              <div v-for="item in cartItems" :key="item.id" class="flex gap-3 pb-3 border-b border-gray-100">
                <div class="w-16 h-16 bg-gray-200 rounded-lg flex items-center justify-center flex-shrink-0">
                  <span class="text-2xl">🍕</span>
                </div>
                <div class="flex-1">
                  <p class="font-semibold text-gray-800 text-sm">{{ item.product_name }}</p>
                  <p class="text-xs text-gray-600">Qty: {{ item.quantity }}</p>
                  <p class="text-sm font-bold text-orange-600">Rs {{ item.price * item.quantity }}</p>
                </div>
              </div>
            </div>

            <!-- Price Breakdown -->
            <div class="space-y-3 mb-6 pb-6 border-b border-gray-200">
              <div class="flex justify-between text-gray-700">
                <span>Subtotal</span>
                <span>Rs {{ subtotal }}</span>
              </div>
              <div class="flex justify-between text-gray-700">
                <span>Delivery Fee {{ calculatingFee ? '(Calculating...)' : '' }}</span>
                <span>Rs {{ deliveryFee }}</span>
              </div>
              <div class="flex justify-between font-bold text-lg pt-3 border-t border-gray-200">
                <span>Total</span>
                <span class="text-orange-600">Rs {{ total }}</span>
              </div>
            </div>

            <!-- Place Order Button -->
            <button @click="placeOrder" :disabled="placing" class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-4 rounded-lg font-bold text-lg hover:from-orange-600 hover:to-orange-700 transition shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed">
              {{ placing ? 'Placing Order...' : 'Place Order' }}
            </button>

            <p class="text-xs text-gray-500 text-center mt-4">
              By placing this order, you agree to our Terms & Conditions
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import { useCartStore } from '../stores/cart';
import api from '../services/api';
import Navbar from '../components/Navbar.vue';

const router = useRouter();
const authStore = useAuthStore();
const cartStore = useCartStore();

const cartItems = ref([]);
const placing = ref(false);
const restaurant = ref(null);
const deliveryFee = ref(0);
const calculatingFee = ref(false);
let map = null;
let marker = null;
let circle = null;
let directionsRenderer = null;

const address = ref({
  name: '',
  phone: '',
  line1: '',
  city: '',
  instructions: '',
  restaurant_id: null,
  latitude: null,
  longitude: null
});

const paymentMethod = ref('cash');
const orderNotes = ref('');

const loadUserData = async () => {
  await authStore.checkAuth();
  if (authStore.user) {
    address.value.name = authStore.user.name || '';
    address.value.phone = authStore.user.phone || '';
  }
};

const subtotal = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0);
});

const total = computed(() => subtotal.value + deliveryFee.value);

const calculateDeliveryFee = async () => {
  if (!restaurant.value || !address.value.latitude || !address.value.longitude) {
    deliveryFee.value = restaurant.value ? parseFloat(restaurant.value.delivery_fee) : 0;
    return;
  }
  
  calculatingFee.value = true;
  
  try {
    if (!window.google || !window.google.maps) {
      await loadGoogleMaps();
    }
    
    const directionsService = new window.google.maps.DirectionsService();
    
    if (directionsRenderer) {
      directionsRenderer.setMap(null);
    }
    
    directionsRenderer = new window.google.maps.DirectionsRenderer({
      map: map,
      suppressMarkers: true,
      polylineOptions: {
        strokeColor: '#FF6B35',
        strokeWeight: 5,
        strokeOpacity: 1
      }
    });
    
    // Request multiple route alternatives
    directionsService.route({
      origin: {
        lat: restaurant.value.latitude + 0.00012,
        lng: restaurant.value.longitude + 0.00012
      },
      destination: {
        lat: address.value.latitude + 0.00012,
        lng: address.value.longitude + 0.00012
      },
      travelMode: window.google.maps.TravelMode.WALKING,
      drivingOptions: {
        departureTime: new Date(),
        trafficModel: 'optimistic'
      },
      provideRouteAlternatives: true,
      avoidHighways: true,
      avoidTolls: true
    }, (result, status) => {
      if (status === 'OK') {
        // Select optimal route using weighted scoring
        let bestRoute = result.routes[0];
        let bestScore = Infinity;
        
        result.routes.forEach(route => {
          const leg = route.legs[0];
          const durationSeconds = leg.duration.value;
          const distanceMeters = leg.distance.value;
          
          // Weighted score: 70% duration, 30% distance
          const score = (durationSeconds * 0.7) + (distanceMeters * 0.3);
          
          if (score < bestScore) {
            bestScore = score;
            bestRoute = route;
          }
        });
        
        // Display only the best route
        directionsRenderer.setDirections({ ...result, routes: [bestRoute] });
        
        const distanceInKm = bestRoute.legs[0].distance.value / 1000;
        const baseFee = parseFloat(restaurant.value.delivery_fee);
        
        if (distanceInKm <= 1) {
          deliveryFee.value = baseFee;
        } else {
          deliveryFee.value = Math.ceil(distanceInKm * baseFee);
        }
      } else {
        deliveryFee.value = parseFloat(restaurant.value.delivery_fee);
      }
      calculatingFee.value = false;
    });
  } catch (error) {
    console.error('Error calculating delivery fee:', error);
    deliveryFee.value = restaurant.value ? parseFloat(restaurant.value.delivery_fee) : 0;
    calculatingFee.value = false;
  }
};

const loadGoogleMaps = () => {
  return new Promise((resolve) => {
    if (window.google && window.google.maps) {
      resolve();
      return;
    }
    const script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBrfy7IL9up-52b6vB0DyQdMTZYAJPDOuw&libraries=places';
    script.async = true;
    script.onload = resolve;
    document.head.appendChild(script);
  });
};

const loadCart = async () => {
  try {
    const response = await api.get('/cart');
    cartItems.value = response.data.data || [];
    
    if (cartItems.value.length > 0) {
      address.value.restaurant_id = cartItems.value[0].restaurant_id;
      await loadRestaurant(cartItems.value[0].restaurant_id);
    }
  } catch (error) {
    console.error('Error loading cart:', error);
  }
};

const loadRestaurant = async (restaurantId) => {
  try {
    const response = await api.get(`/restaurants/${restaurantId}`);
    const data = response.data.data;
    restaurant.value = {
      ...data,
      latitude: parseFloat(data.latitude),
      longitude: parseFloat(data.longitude),
      delivery_radius: parseFloat(data.delivery_radius)
    };
    
    if (window.google && window.google.maps && !map) {
      setTimeout(() => initMap(), 100);
    }
  } catch (error) {
    console.error('Error loading restaurant:', error);
  }
};

const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371;
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  return R * c;
};

const isWithinRadius = (lat, lng) => {
  if (!restaurant.value) return true;
  const distance = calculateDistance(
    restaurant.value.latitude,
    restaurant.value.longitude,
    lat,
    lng
  );
  return distance <= restaurant.value.delivery_radius;
};

const useCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const lat = position.coords.latitude;
        const lng = position.coords.longitude;
        
        if (!isWithinRadius(lat, lng)) {
          showToast('Your location is outside the delivery area', 'error');
          return;
        }
        
        address.value.latitude = lat;
        address.value.longitude = lng;
        calculateDeliveryFee();
        
        if (map && window.google) {
          map.setCenter({ lat, lng });
          if (marker) {
            marker.setPosition({ lat, lng });
          } else {
            marker = new window.google.maps.Marker({
              position: { lat, lng },
              map: map,
              draggable: true,

                icon: {
                   url: 'https://maps.google.com/mapfiles/ms/icons/green-dot.png',
  scaledSize: new window.google.maps.Size(40, 40)
   
  }

            });
            marker.addListener('dragend', (e) => {
              const newLat = e.latLng.lat();
              const newLng = e.latLng.lng();
              if (!isWithinRadius(newLat, newLng)) {
                showToast('Location outside delivery area', 'error');
                marker.setPosition({ lat: address.value.latitude, lng: address.value.longitude });
                return;
              }
              address.value.latitude = newLat;
              address.value.longitude = newLng;
              calculateDeliveryFee();
            });
          }
        }
        
        showToast('Location detected successfully!', 'success');
      },
      (error) => {
        showToast('Unable to get location', 'error');
      }
    );
  } else {
    showToast('Geolocation not supported', 'error');
  }
};

const showToast = (message, type = 'success') => {
  const toast = document.createElement('div');
  toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg text-white z-50 ${type === 'success' ? 'bg-green-500' : 'bg-red-500'}`;
  toast.textContent = message;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 3000);
};

const initMap = () => {
  if (!window.google || !window.google.maps) {
    console.error('Google Maps not loaded');
    return;
  }
  
  const center = restaurant.value 
    ? { lat: restaurant.value.latitude, lng: restaurant.value.longitude }
    : { lat: 6.9271, lng: 79.8612 };
  
  const mapElement = document.getElementById('map');
  if (!mapElement) {
    console.error('Map element not found');
    return;
  }
  
  map = new window.google.maps.Map(mapElement, {
    center: center,
    zoom: 13,
    mapTypeControl: false,
    streetViewControl: false,
    fullscreenControl: false,
    clickableIcons: false
  });
  
  if (restaurant.value) {
    new window.google.maps.Marker({
      position: center,
      map: map,
      icon: {
        path: window.google.maps.SymbolPath.CIRCLE,
        scale: 10,
        fillColor: '#ea580c',
        fillOpacity: 1,
        strokeColor: '#fff',
        strokeWeight: 2
      },
      title: restaurant.value.name
    });
    
    circle = new window.google.maps.Circle({
      map: map,
      center: center,
      radius: restaurant.value.delivery_radius * 1000,
      fillColor: '#fb923c',
      fillOpacity: 0.15,
      strokeColor: '#ea580c',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      clickable: false
    });
  }
  
  setTimeout(() => {
    window.google.maps.event.addListener(map, 'click', (e) => {
      const lat = e.latLng.lat();
      const lng = e.latLng.lng();
      
      if (!isWithinRadius(lat, lng)) {
        showToast('Location outside delivery area', 'error');
        return;
      }
      
      address.value.latitude = lat;
      address.value.longitude = lng;
      calculateDeliveryFee();
      
      if (marker) {
        marker.setPosition({ lat, lng });
      } else {
        marker = new window.google.maps.Marker({
          position: { lat, lng },
          map: map,
          draggable: true,
         // animation: window.google.maps.Animation.DROP
        });
        
        window.google.maps.event.addListener(marker, 'dragend', (e) => {
          const newLat = e.latLng.lat();
          const newLng = e.latLng.lng();
          if (!isWithinRadius(newLat, newLng)) {
            showToast('Location outside delivery area', 'error');
            marker.setPosition({ lat: address.value.latitude, lng: address.value.longitude });
            return;
          }
          address.value.latitude = newLat;
          address.value.longitude = newLng;
          calculateDeliveryFee();
        });
      }
    });
  }, 500);
};

const placeOrder = async () => {
  if (!address.value.name || !address.value.phone || !address.value.line1) {
    alert('Please fill in all required address fields');
    return;
  }

  if (!paymentMethod.value) {
    alert('Please select a payment method');
    return;
  }

  if (!address.value.restaurant_id) {
    alert('Cart is empty or invalid');
    return;
  }
  
  if (!address.value.latitude || !address.value.longitude) {
    alert('Please select your location on the map');
    return;
  }

  placing.value = true;

  try {
    const fullAddress = `${address.value.line1}, ${address.value.city}`;
    
    const response = await api.post('/orders', {
      restaurant_id: address.value.restaurant_id,
      delivery_address: fullAddress,
      delivery_latitude: address.value.latitude,
      delivery_longitude: address.value.longitude,
      delivery_phone: address.value.phone,
      delivery_instructions: address.value.instructions,
      payment_method: paymentMethod.value,
      customer_notes: orderNotes.value,
      delivery_method: 'walk',
      delivery_fee: deliveryFee.value
    });

    cartStore.clearCount();
    alert('Order placed successfully!');
    router.push(`/orders/${response.data.id}`);
  } catch (error) {
    console.error('Error placing order:', error);
    const errors = error.response?.data?.errors;
    if (errors) {
      const errorMessages = Object.values(errors).flat().join('\n');
      alert(errorMessages);
    } else {
      alert(error.response?.data?.message || 'Failed to place order');
    }
  } finally {
    placing.value = false;
  }
};

onMounted(async () => {
  await loadUserData();
  await loadGoogleMaps();
  await loadCart();
});
</script>
