<template>
  <main class="container mx-auto px-6 py-8">
    <!-- Hero Section -->
    <div class="hero min-h-[30vh] bg-gradient-to-r from-primary to-secondary">
      <div class="hero-content text-center text-neutral-content">
        <div class="max-w-md">
          <h1 class="mb-5 text-4xl font-bold">Gestion des Sites</h1>
          <p class="mb-5">
            Gérez vos sites industriels et leurs emplacements.
          </p>
        </div>
      </div>
    </div>

    <!-- Sites Management -->
    <div class="my-8">
      <!-- Header with Add Button -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">Sites</h2>
        <button @click="showAddSiteModal = true" class="btn btn-primary">
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
          </svg>
          Ajouter un site
        </button>
      </div>

      <!-- Sites Grid -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <span class="loading loading-spinner loading-lg"></span>
      </div>

      <div v-else-if="sites.length === 0" class="text-center py-12">
        <div class="max-w-md mx-auto">
          <svg class="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
          </svg>
          <h3 class="text-lg font-medium text-gray-900 mb-2">Aucun site trouvé</h3>
          <p class="text-gray-500 mb-4">Commencez par ajouter votre premier site.</p>
          <button @click="showAddSiteModal = true" class="btn btn-primary">
            Ajouter un site
          </button>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="site in sites" 
          :key="site.id"
          class="card bg-base-100 shadow-lg hover:shadow-xl transition-shadow"
        >
          <div class="card-body">
            <div class="flex items-center justify-between mb-4">
              <h3 class="card-title text-lg">{{ site.name }}</h3>
              <div class="badge badge-primary badge-sm">{{ site.machines?.length || 0 }} machines</div>
            </div>
            
            <p v-if="site.description" class="text-sm text-gray-600 mb-3">{{ site.description }}</p>
            
            <div class="space-y-2 text-sm">
              <div class="flex items-center gap-2">
                <svg class="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path>
                </svg>
                <span class="text-gray-600">{{ site.machines?.length || 0 }} machine(s)</span>
              </div>
            </div>
            
            <div class="card-actions justify-end mt-4">
              <button class="btn btn-sm btn-outline" @click="editSite(site)">
                Modifier
              </button>
              <button class="btn btn-sm btn-error" @click="confirmDeleteSite(site)">
                Supprimer
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Site Modal -->
    <div v-if="showAddSiteModal" class="modal modal-open">
      <div class="modal-box max-w-md">
        <h3 class="font-bold text-lg mb-4">Ajouter un nouveau site</h3>
        <form @submit.prevent="handleCreateSite">
          <div class="form-control mb-4">
            <label class="label">
              <span class="label-text">Nom du site</span>
            </label>
            <input 
              v-model="newSite.name" 
              type="text" 
              placeholder="Ex: Usine principale" 
              class="input input-bordered" 
              required
            />
          </div>
          
          <div class="form-control mb-4">
            <label class="label">
              <span class="label-text">Description (optionnel)</span>
            </label>
            <textarea 
              v-model="newSite.description" 
              placeholder="Description du site..." 
              class="textarea textarea-bordered"
              rows="3"
            ></textarea>
          </div>

          <div class="modal-action">
            <button type="button" class="btn" @click="showAddSiteModal = false">
              Annuler
            </button>
            <button type="submit" class="btn btn-primary">
              Créer le site
            </button>
          </div>
        </form>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useSites } from '~/composables/useSites'
import { useToast } from '~/composables/useToast'

const { sites, loading, loadSites, createSite, updateSite, deleteSite } = useSites()

// Data
const showAddSiteModal = ref(false)

const newSite = reactive({
  name: '',
  description: ''
})

// Methods
const handleCreateSite = async () => {
  const result = await createSite({
    name: newSite.name,
    description: newSite.description
  })
  
  if (result.success) {
    // Reset form
    newSite.name = ''
    newSite.description = ''
    showAddSiteModal.value = false
  }
}

const editSite = (site) => {
  // TODO: Ouvrir le modal d'édition
  console.log('Modifier le site:', site)
}

const confirmDeleteSite = async (site) => {
  const { showError, showSuccess } = useToast()
  
  if (confirm(`Êtes-vous sûr de vouloir supprimer le site "${site.name}" ? Cette action est irréversible.`)) {
    try {
      const result = await deleteSite(site.id)
      if (result.success) {
        showSuccess(`Site "${site.name}" supprimé avec succès`)
      } else {
        showError(`Erreur lors de la suppression: ${result.error}`)
      }
    } catch (error) {
      showError(`Erreur lors de la suppression: ${error.message}`)
    }
  }
}

// Lifecycle
onMounted(async () => {
  await loadSites()
  
  // Vérifier si on doit ouvrir automatiquement la modale d'ajout
  const route = useRoute()
  if (route.query.add === 'true') {
    showAddSiteModal.value = true
    // Nettoyer l'URL
    await navigateTo('/sites', { replace: true })
  }
})
</script> 