<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import type { Game, Leg } from '../types';
import { gameService, legService } from '../services/api';

const route = useRoute();
const router = useRouter();

const game = ref<Game | null>(null);
const legs = ref<Leg[]>([]);
const loading = ref(true);
const saving = ref(false);

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

const mapContainer = ref<HTMLDivElement | null>(null);
let map: L.Map | null = null;
let markers: L.Marker[] = [];

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

async function loadGame() {
  loading.value = true;
  try {
    const response = await gameService.get(gameId.value);
    game.value = response.data;
    legs.value = response.data.legs || [];
  } catch (err) {
    console.error('Failed to load game:', err);
  } finally {
    loading.value = false;
  }
}

function initMap() {
  if (!mapContainer.value) 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);
  }

  legs.value.forEach((leg, index) => {
    if (leg.locationLat && leg.locationLng) {
      const marker = L.marker([leg.locationLat, leg.locationLng])
        .addTo(map!)
        .bindPopup(`Leg ${index + 1}`);
      markers.push(marker);
    }
  });

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

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

  saving.value = true;
  try {
    const response = await legService.create(gameId.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
    });
    
    legs.value.push(response.data);
    
    newLeg.value = {
      description: '',
      conditionType: 'photo',
      conditionDetails: '',
      locationLat: null,
      locationLng: null,
      timeLimit: 30
    };
    
    if (map) {
      markers.forEach(m => m.remove());
      markers = [];
      legs.value.forEach((leg, index) => {
        if (leg.locationLat && leg.locationLng) {
          const marker = L.marker([leg.locationLat, leg.locationLng])
            .addTo(map!)
            .bindPopup(`Leg ${index + 1}`);
          markers.push(marker);
        }
      });
    }
  } catch (err) {
    alert('Failed to add leg');
  } finally {
    saving.value = false;
  }
}

async function deleteLeg(legId: string) {
  if (!confirm('Are you sure you want to delete this leg?')) return;
  
  try {
    await legService.delete(legId);
    legs.value = legs.value.filter(l => l.id !== legId);
  } catch (err) {
    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 getTotalDistance(): number {
  if (!game.value?.locationLat || !game.value?.locationLng || legs.value.length === 0) return 0;
  
  let total = 0;
  let prevLat = game.value.locationLat;
  let prevLng = game.value.locationLng;
  
  for (const leg of legs.value) {
    if (leg.locationLat && leg.locationLng) {
      total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng);
      prevLat = leg.locationLat;
      prevLng = leg.locationLng;
    }
  }
  
  return total;
}

onMounted(() => {
  loadGame().then(() => {
    setTimeout(initMap, 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>Legs ({{ legs.length }})</h2>
          <p><small>Total route distance: {{ getTotalDistance().toFixed(2) }} km</small></p>
          
          <article v-if="legs.length" v-for="(leg, index) in legs" :key="leg.id">
            <div class="leg-header">
              <h3>Leg {{ index + 1 }}</h3>
              <button @click="deleteLeg(leg.id)" class="secondary">Delete</button>
            </div>
            <p>{{ leg.description }}</p>
            <footer>
              <small>
                Type: {{ 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>
          </article>
          <p v-else>No legs added yet</p>
        </article>

        <article>
          <h2>Add New Leg</h2>
          
          <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>
      </div>
    </template>
  </main>
</template>

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

.leg-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.leg-header h3 {
  margin: 0;
}
</style>
