<script setup lang="ts">
import { ref, watch } from 'vue'
import type { BusStop } from '@/types'
import { busStopsService } from '@/services/busStopsService'
import { favoritesService } from '@/services/favoritesService'
import { formatTo12Hour } from '@/utils/timeFormatter'

interface Props {
  busStop: BusStop | null
  isOpen: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(['close', 'navigate'])

const upcomingArrivals = ref<{ routeName: string; arrivalTime: string }[]>([])
const isLoading = ref(false)
const isFavorited = ref(false)
const favoriteId = ref<string | null>(null)

// Function to fetch arrivals
async function loadArrivals() {
  if (props.busStop) {
    isLoading.value = true
    try {
      upcomingArrivals.value = await busStopsService.getNextBusArrivals(props.busStop.id)
    } catch (e) {
      console.error('Failed to load arrivals', e)
      upcomingArrivals.value = []
    } finally {
      isLoading.value = false
    }
  }
}

async function checkFavoriteStatus() {
  const token = localStorage.getItem('auth_token')
  if (!token || !props.busStop) {
    isFavorited.value = false
    favoriteId.value = null
    return
  }
  
  try {
    const favorites = await favoritesService.getMyFavorites()
    const found = favorites.find(f => f.item_type === 'stop' && f.item_id === props.busStop?.id)
    isFavorited.value = !!found
    favoriteId.value = found ? found.id : null
  } catch (e) {
    console.error("Error checking favorite status", e)
  }
}

async function toggleFavorite() {
  const token = localStorage.getItem('auth_token')
  if (!token) {
    alert("Debes iniciar sesión para guardar favoritos")
    return
  }

  if (!props.busStop) return

  try {
    if (isFavorited.value && props.busStop) {
      await favoritesService.removeFavorite('stop', props.busStop.id)
      isFavorited.value = false
      favoriteId.value = null
    } else {
      const fav = await favoritesService.addFavorite('stop', props.busStop.id)
      isFavorited.value = true
      favoriteId.value = fav.id
    }
  } catch (e) {
    alert("Error al actualizar favorito")
  }
}

function startInternalNavigation() {
  if (props.busStop) {
    emit('navigate', props.busStop)
  }
}

// Watch for changes in busStop or isOpen to reload data
watch(() => props.busStop, async (newStop) => {
  if (newStop && props.isOpen) {
    await loadArrivals()
    await checkFavoriteStatus()
  }
})

watch(() => props.isOpen, async (isOpen) => {
  if (isOpen && props.busStop) {
    await loadArrivals()
    await checkFavoriteStatus()
  }
})
</script>

<template>
  <Transition name="modal-fade">
    <div v-if="isOpen" class="modal-overlay" @click="emit('close')">
      <div class="modal-content" @click.stop>
        
        <!-- Header -->
        <div class="modal-header">
          <div v-if="busStop" class="header-info">
            <div class="title-row">
              <h3 class="stop-name">{{ busStop.name }}</h3>
              <button class="fav-btn" @click="toggleFavorite">
                <span class="material-icons" :class="{ 'favorited': isFavorited }">
                  {{ isFavorited ? 'favorite' : 'favorite_border' }}
                </span>
              </button>
            </div>
            <p v-if="busStop.address" class="stop-address">
              <span class="material-icons text-sm">location_on</span>
              {{ busStop.address }}
            </p>
          </div>
          <button class="close-btn" @click="emit('close')">
             <span class="material-icons">close</span>
          </button>
        </div>

        <!-- Amenities Chips -->
        <div v-if="busStop" class="amenities-container">
           <div v-if="busStop.has_shelter" class="amenity-chip" title="Shelter available">
             <span class="material-icons md-16">roofing</span>
             <span>Shelter</span>
           </div>
           <div v-if="busStop.has_seating" class="amenity-chip" title="Seating available">
             <span class="material-icons md-16">event_seat</span>
             <span>Seating</span>
           </div>
           <div v-if="busStop.is_accessible" class="amenity-chip" title="Wheelchair accessible">
             <span class="material-icons md-16">accessible</span>
             <span>Accessible</span>
           </div>
        </div>

        <!-- Body -->
        <div class="modal-body">
          <h4 class="section-title">Next Arrivals</h4>
          
          <div v-if="isLoading" class="loading-state">
            <span class="material-icons spin">refresh</span>
            <p>Loading arrivals...</p>
          </div>

          <div v-else-if="upcomingArrivals.length > 0" class="arrivals-list">
            <div 
              v-for="(arrival, index) in upcomingArrivals" 
              :key="index" 
              class="arrival-item"
              :style="{ animationDelay: `${index * 0.1}s` }"
            >
              <div class="route-info">
                <span class="material-icons bus-icon">directions_bus</span>
                <span class="route-name">{{ arrival.routeName }}</span>
              </div>
              <div class="arrival-time">
                {{ formatTo12Hour(arrival.arrivalTime) }}
              </div>
            </div>
          </div>

          <div v-else class="empty-state">
             <p>No upcoming arrivals found.</p>
          </div>
        </div>

        <!-- Footer / Actions -->
        <div class="modal-footer">
          <button class="action-btn secondary" @click="startInternalNavigation">
            <span class="material-icons md-18">navigation</span>
            Navigate
          </button>
          <button class="action-btn primary" @click="loadArrivals">
            <span class="material-icons md-18">refresh</span>
            Refresh
          </button>
        </div>

      </div>
    </div>
  </Transition>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end; /* Bottom sheet style on mobile, centered on desktop ideally */
  z-index: 1000;
}

/* On larger screens, center it */
@media (min-width: 768px) {
  .modal-overlay {
    align-items: center;
  }
}

.modal-content {
  background: var(--card-bg);
  width: 100%;
  max-width: 500px;
  border-radius: 16px 16px 0 0;
  padding: 24px;
  box-shadow: 0 -4px 20px rgba(0,0,0,0.15);
  animation: slide-up 0.3s ease-out;
  color: var(--text-primary);
}

@media (min-width: 768px) {
  .modal-content {
    border-radius: 16px;
    animation: zoom-in 0.2s ease-out;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.stop-name {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0;
  color: var(--text-primary);
}

.stop-address {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.875rem;
  color: var(--text-secondary);
  margin-top: 4px;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.fav-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  color: var(--text-secondary);
  transition: transform 0.2s, color 0.2s;
}

.fav-btn:hover {
  transform: scale(1.2);
}

.fav-btn .material-icons.favorited {
  color: #ff4757;
}

.close-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 4px;
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 12px;
  color: var(--text-primary);
}

.arrivals-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.arrival-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: var(--bg-secondary);
  border-radius: 8px;
}

.route-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bus-icon {
  color: var(--header-bg);
}

.route-name {
  font-weight: 500;
}

.arrival-time {
  font-weight: 700;
  color: var(--active-color, green);
}

/* Amenities Styles */
.amenities-container {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.amenity-chip {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: var(--bg-secondary);
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 0.75rem;
  font-weight: 500;
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
}

.md-16 { font-size: 16px; }
.md-18 { font-size: 18px; }

/* Modal Footer */
.modal-footer {
  margin-top: 24px;
  display: flex;
  justify-content: space-between; /* Spread buttons */
  gap: 12px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.action-btn.primary {
  background-color: var(--text-primary);
  color: var(--bg-primary);
  flex: 1; /* Take remaining space */
  justify-content: center;
}

.action-btn.secondary {
  background-color: transparent;
  color: var(--text-primary);
  border: 1px solid var(--border-color);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.action-btn:active {
  transform: translateY(0);
}

/* Animations */
.arrival-item {
  animation: fade-in-slide 0.4s ease-out forwards;
  opacity: 0; 
  transform: translateY(10px);
}

@keyframes fade-in-slide {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slide-up {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}

@keyframes zoom-in {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  color: var(--text-secondary);
}

.spin {
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

@keyframes spin { 100% { transform: rotate(360deg); } }
</style>
