<template>
  <!-- Floating Button -->
  <div class="fixed bottom-6 right-6 z-40">
    <button
      @click="showTicketModal = true"
      class="bg-primary-600 hover:bg-primary-700 text-white rounded-full p-4 shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-110"
      title="Signaler un problème ou une amélioration"
    >
      <Ticket class="w-6 h-6" />
    </button>
  </div>

  <!-- Ticket Modal -->
  <transition
    enter-active-class="transition ease-out duration-200"
    enter-from-class="opacity-0"
    enter-to-class="opacity-100"
    leave-active-class="transition ease-in duration-150"
    leave-from-class="opacity-100"
    leave-to-class="opacity-0"
  >
    <div
      v-if="showTicketModal"
      class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
    >
      <div class="bg-white rounded-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-xl font-semibold">Nouveau ticket</h2>
          <button
            @click="closeModal"
            class="text-gray-400 hover:text-gray-600"
          >
            <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <form @submit.prevent="submitTicket" class="space-y-6">
          <!-- Title -->
          <div>
            <label class="label">Titre *</label>
            <input
              v-model="ticketForm.title"
              type="text"
              class="input"
              required
              maxlength="200"
              placeholder="Titre de votre ticket"
            >
          </div>
          
          <!-- Type -->
          <div>
            <label class="label">Type</label>
            <select v-model="ticketForm.ticket_type" class="input">
              <option value="bug">🐛 Bug</option>
              <option value="feature_request">💡 Demande de fonctionnalité</option>
              <option value="improvement">✨ Amélioration</option>
              <option value="support">❓ Support</option>
              <option value="other">📝 Autre</option>
            </select>
          </div>
          
          <!-- Priority -->
          <div>
            <label class="label">Priorité</label>
            <select v-model="ticketForm.priority" class="input">
              <option value="low">🟢 Faible</option>
              <option value="medium">🟡 Moyenne</option>
              <option value="high">🟠 Élevée</option>
              <option value="urgent">🔴 Urgente</option>
            </select>
          </div>
          
          <!-- Description -->
          <div>
            <label class="label">Description *</label>
            <textarea
              v-model="ticketForm.description"
              class="input resize-none"
              rows="6"
              required
              placeholder="Décrivez votre problème ou votre demande en détail..."
            ></textarea>
          </div>
          
          <!-- Screenshot -->
          <div>
            <label class="label">Screenshot (optionnel)</label>
            <input
              ref="screenshotInput"
              type="file"
              accept="image/*"
              class="input"
              @change="handleScreenshotChange"
            >
            <div class="mt-1 text-sm text-gray-600">
              Formats acceptés : JPG, PNG, GIF, WebP (max 5MB)
            </div>
          </div>
          
          <!-- Actions -->
          <div class="flex gap-3 pt-4">
            <button
              type="button"
              @click="closeModal"
              class="flex-1 btn-secondary"
            >
              Annuler
            </button>
            <button
              type="submit"
              class="flex-1 btn-primary"
              :disabled="submitting"
            >
              <LoadingLogo v-if="submitting" variant="spinner" size="small" :showText="false" />
              {{ submitting ? 'Envoi...' : 'Envoyer le ticket' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useToast } from 'vue-toastification'
import { useRouter } from 'vue-router'
import axios from '@/utils/axios'
import { useAuthStore } from '@/stores/auth'
import { Plus, X, Send, Ticket } from 'lucide-vue-next'
import LoadingLogo from '@/components/LoadingLogo.vue'

const toast = useToast()
const router = useRouter()

// State
const showTicketModal = ref(false)
const submitting = ref(false)
const screenshotInput = ref(null)

const ticketForm = ref({
  title: '',
  description: '',
  ticket_type: 'other',
  priority: 'medium'
})

// Methods
function closeModal() {
  showTicketModal.value = false
  resetForm()
}

function resetForm() {
  ticketForm.value = {
    title: '',
    description: '',
    ticket_type: 'other',
    priority: 'medium'
  }
  if (screenshotInput.value) {
    screenshotInput.value.value = ''
  }
}

function handleScreenshotChange(event) {
  const file = event.target.files[0]
  if (file && file.size > 5 * 1024 * 1024) {
    toast.error('Le fichier est trop volumineux (max 5MB)')
    event.target.value = ''
  }
}

async function submitTicket() {
  submitting.value = true
  try {
    const formData = new FormData()
    formData.append('title', ticketForm.value.title)
    formData.append('description', ticketForm.value.description)
    formData.append('ticket_type', ticketForm.value.ticket_type)
    formData.append('priority', ticketForm.value.priority)
    
    if (screenshotInput.value && screenshotInput.value.files[0]) {
      formData.append('screenshot', screenshotInput.value.files[0])
    }
    
    // Debug: afficher les données envoyées
    console.log('DEBUG - Ticket form data:')
    console.log('  title:', ticketForm.value.title)
    console.log('  description:', ticketForm.value.description)
    console.log('  ticket_type:', ticketForm.value.ticket_type)
    console.log('  priority:', ticketForm.value.priority)
    console.log('  screenshot:', screenshotInput.value?.files[0])
    
    // Debug: afficher le FormData
    for (let [key, value] of formData.entries()) {
      console.log(`DEBUG - FormData entry: ${key} = ${value}`)
    }
    
    await axios.post('/api/tickets/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    })
    toast.success('Ticket envoyé avec succès !')
    closeModal()
    
    // Redirect to MyTickets page
    router.push('/my-tickets')
  } catch (error) {
    console.error('Error submitting ticket:', error)
    if (error.response) {
      console.error('Error response:', error.response.data)
      console.error('Error status:', error.response.status)
    }
    toast.error('Erreur lors de l\'envoi du ticket')
  } finally {
    submitting.value = false
  }
}
</script>
