<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>
  <div class="edit-game">
    <div v-if="loading" class="loading">Loading...</div>
    
    <template v-else-if="game">
      <header class="page-header">
        <div>
          <RouterLink :to="`/games/${game.id}`" class="back-link">&larr; Back to Game</RouterLink>
          <h1>Edit: {{ game.name }}</h1>
        </div>
      </header>

      <div class="edit-content">
        <section class="legs-section">
          <h2>Legs ({{ legs.length }})</h2>
          <p class="hint">Total route distance: {{ getTotalDistance().toFixed(2) }} km</p>
          
          <div v-if="legs.length" class="legs-list">
            <div v-for="(leg, index) in legs" :key="leg.id" class="leg-item">
              <div class="leg-number">{{ index + 1 }}</div>
              <div class="leg-info">
                <p>{{ leg.description }}</p>
                <div class="leg-meta">
                  <span>Type: {{ leg.conditionType }}</span>
                  <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>
                </div>
              </div>
              <button @click="deleteLeg(leg.id)" class="btn btn-danger">Delete</button>
            </div>
          </div>
          <div v-else class="empty">No legs added yet</div>
        </section>

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

<style scoped>
.edit-game {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem;
}

.back-link {
  color: #667eea;
  text-decoration: none;
  font-size: 0.875rem;
}

.page-header {
  margin-bottom: 2rem;
}

.edit-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.legs-section, .add-leg-section {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.legs-section h2, .add-leg-section h2 {
  margin-bottom: 1rem;
}

.hint {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 1rem;
}

.legs-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.leg-item {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  background: #f9f9f9;
  border-radius: 6px;
}

.leg-number {
  width: 32px;
  height: 32px;
  background: #667eea;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.leg-info {
  flex: 1;
}

.leg-info p {
  margin: 0 0 0.5rem;
}

.leg-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.75rem;
  color: #666;
}

.map-container {
  height: 250px;
  border-radius: 8px;
  margin-bottom: 0.5rem;
}

.leg-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.form-group label {
  font-size: 0.875rem;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  border: none;
  font-size: 0.875rem;
}

.btn-primary { background: #667eea; color: white; }
.btn-danger { background: #dc3545; color: white; }

.empty {
  text-align: center;
  padding: 2rem;
  color: #666;
}
</style>
