<template>
  <div class="admin-schedules">
    <div class="glass-container">
      <div class="header">
        <button class="back-link" @click="router.push('/admin')">
          <span class="material-icons notranslate" translate="no">arrow_back</span>
          Volver al Panel
        </button>
        <h1 class="premium-title">Gestión de Horarios</h1>
      </div>

      <!-- Route Selection -->
      <div class="selection-card glass-morphism">
        <div class="input-w-icon">
          <span class="material-icons notranslate" translate="no">route</span>
          <select v-model="selectedRouteId" @change="loadSchedules" class="premium-select">
            <option value="">-- Selecciona una ruta para gestionar --</option>
            <option v-for="route in routes" :key="route.id" :value="route.id">
              {{ route.name }} ({{ route.origin_city }} &rarr; {{ route.destination_city }})
            </option>
          </select>
        </div>
      </div>

      <div v-if="selectedRouteId" class="schedules-content">
        <div class="actions-header">
          <h2 class="section-title">Horarios Configurados</h2>
          <button class="add-btn premium-btn" @click="showAddForm = true">
            <span class="material-icons notranslate" translate="no">add</span> Nuevo Horario
          </button>
        </div>

        <!-- Add/Edit form -->
        <Transition name="fade">
          <div v-if="showAddForm || editingSchedule" class="schedule-form-card glass-morphism active-border">
            <h3 class="form-title">{{ editingSchedule ? 'Editar Horario' : 'Agregar Nuevo Horario' }}</h3>
            <div class="form-grid">
              <div class="form-group">
                <label>Hora de Salida</label>
                <div class="input-wrapper">
                  <span class="material-icons notranslate" translate="no">schedule</span>
                  <input v-model="form.departure_time" type="time" required>
                </div>
              </div>
              <div class="form-group">
                <label>Frecuencia (min)</label>
                <div class="input-wrapper">
                  <span class="material-icons notranslate" translate="no">update</span>
                  <input v-model.number="form.frequency_minutes" type="number" placeholder="30">
                </div>
              </div>
              <div class="form-group">
                <label>Tipo de Día</label>
                <div class="input-wrapper">
                  <span class="material-icons notranslate" translate="no">calendar_today</span>
                  <select v-model="form.schedule_type">
                    <option value="weekday">Día de Semana</option>
                    <option value="weekend">Fin de Semana</option>
                    <option value="holiday">Feriado</option>
                  </select>
                </div>
              </div>
              <div class="form-group toggle-group">
                <label class="switch-label">
                  <span>Publicado</span>
                  <input v-model="form.is_published" type="checkbox" class="retro-checkbox">
                </label>
              </div>
              <div class="form-group toggle-group">
                <label class="switch-label">
                  <span>Activo (Operativo)</span>
                  <input v-model="form.is_active" type="checkbox" class="retro-checkbox">
                </label>
              </div>
            </div>
            <div class="form-actions">
              <button class="btn-secondary" @click="cancelForm">Cancelar</button>
              <button class="btn-primary" @click="saveSchedule">Guardar Horario</button>
            </div>
          </div>
        </Transition>

        <!-- Schedules List -->
        <div class="schedules-list">
          <div v-if="isLoadingSchedules" class="loader-container">
            <span class="material-icons spin notranslate" translate="no">refresh</span>
            <p>Cargando horarios...</p>
          </div>
          <div v-else-if="schedules.length === 0" class="empty-state glass-morphism">
            <span class="material-icons notranslate" translate="no">event_busy</span>
            <p>No hay horarios configurados para esta ruta.</p>
          </div>
          <div v-else class="grid-container">
            <div 
              v-for="schedule in sortedSchedules" 
              :key="schedule.id" 
              class="schedule-card-premium glass-morphism" 
              :class="{ 'draft-card': !schedule.is_published }"
            >
              <div class="card-left">
                <div class="time-display">{{ formatTo12Hour(schedule.departure_time) }}</div>
                <div class="type-tag" :class="schedule.schedule_type">
                  {{ translateType(schedule.schedule_type) }}
                </div>
              </div>
              
              <div class="card-right">
                <div class="status-indicator">
                  <span class="dot" :class="{ 'online': schedule.is_published }"></span>
                  {{ schedule.is_published ? 'Publicado' : 'Borrador' }}
                </div>
                <div class="action-buttons">
                  <button class="icon-btn edit-btn" @click="editSchedule(schedule)" title="Editar">
                    <span class="material-icons notranslate" translate="no">edit</span>
                  </button>
                  <button class="icon-btn delete-btn" @click="handleDelete(schedule.id)" title="Eliminar">
                    <span class="material-icons notranslate" translate="no">delete</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="no-selection-state">
        <div class="icon-circle">
          <span class="material-icons notranslate" translate="no">list_alt</span>
        </div>
        <h3>Gestión de Despachos</h3>
        <p>Selecciona una ruta del menú superior para administrar los horarios de salida y frecuencia.</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { routesService } from '@/services/routesService'
import { schedulesService } from '@/services/schedulesService'
import { formatTo12Hour } from '@/utils/timeFormatter'

const router = useRouter()
const routes = ref<any[]>([])
const selectedRouteId = ref('')
const schedules = ref<any[]>([])
const showAddForm = ref(false)
const editingSchedule = ref<any>(null)
const isLoadingSchedules = ref(false)

const form = ref({
  departure_time: '06:00',
  frequency_minutes: 30,
  schedule_type: 'weekday',
  is_published: true,
  is_active: true
})

onMounted(async () => {
  try {
    const data = await routesService.getAllRoutes()
    routes.value = data || []
  } catch (e) {
    console.error('Error loading routes', e)
  }
})

const sortedSchedules = computed(() => {
  return [...schedules.value].sort((a, b) => a.departure_time.localeCompare(b.departure_time))
})

async function loadSchedules() {
  if (!selectedRouteId.value) {
    schedules.value = []
    return
  }
  isLoadingSchedules.value = true
  try {
    // Get all schedules including drafts (false for onlyPublished)
    const data = await schedulesService.getRouteSchedules(selectedRouteId.value, false)
    schedules.value = data || []
  } catch (e) {
    console.error('Error loading schedules', e)
  } finally {
    isLoadingSchedules.value = false
  }
}

function translateType(type: string) {
  const map: Record<string, string> = {
    'weekday': 'Día de Semana',
    'weekend': 'Fin de Semana',
    'holiday': 'Feriado'
  }
  return map[type] || type
}

function editSchedule(schedule: any) {
  editingSchedule.value = schedule
  form.value = {
    departure_time: schedule.departure_time,
    frequency_minutes: schedule.frequency_minutes,
    schedule_type: schedule.schedule_type,
    is_published: schedule.is_published,
    is_active: schedule.is_active
  }
  showAddForm.value = true
}

function cancelForm() {
  showAddForm.value = false
  editingSchedule.value = null
  resetForm()
}

function resetForm() {
  form.value = {
    departure_time: '06:00',
    frequency_minutes: 30,
    schedule_type: 'weekday',
    is_published: true,
    is_active: true
  }
}

async function saveSchedule() {
  try {
    if (editingSchedule.value) {
      await schedulesService.updateSchedule(editingSchedule.value.id, form.value)
    } else {
      await schedulesService.createSchedule({
        ...form.value,
        route_id: selectedRouteId.value
      })
    }
    await loadSchedules()
    cancelForm()
  } catch (e: any) {
    console.error('Save error details:', e.response?.data || e)
    const errorMsg = e.response?.data?.detail 
      ? (typeof e.response.data.detail === 'string' ? e.response.data.detail : JSON.stringify(e.response.data.detail))
      : 'Error de conexión con el servidor'
    alert('Error al guardar: ' + errorMsg)
  }
}

async function handleDelete(id: string) {
  if (!confirm('¿Estás seguro de eliminar este horario?')) return
  try {
    await schedulesService.deleteSchedule(id)
    await loadSchedules()
  } catch (e: any) {
    console.error('Delete error:', e.response?.data || e)
    const errorMsg = e.response?.data?.detail 
      ? (typeof e.response.data.detail === 'string' ? e.response.data.detail : JSON.stringify(e.response.data.detail))
      : 'Error al eliminar el registro'
    alert('Error: ' + errorMsg)
  }
}
</script>

<style scoped>
.admin-schedules {
  padding: 40px 20px;
  min-height: 100vh;
  background: var(--bg-primary);
}

.glass-container {
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 32px;
}

.back-link {
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  padding: 8px 16px;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 600;
  width: fit-content;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.back-link:hover {
  transform: translateX(-4px);
  background: var(--hover-bg);
  border-color: var(--active-color);
}

.premium-title {
  font-size: 2.5rem;
  font-weight: 900;
  background: linear-gradient(135deg, #fee715 0%, #facc15 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: -0.04em;
}

.glass-morphism {
  background: var(--card-bg);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border: 1px solid var(--border-color);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
}

.selection-card {
  padding: 24px;
  margin-bottom: 40px;
}

.input-w-icon {
  display: flex;
  align-items: center;
  gap: 12px;
  background: var(--bg-secondary);
  padding: 12px 16px;
  border-radius: 14px;
  border: 1px solid var(--border-color);
}

.input-w-icon .material-icons {
  color: var(--active-color);
}

.premium-select {
  flex: 1;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
  outline: none;
  cursor: pointer;
}

.premium-select option {
  background: var(--bg-primary, #1e1e2d);
  color: var(--text-primary, #ffffff);
}

.actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 800;
  color: var(--text-primary);
}

.premium-btn {
  background: linear-gradient(135deg, #fee715 0%, #facc15 100%);
  color: #101820;
  border: none;
  padding: 12px 24px;
  border-radius: 14px;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 10px 20px rgba(254, 231, 21, 0.2);
}

.premium-btn:hover {
  transform: translateY(-4px);
  box-shadow: 0 15px 30px rgba(254, 231, 21, 0.3);
}

.schedule-form-card {
  padding: 32px;
  margin-bottom: 32px;
}

.active-border {
  border-color: var(--active-color);
}

.form-title {
  margin-bottom: 24px;
  font-size: 1.25rem;
  font-weight: 800;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.form-group label {
  display: block;
  font-size: 0.9rem;
  font-weight: 700;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--bg-secondary);
  padding: 10px 14px;
  border-radius: 10px;
  border: 1.5px solid var(--border-color);
}

.input-wrapper input, .input-wrapper select {
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-weight: 600;
  width: 100%;
  outline: none;
}

.switch-label {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
}

.retro-checkbox {
  width: 20px;
  height: 20px;
  accent-color: var(--active-color);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.btn-primary {
  background: var(--active-color);
  color: #101820;
  border: none;
  padding: 12px 28px;
  border-radius: 12px;
  font-weight: 800;
  cursor: pointer;
}

.btn-secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  padding: 12px 28px;
  border-radius: 12px;
  font-weight: 700;
  cursor: pointer;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.schedule-card-premium {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s ease;
}

.schedule-card-premium:hover {
  transform: scale(1.02);
  border-color: var(--active-color);
}

.draft-card {
  opacity: 0.6;
  background: var(--bg-secondary);
}

.time-display {
  font-size: 1.75rem;
  font-weight: 900;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.type-tag {
  font-size: 0.75rem;
  font-weight: 800;
  padding: 4px 10px;
  border-radius: 6px;
  display: inline-block;
}

.type-tag.weekday { background: rgba(52, 152, 219, 0.1); color: #3498db; }
.type-tag.weekend { background: rgba(155, 89, 182, 0.1); color: #9b59b2; }
.type-tag.holiday { background: rgba(231, 76, 60, 0.1); color: #e74c3c; }

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.8rem;
  font-weight: 700;
  color: var(--text-secondary);
  margin-bottom: 12px;
  justify-content: flex-end;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #95a5a6;
}

.dot.online {
  background: #2ecc71;
  box-shadow: 0 0 8px #2ecc71;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.icon-btn {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--border-color);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.2s;
}

.edit-btn:hover { background: var(--hover-bg); color: var(--active-color); border-color: var(--active-color); }
.delete-btn:hover { background: #fff0f0; color: #e74c3c; border-color: #ef4444; }

.no-selection-state {
  text-align: center;
  padding: 80px 40px;
}

.icon-circle {
  width: 100px;
  height: 100px;
  background: var(--bg-secondary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
}

.icon-circle .material-icons {
  font-size: 3rem;
  color: var(--active-color);
  opacity: 0.5;
}

.no-selection-state h3 {
  font-size: 1.5rem;
  font-weight: 800;
  margin-bottom: 12px;
}

.no-selection-state p {
  color: var(--text-secondary);
  max-width: 400px;
  margin: 0 auto;
}

.loader-container {
  text-align: center;
  padding: 40px;
}

.spin {
  animation: spin 1s linear infinite;
  display: block;
  margin: 0 auto 12px;
  font-size: 2rem;
  color: var(--active-color);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.fade-enter-active, .fade-leave-active { transition: opacity 0.3s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
