<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import type { Game, Route } from '../types';
import { gameService, routeService } from '../services/api';
import { alert, confirm } from '../composables/useModal';
import { useAuthStore } from '../stores/auth';
import { formatDistance } from '../utils/units';

const route = useRoute();
const authStore = useAuthStore();

const game = ref<Game | null>(null);
const routes = ref<Route[]>([]);
const selectedRouteId = ref<string | null>(null);
const loading = ref(true);
const saving = ref(false);

const gameId = computed(() => route.params.id as string);

const selectedRoute = computed(() => 
  routes.value.find(r => r.id === selectedRouteId.value) || null
);

const unitPreference = computed(() => authStore.user?.unitPreference || 'METRIC');

const mapContainer = ref<HTMLDivElement | null>(null);
let map: L.Map | null = null;
let routeMarkers: { [routeId: string]: L.Marker[] } = {};
let mapInitialized = false;

const newRoute = ref({
  name: '',
  description: '',
  color: '#3498db'
});

const editRoute = ref({
  name: '',
  description: '',
  color: ''
});

const newLeg = ref({
  description: '',
  conditionType: 'photo',
  conditionDetails: '',
  locationLat: null as number | null,
  locationLng: null as number | null,
  timeLimit: 30
});

function startEditRoute() {
  if (selectedRoute.value) {
    editRoute.value = {
      name: selectedRoute.value.name,
      description: selectedRoute.value.description || '',
      color: selectedRoute.value.color
    };
  }
}

async function saveRoute() {
  if (!selectedRouteId.value) return;
  
  saving.value = true;
  try {
    const response = await routeService.update(selectedRouteId.value, {
      name: editRoute.value.name,
      description: editRoute.value.description || undefined,
      color: editRoute.value.color
    });
    
    const idx = routes.value.findIndex(r => r.id === selectedRouteId.value);
    if (idx >= 0) {
      routes.value[idx].name = response.data.name;
      routes.value[idx].description = response.data.description;
      routes.value[idx].color = response.data.color;
    }
    
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to update route');
  } finally {
    saving.value = false;
  }
}

async function loadGame() {
  loading.value = true;
  try {
    const response = await gameService.get(gameId.value);
    game.value = response.data;
    routes.value = response.data.routes || [];
    
    if (routes.value.length > 0 && !selectedRouteId.value) {
      selectedRouteId.value = routes.value[0].id;
    }
  } catch (err) {
    console.error('Failed to load game:', err);
  } finally {
    loading.value = false;
  }
}

function initMap() {
  if (!mapContainer.value || map) return;
  
  const center = game.value?.locationLat && game.value?.locationLng
    ? [game.value.locationLat, game.value.locationLng] as [number, number]
    : [51.505, -0.09] as [number, number];
    
  map = L.map(mapContainer.value).setView(center, 13);
  
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; OpenStreetMap'
  }).addTo(map);

  if (game.value?.locationLat && game.value?.locationLng) {
    L.circle([game.value.locationLat, game.value.locationLng], {
      radius: game.value.searchRadius || 500,
      color: '#667eea',
      fillColor: '#667eea',
      fillOpacity: 0.1
    }).addTo(map);
  }

  map.on('click', (e: L.LeafletMouseEvent) => {
    newLeg.value.locationLat = e.latlng.lat;
    newLeg.value.locationLng = e.latlng.lng;
  });

  updateMapMarkers();
}

function updateMapMarkers() {
  if (!map) return;
  
  Object.values(routeMarkers).forEach(markers => {
    markers.forEach(m => m.remove());
  });
  routeMarkers = {};

  routes.value.forEach((route) => {
    const color = route.color || '#3498db';
    routeMarkers[route.id] = [];
    
    route.routeLegs?.forEach((leg, legIndex) => {
      if (leg.locationLat && leg.locationLng) {
        const marker = L.marker([leg.locationLat, leg.locationLng], {
          icon: L.divIcon({
            className: `route-marker-${route.id}`,
            html: `<div style="background: ${color}; width: 20px; height: 20px; border-radius: 50%; border: 2px solid white; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">${legIndex + 1}</div>`,
            iconSize: [20, 20]
          })
        })
          .addTo(map!)
          .bindPopup(`${route.name} - Leg ${legIndex + 1}`);
        routeMarkers[route.id].push(marker);
      }
    });
  });

  setTimeout(() => map?.invalidateSize(), 100);
}

async function createRoute() {
  if (!newRoute.value.name.trim()) {
    await alert('Please enter a route name');
    return;
  }

  saving.value = true;
  try {
    const response = await routeService.create({
      gameId: gameId.value,
      name: newRoute.value.name,
      description: newRoute.value.description || undefined,
      color: newRoute.value.color
    });
    
    routes.value.push(response.data);
    selectedRouteId.value = response.data.id;
    
    newRoute.value = { name: '', description: '', color: '#3498db' };
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to create route');
  } finally {
    saving.value = false;
  }
}

async function copyRoute(routeId: string) {
  try {
    const response = await routeService.copy(routeId);
    routes.value.push(response.data);
    selectedRouteId.value = response.data.id;
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to copy route');
  }
}

async function deleteRoute(routeId: string) {
  if (!await confirm('Are you sure you want to delete this route and all its legs?')) return;
  
  try {
    await routeService.delete(routeId);
    routes.value = routes.value.filter(r => r.id !== routeId);
    
    if (selectedRouteId.value === routeId) {
      selectedRouteId.value = routes.value[0]?.id || null;
    }
    
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to delete route');
  }
}

async function addLeg() {
  if (!selectedRouteId.value || !newLeg.value.description) {
    await alert('Please enter a description');
    return;
  }

  saving.value = true;
  try {
    const response = await routeService.addLeg(selectedRouteId.value, {
      description: newLeg.value.description,
      conditionType: newLeg.value.conditionType,
      conditionDetails: newLeg.value.conditionDetails || undefined,
      locationLat: newLeg.value.locationLat || undefined,
      locationLng: newLeg.value.locationLng || undefined,
      timeLimit: newLeg.value.timeLimit
    });
    
    const route = routes.value.find(r => r.id === selectedRouteId.value);
    if (route) {
      if (!route.routeLegs) route.routeLegs = [];
      route.routeLegs.push(response.data);
    }
    
    newLeg.value = {
      description: '',
      conditionType: 'photo',
      conditionDetails: '',
      locationLat: null,
      locationLng: null,
      timeLimit: 30
    };
    
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to add leg');
  } finally {
    saving.value = false;
  }
}

async function deleteLeg(legId: string) {
  if (!await confirm('Are you sure you want to delete this leg?')) return;
  
  try {
    await routeService.deleteLeg(selectedRouteId.value!, legId);
    
    const route = routes.value.find(r => r.id === selectedRouteId.value);
    if (route && route.routeLegs) {
      route.routeLegs = route.routeLegs.filter(l => l.id !== legId);
    }
    
    updateMapMarkers();
  } catch (err) {
    await alert('Failed to delete leg');
  }
}

function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  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;
}

function getRouteDistance(route: Route): number {
  if (!game.value?.locationLat || !game.value?.locationLng || !route.routeLegs?.length) return 0;
  
  let total = 0;
  let prevLat = game.value.locationLat;
  let prevLng = game.value.locationLng;
  
  for (const leg of route.routeLegs) {
    if (leg.locationLat && leg.locationLng) {
      total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng);
      prevLat = leg.locationLat;
      prevLng = leg.locationLng;
    }
  }
  
  return total;
}

function getTotalLegs(): number {
  return routes.value.reduce((sum, r) => sum + (r.routeLegs?.length || 0), 0);
}

watch(selectedRouteId, async (newId) => {
  if (newId) {
    startEditRoute();
    if (!mapInitialized) {
      await nextTick();
      if (mapContainer.value) {
        initMap();
        mapInitialized = true;
      }
    } else {
      updateMapMarkers();
    }
  }
});

onMounted(() => {
  loadGame().then(() => {
    if (selectedRouteId.value) {
      setTimeout(() => {
        if (mapContainer.value && !mapInitialized) {
          initMap();
          mapInitialized = true;
        }
      }, 100);
    }
  });
});

onUnmounted(() => {
  if (map) map.remove();
});
</script>

<template>
  <main class="container">
    <article v-if="loading">Loading...</article>
    
    <template v-else-if="game">
      <nav aria-label="breadcrumb">
        <ul>
          <li><RouterLink :to="`/games/${game.id}`">&larr; Back to Game</RouterLink></li>
        </ul>
      </nav>

      <h1>Edit: {{ game.name }}</h1>

      <div class="grid">
        <article>
          <h2>Routes ({{ routes.length }})</h2>
          <p><small>Total legs: {{ getTotalLegs() }}</small></p>
          
          <div v-for="routeItem in routes" :key="routeItem.id" 
               class="route-card"
               :class="{ selected: selectedRouteId === routeItem.id }"
               @click="selectedRouteId = routeItem.id">
            <div class="route-header">
              <svg width="16" height="18" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
                <path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="routeItem.color" stroke="white" stroke-width="1"/>
              </svg>
              <h3>{{ routeItem.name }}</h3>
              <div class="route-actions">
                <button @click.stop="copyRoute(routeItem.id)" class="secondary outline">Copy</button>
                <button @click.stop="deleteRoute(routeItem.id)" class="contrast outline">Delete</button>
              </div>
            </div>
            <p v-if="routeItem.description">{{ routeItem.description }}</p>
            <footer>
              <small>
                {{ routeItem.routeLegs?.length || 0 }} legs
                · {{ formatDistance(getRouteDistance(routeItem), unitPreference) }}
              </small>
            </footer>
          </div>

          <details class="add-route" open>
            <summary>Add New Route</summary>
            <form @submit.prevent="createRoute">
              <label>
                Route Name
                <input v-model="newRoute.name" type="text" placeholder="e.g., Route A" required />
              </label>
              <label>
                Description (optional)
                <input v-model="newRoute.description" type="text" placeholder="e.g., Via downtown" />
              </label>
              <label class="color-label">
                Color
                <div style="display: flex; align-items: center; gap: 0.5rem;">
                  <input v-model="newRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
                  <span :style="{ color: newRoute.color, fontWeight: 'bold' }">{{ newRoute.color }}</span>
                </div>
              </label>
              <button type="submit" :disabled="saving">
                {{ saving ? 'Creating...' : 'Create Route' }}
              </button>
            </form>
          </details>
        </article>

        <article v-if="selectedRoute">
          <div class="route-header">
            <svg width="20" height="22" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
              <path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="selectedRoute.color" stroke="white" stroke-width="1"/>
            </svg>
            <h2>{{ selectedRoute.name }}</h2>
            <select v-model="selectedRouteId" style="max-width: 200px;">
              <option v-for="r in routes" :key="r.id" :value="r.id">
                {{ r.name }}
              </option>
            </select>
          </div>
          
          <details>
            <summary>Edit Route</summary>
            <form @submit.prevent="saveRoute">
              <label>
                Route Name
                <input v-model="editRoute.name" type="text" required />
              </label>
              <label>
                Description
                <input v-model="editRoute.description" type="text" />
              </label>
              <label class="color-label">
                Color
                <div style="display: flex; align-items: center; gap: 0.5rem;">
                  <input v-model="editRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
                  <span :style="{ color: editRoute.color, fontWeight: 'bold' }">{{ editRoute.color }}</span>
                </div>
              </label>
              <button type="submit" :disabled="saving">
                {{ saving ? 'Saving...' : 'Save Changes' }}
              </button>
            </form>
          </details>
          
          <div v-if="selectedRoute.routeLegs?.length" v-for="(leg, index) in selectedRoute.routeLegs" :key="leg.id" class="leg-card">
            <div class="leg-header">
              <h3>Leg {{ index + 1 }}</h3>
              <button @click="deleteLeg(leg.id)" class="secondary outline">Delete</button>
            </div>
            <p>{{ leg.description }}</p>
            <footer>
              <small>
                {{ leg.conditionType }}
                <span v-if="leg.timeLimit"> · {{ leg.timeLimit }} min</span>
                <span v-if="leg.locationLat && leg.locationLng">
                  · {{ leg.locationLat.toFixed(4) }}, {{ leg.locationLng.toFixed(4) }}
                </span>
              </small>
            </footer>
          </div>
          <p v-else>No legs in this route yet.</p>

          <h3>Add Leg</h3>
          <div ref="mapContainer" class="map-container"></div>
          <p><small>Click on map to set location</small></p>
          
          <form @submit.prevent="addLeg">
            <label>Description / Clue</label>
            <textarea v-model="newLeg.description" rows="2" required></textarea>
            
            <div class="grid">
              <label>
                Condition Type
                <select v-model="newLeg.conditionType">
                  <option value="photo">Photo Proof</option>
                  <option value="purchase">Purchase</option>
                  <option value="text">Text Answer</option>
                </select>
              </label>
              
              <label>
                Time Limit (minutes)
                <input v-model.number="newLeg.timeLimit" type="number" min="1" />
              </label>
            </div>
            
            <div class="grid">
              <label>
                Latitude
                <input v-model.number="newLeg.locationLat" type="number" step="any" readonly />
              </label>
              <label>
                Longitude
                <input v-model.number="newLeg.locationLng" type="number" step="any" readonly />
              </label>
            </div>
            
            <button type="submit" :disabled="saving">
              {{ saving ? 'Adding...' : 'Add Leg' }}
            </button>
          </form>
        </article>

        <article v-else>
          <p>Select a route or create a new one to start adding legs.</p>
        </article>
      </div>
    </template>
  </main>
</template>

<style scoped>
.map-container {
  height: 250px;
  border-radius: var(--pico-border-radius);
  margin-bottom: 0.5rem;
}

.route-card, .leg-card {
  margin-bottom: 1rem;
  cursor: pointer;
}

.route-card.selected {
  border-color: var(--pico-primary-focus);
}

.route-header, .leg-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.route-header h3, .leg-header h3 {
  margin: 0;
}

.route-actions {
  display: flex;
  gap: 0.5rem;
}

.add-route {
  margin-top: 1rem;
}

.add-route summary {
  cursor: pointer;
  padding: 0.5rem;
  background: var(--pico-muted-border-color);
  border-radius: var(--pico-border-radius);
}

.add-route form {
  padding-top: 1rem;
}

input[type="color"] {
  width: 100%;
  height: 40px;
  padding: 2px;
  border-radius: var(--pico-border-radius);
  cursor: pointer;
}

.color-label {
  display: flex;
  flex-direction: column;
}
</style>
