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

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',
  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 {
    const token = localStorage.getItem('auth_token');
    const formData = new FormData();
    
    // Añadimos campos obligatorios para el backend
    formData.append('route_name', `${shuttleForm.value.origin} - ${shuttleForm.value.destination}`);
    formData.append('origin', shuttleForm.value.origin);
    formData.append('destination', shuttleForm.value.destination);
    formData.append('vehicle_type', shuttleForm.value.vehicle_type);
    formData.append('company_name', shuttleForm.value.company_name);
    formData.append('price_per_person', String(shuttleForm.value.price_per_person));
    formData.append('price_private_trip', String(shuttleForm.value.price_private_trip));
    formData.append('estimated_duration', shuttleForm.value.estimated_duration);
    formData.append('departure_times', shuttleForm.value.departure_times);
    formData.append('contact_whatsapp', shuttleForm.value.contact_whatsapp);
    formData.append('phone_number', shuttleForm.value.phone_number);
    formData.append('english_speaking', String(shuttleForm.value.english_speaking));
    
    if (selectedFile.value) {
      formData.append('image', selectedFile.value);
    }

    await axios.post(`${API_URL}/api/shuttles`, formData, {
      headers: { 
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });

    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">
            <label>Tipo de Vehículo</label>
            <input v-model="shuttleForm.vehicle_type" type="text" placeholder="Mini Van Compartida">
          </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 SIBU' }}
          </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">
          <!-- LA TARJETA TAL CUAL LA IMAGEN DEL USUARIO -->
          <div class="shuttle-card-preview" :style="{ backgroundImage: `url(${shuttleForm.image_url})` }">
            <div class="card-header">
              <div class="company-badge">
                <span class="material-icons">business</span>
                {{ shuttleForm.company_name }}
              </div>
              <div class="price-badge-top">
                ${{ shuttleForm.price_per_person }}
              </div>
            </div>

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

            <div class="vehicle-tag">
              <span class="material-icons">directions_bus</span>
              {{ shuttleForm.vehicle_type }}
            </div>

            <div class="card-details-box">
              <div class="detail-item">
                <span class="material-icons icon-yellow">schedule</span>
                <div class="texts">
                  <span class="label">DURACIÓN ESTIMADA</span>
                  <span class="val">{{ shuttleForm.estimated_duration }}</span>
                </div>
              </div>
              <div class="detail-item">
                <span class="material-icons icon-yellow">calendar_today</span>
                <div class="texts">
                  <span class="label">SALIDAS</span>
                  <span class="val">{{ shuttleForm.departure_times }}</span>
                </div>
              </div>
            </div>

            <div class="card-footer-preview">
              <div class="price-info">
                <span class="main-price">${{ shuttleForm.price_per_person }} <small>por persona</small></span>
                <div class="lang-indicator" v-if="shuttleForm.english_speaking">
                   <span class="material-icons">g_translate</span>
                   ENGLISH
                </div>
              </div>
              <div class="contact-actions">
                <div class="mini-contact-btn phone">
                  <span class="material-icons">phone</span>
                </div>
                <div class="mini-contact-btn wa">
                  <span class="material-icons">chat</span>
                </div>
              </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%);
  -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 {
  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;
}

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

.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 STYLES */
.shuttle-card-preview {
  width: 100%;
  aspect-ratio: 1.2;
  background-size: cover;
  background-position: center;
  border-radius: 24px;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-shadow: 0 30px 60px rgba(0,0,0,0.5);
}

.shuttle-card-preview::before {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.2) 60%, rgba(0,0,0,0.4) 100%);
}

.card-header, .route-display, .vehicle-tag, .card-details-box, .card-footer-preview {
  position: relative;
  z-index: 1;
}

.company-badge {
  background: rgba(254, 231, 21, 0.2);
  backdrop-filter: blur(8px);
  color: #fee715;
  padding: 6px 12px;
  border-radius: 8px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 0.8rem;
  font-weight: 800;
  border: 1px solid rgba(254, 231, 21, 0.3);
}

.price-badge-top {
  position: absolute;
  top: 0;
  right: 0;
  background: #fee715;
  color: #101820;
  padding: 8px 16px;
  border-radius: 12px;
  font-weight: 900;
  font-size: 1.1rem;
}

.route-display {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 1.5rem;
  font-weight: 900;
}

.route-display .arrow {
  color: #fee715;
}

.vehicle-tag {
  margin-top: 12px;
  background: rgba(0,0,0,0.6);
  padding: 8px 16px;
  border-radius: 12px;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  width: fit-content;
  font-weight: 700;
  font-size: 0.9rem;
}

.card-details-box {
  margin-top: auto;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-yellow { color: #fee715; font-size: 20px; }

.lang-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  background: rgba(254, 231, 21, 0.2);
  color: #fee715;
  padding: 2px 8px;
  border-radius: 6px;
  font-size: 0.6rem;
  font-weight: 800;
  margin-top: 4px;
  width: fit-content;
}

.lang-indicator .material-icons { font-size: 10px; }

.card-footer-preview {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  width: 100%;
}

.contact-actions {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.mini-contact-btn {
  width: 50px;
  height: 50px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.mini-contact-btn.phone { background: rgba(255,255,255,0.1); color: white; border: 1px solid rgba(255,255,255,0.2); }
.mini-contact-btn.wa { background: #25d366; color: white; box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3); }

.mini-contact-btn .material-icons { font-size: 24px; }

.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; }

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

.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>
