<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useRouteStore } from '@/stores/route'
import { useTaxiStore } from '@/stores/taxi'
import { analyticsService } from '@/services/analyticsService'
import FavoriteButton from '@/components/FavoriteButton.vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const router = useRouter()
const routeStore = useRouteStore()
const taxiStore = useTaxiStore()

const activeTab = ref<'routes' | 'taxis'>('routes')
const originSearch = ref('')
const destinationSearch = ref('')
const selectedCorregimiento = ref('')
const englishOnly = ref(false)

onMounted(async () => {
  analyticsService.logEvent({ event_name: 'screen_view', screen_name: 'Transport' })
  await Promise.all([
    routeStore.loadRoutes(),
    taxiStore.loadTaxis()
  ])
})

const handleBusSearch = async () => {
  await routeStore.loadRoutes({
    originCity: originSearch.value,
    destinationCity: destinationSearch.value
  })
}

const handleTaxiFilter = async () => {
  await taxiStore.loadTaxis({
    corregimiento: selectedCorregimiento.value || undefined,
    english_speaking: englishOnly.value || undefined
  })
}

const goToSchedules = (route: any) => {
  analyticsService.logEvent({ 
    event_name: 'route_selected', 
    item_id: route.name,
    properties: { route_id: route.id }
  })
  routeStore.selectRoute(route.id, route.name)
  router.push({ path: '/schedules', query: { routeId: route.id } })
}

const callTaxi = (phoneNumber: string) => {
  window.open(`tel:${phoneNumber}`)
}

const correlimientos = computed(() => {
  const set = new Set(taxiStore.taxis.map(t => t.corregimiento).filter(Boolean))
  return Array.from(set).sort()
})


</script>

<template>
  <div class="transport-view bg-white dark:bg-background-dark min-h-screen text-slate-900 dark:text-white pb-32">
    <!-- Header -->
    <div class="px-6 pt-12 pb-4 flex items-center justify-between sticky top-0 z-50 bg-white/80 dark:bg-background-dark/80 backdrop-blur-md">
      <button @click="router.back()" class="size-10 flex items-center justify-center rounded-full bg-slate-100 dark:bg-card-dark text-slate-600 dark:text-gray-300 active:scale-95 transition-transform">
        <span class="material-icons text-[20px]">arrow_back</span>
      </button>
      <h1 class="text-xl font-extrabold tracking-tight text-primary uppercase italic">SIBU</h1>
      <div class="size-10"></div>
    </div>

    <div class="px-6 py-2 space-y-6">
      <!-- Tabs Selector -->
      <div class="bg-slate-50 dark:bg-card-dark rounded-[2.5rem] p-1.5 flex shadow-inner border border-slate-200 dark:border-white/5">
        <button 
          @click="activeTab = 'routes'"
          class="flex-1 py-3 px-4 rounded-[2rem] flex items-center justify-center gap-2 text-sm font-bold transition-all"
          :class="activeTab === 'routes' ? 'bg-primary shadow-lg text-slate-900' : 'bg-transparent text-slate-500 dark:text-gray-500'"
        >
          <span class="material-icons text-lg">directions_bus</span>
          {{ t('routesView.busTab') }}
        </button>
        <button 
          @click="activeTab = 'taxis'"
          class="flex-1 py-3 px-4 rounded-[2rem] flex items-center justify-center gap-2 text-sm font-bold transition-all"
          :class="activeTab === 'taxis' ? 'bg-primary shadow-lg text-slate-900' : 'bg-transparent text-slate-500 dark:text-gray-500'"
        >
          <span class="material-icons text-lg">local_taxi</span>
          {{ t('routesView.taxiTab') }}
        </button>
      </div>

      <!-- Search Panel -->
      <div class="bg-slate-50 dark:bg-card-dark rounded-[2.5rem] p-6 shadow-xl border border-slate-200 dark:border-white/10">
        <div v-if="activeTab === 'routes'" class="space-y-4">
          <div class="relative group">
            <div class="flex items-center gap-3 px-4 h-14 rounded-2xl border border-slate-200 dark:border-white/10 bg-white dark:bg-input-dark">
              <span class="material-icons text-primary font-bold">location_on</span>
              <input 
                v-model="originSearch"
                @keyup.enter="handleBusSearch"
                class="bg-transparent border-none focus:ring-0 text-sm font-semibold w-full placeholder:text-slate-400 dark:placeholder:text-gray-500"
                :placeholder="t('routesView.originPlaceholder')"
              />
            </div>
          </div>
          <div class="relative group">
            <div class="flex items-center gap-3 px-4 h-14 rounded-2xl border border-slate-200 dark:border-white/10 bg-white dark:bg-input-dark">
              <span class="material-icons text-primary font-bold">flag</span>
              <input 
                v-model="destinationSearch"
                @keyup.enter="handleBusSearch"
                class="bg-transparent border-none focus:ring-0 text-sm font-semibold w-full placeholder:text-slate-400 dark:placeholder:text-gray-500"
                :placeholder="t('routesView.destPlaceholder')"
              />
            </div>
          </div>
          <button @click="handleBusSearch" class="w-full bg-primary py-4 rounded-2xl text-slate-900 font-bold uppercase tracking-widest text-xs shadow-lg active:scale-95 transition-all">
            {{ t('routesView.searchBtn') }}
          </button>
        </div>

        <div v-else class="flex gap-4">
          <div class="flex-1 space-y-4">
            <div class="relative">
              <div class="flex items-center gap-3 px-4 h-14 rounded-2xl border border-slate-200 dark:border-white/10 bg-white dark:bg-input-dark">
                <span class="material-icons text-primary font-bold">near_me</span>
                <select 
                  v-model="selectedCorregimiento"
                  @change="handleTaxiFilter"
                  class="bg-transparent border-none focus:ring-0 text-sm font-semibold w-full dark:text-gray-200 appearance-none cursor-pointer"
                >
                  <option value="">{{ t('routesView.allCorregimientos') }}</option>
                  <option v-for="c in correlimientos" :key="c" :value="c">{{ c }}</option>
                </select>
                <span class="material-icons ml-auto text-gray-500 text-sm">unfold_more</span>
              </div>
            </div>
          </div>
          <div class="flex flex-col items-center justify-center px-2">
            <span class="text-[10px] font-black text-slate-400 dark:text-gray-400 mb-2 uppercase">{{ t('routesView.english') }}</span>
            <div 
              @click="englishOnly = !englishOnly; handleTaxiFilter()"
              class="size-10 rounded-lg border-2 border-primary flex items-center justify-center bg-transparent cursor-pointer transition-colors"
              :class="englishOnly ? 'bg-primary' : ''"
            >
              <span class="material-icons text-slate-900" v-if="englishOnly">check</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Results Area -->
    <div class="flex-1 px-6 pt-8 space-y-4 pb-32">
      <h2 class="text-[11px] font-black text-slate-400 dark:text-gray-500 uppercase tracking-[0.15em] mb-4">
        {{ activeTab === 'routes' ? t('routesView.availableRoutes') : t('routesView.recommendedDrivers') }}
      </h2>

      <!-- Loading Results -->
      <div v-if="routeStore.isLoadingRoutes || taxiStore.isLoading" class="flex justify-center py-10">
        <div class="w-10 h-10 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
      </div>

      <!-- Bus Routes List -->
      <template v-else-if="activeTab === 'routes'">
        <div 
          v-for="route in routeStore.allRoutes" 
          :key="route.id"
          v-memo="[route.id]"
          class="bg-slate-50 dark:bg-card-dark p-5 rounded-[2rem] shadow-sm border border-slate-200 dark:border-white/5 flex flex-col gap-4 active:scale-[0.98] transition-all cursor-pointer"
          @click="goToSchedules(route)"
        >
          <div class="flex justify-between items-center">
            <div class="flex items-center gap-4">
              <div class="size-14 rounded-2xl bg-primary/10 flex items-center justify-center text-primary">
                <span class="material-icons text-[32px]">directions_bus</span>
              </div>
              <div>
                <div class="flex items-center gap-2">
                  <p class="font-extrabold text-xl">{{ route.name }}</p>
                  <span class="px-2 py-0.5 rounded-full bg-primary text-[9px] font-black uppercase tracking-wider text-slate-900">{{ t('routesView.active') }}</span>
                </div>
                <p class="text-[11px] text-slate-500 dark:text-gray-400 font-bold uppercase tracking-tight">
                  {{ route.origin_city }} → {{ route.destination_city }}
                </p>
              </div>
            </div>
            <div class="text-right">
              <FavoriteButton 
                item-type="route" 
                :item-id="route.id" 
                :item-name="route.name"
              />
            </div>
          </div>
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2 bg-white dark:bg-input-dark px-3 py-2 rounded-xl border border-slate-200 dark:border-white/5">
              <span class="text-[10px] font-black dark:text-gray-200">{{ route.estimated_duration_minutes }} {{ t('routesView.minutes') }} • {{ route.distance_km }} {{ t('routesView.km') }}</span>
            </div>
            <button class="bg-primary px-8 py-3 rounded-2xl text-xs font-black uppercase tracking-widest shadow-sm hover:brightness-110 text-slate-900 transition-all">
              {{ t('routesView.findSchedules') }}
            </button>
          </div>
        </div>
        <div v-if="routeStore.allRoutes.length === 0" class="text-center py-10 opacity-50 italic">
          {{ t('routesView.noRoutes') }}
        </div>
      </template>

      <!-- Taxis List -->
      <template v-else>
        <div 
          v-for="taxi in taxiStore.taxis" 
          :key="taxi.id"
          v-memo="[taxi.id]"
          class="bg-slate-50 dark:bg-card-dark p-5 rounded-[2rem] shadow-sm border border-slate-200 dark:border-white/5 flex flex-col gap-4 active:scale-[0.98] transition-all"
        >
          <div class="flex justify-between items-center">
            <div class="flex items-center gap-4">
              <div class="size-14 rounded-2xl bg-primary/10 flex items-center justify-center text-primary overflow-hidden">
                <img v-if="taxi.image_url" :src="taxi.image_url" loading="lazy" decoding="async" class="w-full h-full object-cover">
                <span v-else class="material-icons text-[32px]">local_taxi</span>
              </div>
              <div>
                <div class="flex items-center gap-2">
                  <p class="font-extrabold text-xl">{{ taxi.owner_name }}</p>
                  <span class="px-2 py-0.5 rounded-full bg-primary text-[9px] font-black uppercase tracking-wider text-slate-900">PRO</span>
                </div>
                <p class="text-[11px] text-slate-500 dark:text-gray-400 font-bold uppercase tracking-tight">
                  {{ taxi.corregimiento }} • {{ taxi.license_plate }}
                </p>
              </div>
            </div>
            <div class="text-right flex flex-col items-end gap-2">
              <p class="font-black text-xl text-primary">{{ taxi.shift }}</p>
              <FavoriteButton 
                item-type="taxi" 
                :item-id="taxi.id" 
                :item-name="taxi.owner_name"
                :item-image="taxi.image_url || undefined"
              />
            </div>
          </div>
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-2 bg-white dark:bg-input-dark px-3 py-2 rounded-xl border border-slate-200 dark:border-white/5">
              <span class="text-[10px] font-black dark:text-gray-200">{{ taxi.rating || 5.0 }} ★</span>
              <span v-if="taxi.english_speaking" class="text-[10px] font-black text-blue-500 uppercase">{{ t('routesView.english') }}</span>
            </div>
            <button 
              @click="callTaxi(taxi.phone_number)"
              class="bg-primary px-8 py-3 rounded-2xl text-xs font-black uppercase tracking-widest shadow-sm hover:brightness-110 text-slate-900 transition-all"
            >
              {{ t('routesView.contact') }}
            </button>
          </div>
        </div>
        <div v-if="taxiStore.taxis.length === 0" class="text-center py-10 opacity-50 italic">
          {{ t('routesView.noTaxis') }}
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped>
.transport-view {
  font-family: 'Plus Jakarta Sans', sans-serif;
}

.bg-background-dark {
  background-color: #0F1115;
}

.bg-card-dark {
  background-color: #1C1F26;
}

.bg-input-dark {
  background-color: #252932;
}

select {
  outline: none;
}
</style>
