<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { supabase } from '@/supabase';

const router = useRouter();
const isLoading = ref(false);
const showMessage = ref({ text: '', type: '' });

const selectedFile = ref<File | null>(null);
const selectedFileName = ref('');

// Form state
const shuttleForm = ref({
  company_name: 'Chiriqui Transfers',
  origin: 'Boquete',
  destination: 'Santa Catalina',
  vehicle_type: 'Mini Van Compartida',
  category: 'local',
  description: '',
  price_per_person: 35,
  price_private_trip: 180,
  estimated_duration: '4.5 horas',
  departure_times: 'Todos los días 8:00 AM',
  contact_whatsapp: '50712345678',
  phone_number: '50712345678',
  english_speaking: true,
  image_url: '',
  is_active: true
});

const previewImageUrl = ref('https://images.unsplash.com/photo-1449034446853-66c86144b0ad?q=80&w=2070&auto=format&fit=crop');

function handleImageChange(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    selectedFile.value = file;
    selectedFileName.value = file.name;
    
    // Preview logic
    const reader = new FileReader();
    reader.onload = (e) => {
      previewImageUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
}

async function saveShuttle() {
  isLoading.value = true;
  showMessage.value = { text: '', type: '' };
  
  try {
    let image_url = '';

    if (selectedFile.value) {
      const ext = selectedFile.value.name.split('.').pop();
      const filename = `shuttles/${Date.now()}.${ext}`;
      const { error: upErr } = await supabase.storage.from('uploads').upload(filename, selectedFile.value);
      if (upErr) throw upErr;
      const { data: urlData } = supabase.storage.from('uploads').getPublicUrl(filename);
      image_url = urlData.publicUrl;
    }

    const payload = {
      route_name: `${shuttleForm.value.origin} - ${shuttleForm.value.destination}`,
      origin: shuttleForm.value.origin,
      destination: shuttleForm.value.destination,
      vehicle_type: shuttleForm.value.vehicle_type,
      category: shuttleForm.value.category,
      description: shuttleForm.value.description,
      company_name: shuttleForm.value.company_name,
      price_per_person: shuttleForm.value.price_per_person,
      price_private_trip: shuttleForm.value.price_private_trip,
      estimated_duration: shuttleForm.value.estimated_duration,
      departure_times: shuttleForm.value.departure_times,
      contact_whatsapp: shuttleForm.value.contact_whatsapp,
      phone_number: shuttleForm.value.phone_number,
      english_speaking: shuttleForm.value.english_speaking,
      is_active: shuttleForm.value.is_active,
      image_url: image_url || shuttleForm.value.image_url
    };

    const { error: insertError } = await supabase.from('shuttles').insert([payload]);
    
    if (insertError) {
      throw insertError;
    }

    showMessage.value = { text: '¡Viaje Turístico Desplegado!', type: 'success' };
    setTimeout(() => router.push('/admin'), 2000);
  } catch (error: any) {
    console.error('Error saving shuttle:', error);
    const errorDetail = error.response?.data?.detail || 'Error en el despliegue del sistema.';
    showMessage.value = { text: errorDetail, type: 'error' };
  } finally {
    isLoading.value = false;
  }
}
</script>

<template>
  <div class="admin-shuttles-view">
    <div class="nexus-admin-header">
      <button class="back-btn" @click="router.push('/admin')">
        <span class="material-icons">arrow_back</span>
      </button>
      <h1>Generador de Shuttles Turísticos</h1>
      <div class="header-status">ID: SHUTTLE-MARK-I</div>
    </div>

    <div class="admin-grid-layout">
      <!-- FORM PANEL -->
      <section class="form-panel nexus-glass">
        <div class="section-title">
          <span class="material-icons">edit_note</span>
          <h2>Datos del Servicio</h2>
        </div>

        <div class="nexus-form">
          <div class="form-group grid-row">
            <div class="input-box">
              <label>Nombre de la Empresa</label>
              <input v-model="shuttleForm.company_name" type="text" placeholder="Ej: Chiriqui Transfers" />
            </div>
            <div class="input-box">
              <label>Imagen del Transporte</label>
              <div class="file-upload-wrapper">
                <input type="file" @change="handleImageChange" accept="image/*" id="file-input" />
                <label for="file-input" class="file-label">
                  <span class="material-icons">cloud_upload</span>
                  {{ selectedFileName || 'SELECCIONAR IMAGEN' }}
                </label>
                <p class="upload-hint">Recomendado: 1200x900px (4:3)</p>
              </div>
            </div>
          </div>

          <div class="form-group grid-row">
            <div class="input-box">
              <label>Origen</label>
              <input v-model="shuttleForm.origin" type="text" placeholder="Boquete" />
            </div>
            <div class="input-box">
              <label>Destino</label>
              <input v-model="shuttleForm.destination" type="text" placeholder="Santa Catalina" />
            </div>
          </div>

          <div class="form-group grid-row">
            <div class="input-box">
              <label>Tipo de Vehículo</label>
              <input v-model="shuttleForm.vehicle_type" type="text" placeholder="Mini Van Compartida" />
            </div>
            <div class="input-box">
              <label>Categoría</label>
              <select v-model="shuttleForm.category" class="nexus-select">
                <option value="local">Evento Local / Interno</option>
                <option value="interprovincial">Interprovincial (Fuera de provincia)</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label>Descripción del Viaje</label>
            <textarea 
              v-model="shuttleForm.description" 
              placeholder="Añade detalles sobre el itinerario, paradas, o qué incluye el viaje..."
              rows="3"
              class="nexus-textarea"
            ></textarea>
          </div>

          <div class="form-group grid-row">
            <div class="input-box">
              <label>Duración Estimada</label>
              <input v-model="shuttleForm.estimated_duration" type="text" placeholder="4.5 horas" />
            </div>
            <div class="input-box">
              <label>Salidas</label>
              <input v-model="shuttleForm.departure_times" type="text" placeholder="Todos los días 8:00 AM" />
            </div>
          </div>

          <div class="form-group grid-row">
            <div class="input-box">
              <label>Precio por Persona ($)</label>
              <input v-model="shuttleForm.price_per_person" type="number" />
            </div>
            <div class="input-box">
              <label>Precio Viaje Privado ($)</label>
              <input v-model="shuttleForm.price_private_trip" type="number" />
            </div>
          </div>

          <div class="form-group grid-row">
            <div class="input-box">
              <label>WhatsApp (Sin +)</label>
              <div class="whatsapp-input">
                <span class="prefix">+</span>
                <input v-model="shuttleForm.contact_whatsapp" type="text" placeholder="50760000000" />
              </div>
            </div>
            <div class="input-box">
              <label>Teléfono de Llamada</label>
              <input v-model="shuttleForm.phone_number" type="text" placeholder="50760000000" />
            </div>
          </div>

          <div class="form-group">
            <label class="toggle-container">
              <div class="toggle-text">
                <span class="material-icons">translate</span>
                <span>¿Habla Inglés? (Bilingüe)</span>
              </div>
              <div class="nexus-switch">
                <input type="checkbox" v-model="shuttleForm.english_speaking" />
                <span class="slider"></span>
              </div>
            </label>
          </div>

          <button class="deploy-btn" :disabled="isLoading" @click="saveShuttle">
            <span class="material-icons">{{ isLoading ? 'sync' : 'rocket_launch' }}</span>
            {{ isLoading ? 'PROCESANDO...' : 'PUBLICAR EN SIB' }}
          </button>
          
          <p v-if="showMessage.text" :class="['message', showMessage.type]">{{ showMessage.text }}</p>
        </div>
      </section>

      <!-- PREVIEW PANEL -->
      <section class="preview-panel">
        <div class="section-title white">
          <span class="material-icons">visibility</span>
          <h2>Previsualización en Directo</h2>
        </div>

        <div class="preview-container">
          <!-- PREVIEW CARD -->
          <div class="shuttle-card-preview" :class="{ expanded: true }">
            <img :src="previewImageUrl" class="shuttle-card-bg" @error="(e) => (e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1449034446853-66c86144b0ad?q=80&w=2070&auto=format&fit=crop'" />
            <div class="shuttle-main-info">
              <div class="shuttle-header-mini">
                <div class="company-badge">
                  <span class="material-icons">business</span>
                  {{ shuttleForm.company_name }}
                </div>
                <div class="price-pill">
                  <span class="currency">$</span>
                  <span class="amount">{{ shuttleForm.price_per_person }}</span>
                  <span class="price-pill-label">/p</span>
                </div>
              </div>

              <div class="shuttle-route-compact">
                <span class="route-text">{{ shuttleForm.origin }}</span>
                <span class="material-icons route-arrow">arrow_forward</span>
                <span class="route-text">{{ shuttleForm.destination }}</span>
              </div>

              <div class="shuttle-tags">
                <div class="vehicle-tag-mini">
                  <span class="material-icons">directions_bus</span>
                  {{ shuttleForm.vehicle_type }}
                </div>
                <div class="expand-indicator">
                  <span class="material-icons">expand_less</span>
                </div>
              </div>
            </div>

            <!-- EXPANDED CONTENT PREVIEW -->
            <div class="shuttle-details">
              <div class="shuttle-separator"></div>

              <div class="shuttle-body">
                <div class="info-row">
                  <span class="material-icons">schedule</span>
                  <div>
                    <p class="label">DURACIÓN ESTIMADA</p>
                    <p class="value">{{ shuttleForm.estimated_duration }}</p>
                  </div>
                </div>
                <div class="info-row">
                  <span class="material-icons">event</span>
                  <div>
                    <p class="label">SALIDAS</p>
                    <p class="value">{{ shuttleForm.departure_times }}</p>
                  </div>
                </div>
                <div class="info-row" v-if="shuttleForm.english_speaking">
                  <span class="material-icons">g_translate</span>
                  <div>
                    <p class="label">IDIOMA</p>
                    <p class="value">Español · English</p>
                  </div>
                </div>
              </div>

              <!-- NUEVA DESCRIPCIÓN EN PREVIEW -->
              <div class="shuttle-description-preview" v-if="shuttleForm.description">
                <p>{{ shuttleForm.description }}</p>
              </div>

              <!-- Precios prominentes -->
              <div class="price-block">
                <div class="price-row-main">
                  <span class="price-amount-big">${{ shuttleForm.price_per_person }}</span>
                  <span class="price-label-big">por persona</span>
                </div>
                <div class="price-row-secondary" v-if="shuttleForm.price_private_trip">
                  <span class="material-icons price-icon-secondary">directions_car</span>
                  <span class="price-amount-secondary">${{ shuttleForm.price_private_trip }}</span>
                  <span class="price-label-secondary">viaje privado</span>
                </div>
              </div>

              <!-- Botones de contacto -->
              <div class="contact-buttons-preview">
                <button class="btn-whatsapp-preview">
                  <span class="material-icons">chat</span>
                  WhatsApp
                </button>
              </div>
            </div>
          </div>
          <p class="preview-hint">Esta es la apariencia final que verán los usuarios en su app móvil.</p>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.admin-shuttles-view {
  min-height: 100vh;
  background: #0f172a;
  color: white;
  padding: 40px;
  font-family: 'Inter', sans-serif;
}

.nexus-admin-header {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 40px;
}

.back-btn {
  background: rgba(255,255,255,0.1);
  border: none;
  color: white;
  width: 44px;
  height: 44px;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nexus-admin-header h1 {
  font-size: 2rem;
  font-weight: 800;
  margin: 0;
  background: linear-gradient(135deg, #fff 0%, #94a3b8 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-status {
  padding: 4px 12px;
  background: rgba(254, 231, 21, 0.1);
  color: #fee715;
  border: 1px solid rgba(254, 231, 21, 0.2);
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 800;
  margin-left: auto;
}

.admin-grid-layout {
  display: grid;
  grid-template-columns: 1fr 450px;
  gap: 40px;
}

.nexus-glass {
  background: rgba(30, 41, 59, 0.5);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 32px;
  padding: 32px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 32px;
  color: #94a3b8;
}

.section-title h2 {
  font-size: 1.25rem;
  margin: 0;
}

.section-title.white {
  color: white;
}

.nexus-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.grid-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 0.85rem;
  font-weight: 600;
  color: #94a3b8;
}

.form-group input, .nexus-select, .nexus-textarea {
  background: rgba(15, 23, 42, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 14px 16px;
  border-radius: 12px;
  color: white;
  font-size: 1rem;
  outline: none;
  transition: all 0.3s;
}

.nexus-select {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='white'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 1rem center;
  background-size: 1.5em;
  padding-right: 3rem;
}

.nexus-textarea {
  resize: vertical;
  min-height: 100px;
}

.form-group input:focus, .nexus-select:focus, .nexus-textarea:focus {
  border-color: #fee715;
  box-shadow: 0 0 0 4px rgba(254, 231, 21, 0.1);
}

.shuttle-description-preview {
  padding: 0 20px 14px;
  color: rgba(255,255,255,0.7);
  font-size: 0.85rem;
  line-height: 1.5;
  white-space: pre-wrap;
}

.file-upload-wrapper {
  position: relative;
  width: 100%;
}

.file-upload-wrapper input[type="file"] {
  position: absolute;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  z-index: -1;
}

.file-label {
  display: flex !important;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background: rgba(254, 231, 21, 0.1) !important;
  border: 1px dashed #fee715 !important;
  padding: 12px !important;
  border-radius: 12px;
  color: #fee715 !important;
  font-weight: 800;
  cursor: pointer;
  transition: all 0.3s;
  text-transform: uppercase;
  font-size: 0.75rem !important;
}

.file-label:hover {
  background: rgba(254, 231, 21, 0.2) !important;
}

.upload-hint {
  font-size: 0.7rem;
  color: #94a3b8;
  margin-top: 6px;
  font-weight: 600;
  text-align: right;
}

.whatsapp-input {
  display: flex;
  background: rgba(15, 23, 42, 0.5);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.whatsapp-input .prefix {
  padding: 14px 16px;
  background: rgba(255,255,255,0.05);
  color: #94a3b8;
  font-weight: 700;
}

.whatsapp-input input {
  flex: 1;
  border: none;
  background: transparent;
}

.deploy-btn {
  margin-top: 20px;
  background: #fee715;
  color: #101820;
  border: none;
  padding: 20px;
  border-radius: 16px;
  font-weight: 800;
  font-size: 1.1rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  transition: all 0.3s;
}

.deploy-btn:hover:not(:disabled) {
  transform: translateY(-4px);
  box-shadow: 0 10px 20px rgba(254, 231, 21, 0.2);
}

.deploy-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* SHUTTLE PREVIEW CARD PREMIUM STYLES */
.shuttle-card-preview {
  width: 100%;
  border-radius: 20px;
  overflow: hidden;
  border: 1px solid rgba(255,255,255,0.12);
  position: relative;
  display: flex;
  flex-direction: column;
  box-shadow: 0 30px 60px rgba(0,0,0,0.5);
  background: #101820;
}

.shuttle-card-bg {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;
}

.shuttle-card-preview::before {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to top,
    rgba(0, 0, 0, 0.93) 0%,
    rgba(0, 0, 0, 0.65) 55%,
    rgba(0, 0, 0, 0.30) 100%
  );
  z-index: 1;
}

.shuttle-card-preview.expanded {
  border: 2px solid #FEE715;
}

.shuttle-card-preview.expanded::before {
  background: linear-gradient(
    to top,
    rgba(0, 0, 0, 0.97) 0%,
    rgba(0, 0, 0, 0.80) 45%,
    rgba(0, 0, 0, 0.40) 100%
  );
}

.shuttle-main-info,
.shuttle-details {
  position: relative;
  z-index: 2;
  padding: 18px 20px;
}

.shuttle-main-info {
  padding-bottom: 14px;
}

.shuttle-header-mini {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}

.shuttle-card-preview .company-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  background: rgba(0, 0, 0, 0.60);
  color: #FEE715;
  padding: 5px 11px;
  border-radius: 10px;
  font-size: 0.75rem;
  font-weight: 800;
  border: 1px solid rgba(254, 231, 21, 0.45);
  backdrop-filter: blur(8px);
}

.price-pill {
  background: #FEE715;
  color: #101820;
  padding: 5px 11px;
  border-radius: 10px;
  font-weight: 900;
  font-size: 1rem;
  display: flex;
  align-items: baseline;
  gap: 1px;
  box-shadow: 0 4px 12px rgba(254, 231, 21, 0.35);
}

.price-pill .currency { font-size: 0.8rem; }
.price-pill .amount { font-size: 1rem; }
.price-pill-label { font-size: 0.7rem; font-weight: 700; opacity: 0.75; }

.shuttle-route-compact {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 1.1rem;
  font-weight: 900;
  color: #ffffff;
  margin-bottom: 14px;
}

.route-arrow {
  color: #FEE715;
  font-size: 20px;
}

.shuttle-tags {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vehicle-tag-mini {
  padding: 5px 10px;
  background: rgba(255, 255, 255, 0.12);
  border-radius: 8px;
  font-size: 0.72rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.20);
}

.vehicle-tag-mini .material-icons { font-size: 15px; color: #FEE715; }
.expand-indicator { color: #FEE715; }

.shuttle-separator {
  height: 1px;
  background: linear-gradient(to right, transparent, rgba(255,255,255,0.25), transparent);
  margin: 0 0 16px;
}

.shuttle-body {
  display: flex;
  flex-direction: column;
  gap: 14px;
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-row .material-icons { color: #FEE715; font-size: 22px; }

.info-row .label {
  font-size: 0.65rem;
  color: rgba(255, 255, 255, 0.55);
  margin: 0;
  text-transform: uppercase;
  font-weight: 700;
}

.info-row .value {
  font-size: 0.95rem;
  color: #ffffff;
  margin: 2px 0 0;
  font-weight: 700;
}

.price-block {
  padding: 14px 0;
  border-top: 1px solid rgba(255,255,255,0.08);
  border-bottom: 1px solid rgba(255,255,255,0.08);
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.price-row-main {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.price-amount-big {
  font-size: 2rem;
  font-weight: 900;
  color: #FEE715;
  line-height: 1;
}

.price-label-big {
  font-size: 0.85rem;
  color: rgba(255,255,255,0.75);
  font-weight: 600;
}

.price-row-secondary {
  display: flex;
  align-items: center;
  gap: 6px;
}

.price-icon-secondary { font-size: 16px; color: rgba(255,255,255,0.55); }
.price-amount-secondary { font-size: 1rem; font-weight: 800; color: rgba(255,255,255,0.85); }
.price-label-secondary { font-size: 0.75rem; color: rgba(255,255,255,0.5); }

.contact-buttons-preview {
  width: 100%;
}

.btn-whatsapp-preview {
  width: 100%;
  background: #25d366;
  color: white;
  border: none;
  padding: 14px;
  border-radius: 12px;
  font-weight: 800;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 1rem;
}

.preview-hint {
  text-align: center;
  color: #94a3b8;
  font-size: 0.85rem;
  margin-top: 20px;
}

.toggle-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(15, 23, 42, 0.5);
  padding: 14px 16px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  cursor: pointer;
}

.toggle-text {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #94a3b8;
  font-weight: 600;
}

.nexus-switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}

.nexus-switch input { opacity: 0; width: 0; height: 0; }

.nexus-switch .slider {
  position: absolute;
  cursor: pointer;
  inset: 0;
  background-color: rgba(255,255,255,0.1);
  transition: .4s;
  border-radius: 34px;
}

.nexus-switch .slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

.nexus-switch input:checked + .slider { background-color: #fee715; }
.nexus-switch input:checked + .slider:before { transform: translateX(20px); background-color: #101820; }

.message {
  text-align: center;
  padding: 12px;
  border-radius: 12px;
  font-weight: 700;
}

.message.success { background: rgba(37, 211, 102, 0.1); color: #25d366; }
.message.error { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

@media (max-width: 1100px) {
  .admin-grid-layout { grid-template-columns: 1fr; }
  .preview-panel { order: -1; }
}
</style>
