<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 Machines</h1>
          <p class="mb-5">
            Gérez vos machines industrielles par site et par type.
          </p>
        </div>
      </div>
    </div>

    <!-- Machines Management -->
    <div class="my-8">
      <!-- Header with Add Button -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">Machines</h2>
        <button @click="showAddMachineModal = 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 une machine
        </button>
      </div>

      <!-- Filters -->
      <div class="card bg-base-100 shadow-lg mb-6">
        <div class="card-body">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Site</span>
              </label>
              <select v-model="selectedSite" class="select select-bordered">
                <option value="">Tous les sites</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">
                  {{ site.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Type de machine</span>
              </label>
              <select v-model="selectedType" class="select select-bordered">
                <option value="">Tous les types</option>
                <option v-for="type in machineTypes" :key="type.id" :value="type.id">
                  {{ type.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Catégorie</span>
              </label>
              <select v-model="selectedCategory" class="select select-bordered">
                <option value="">Toutes les catégories</option>
                <option v-for="category in categories" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- Machines 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="filteredMachines.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="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>
          <h3 class="text-lg font-medium text-gray-900 mb-2">Aucune machine trouvée</h3>
          <p class="text-gray-500 mb-4">Commencez par ajouter votre première machine.</p>
          <button @click="showAddMachineModal = true" class="btn btn-primary">
            Ajouter une machine
          </button>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="machine in filteredMachines" 
          :key="machine.id"
          class="card bg-base-100 shadow-lg hover:shadow-xl transition-shadow cursor-pointer"
          @click="viewMachineDetails(machine)"
        >
          <div class="card-body">
            <div class="flex items-center justify-between mb-2">
              <h3 class="card-title text-lg">{{ machine.name }}</h3>
              <div class="badge badge-primary badge-sm">{{ machine.typeMachine?.category || 'N/A' }}</div>
            </div>
            
            <p class="text-sm text-gray-600 mb-3">{{ machine.description || machine.typeMachine?.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="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>
                <span class="text-gray-600">{{ machine.site?.name || 'Site inconnu' }}</span>
              </div>
              
              <div class="flex items-center gap-2">
                <svg class="w-4 h-4 text-green-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">{{ machine.typeMachine?.name || 'Type inconnu' }}</span>
              </div>
              
              <div v-if="machine.reference" class="flex items-center gap-2">
                <svg class="w-4 h-4 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                </svg>
                <span class="text-gray-600">{{ machine.reference }}</span>
              </div>
              
              <div v-if="machine.emplacement" class="flex items-center gap-2">
                <svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"></path>
                </svg>
                <span class="text-gray-600">{{ machine.emplacement }}</span>
              </div>
            </div>
            
            <div class="card-actions justify-end mt-4">
              <button class="btn btn-sm btn-outline" @click.stop="editMachine(machine)">
                Modifier
              </button>
              <button class="btn btn-sm btn-error" @click.stop="confirmDeleteMachine(machine)">
                Supprimer
              </button>
              <NuxtLink :to="`/machine/${machine.id}`" class="btn btn-sm btn-primary">
                Voir détails
              </NuxtLink>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Machine Modal -->
    <div v-if="showAddMachineModal" class="modal modal-open">
      <div class="modal-box max-w-2xl">
        <h3 class="font-bold text-lg mb-4">Ajouter une nouvelle machine</h3>
        <form @submit.prevent="handleCreateMachine">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Nom de la machine</span>
              </label>
              <input 
                v-model="newMachine.name" 
                type="text" 
                placeholder="Ex: Presse hydraulique #1" 
                class="input input-bordered" 
                required
              />
            </div>
            
            <div class="form-control">
              <label class="label">
                <span class="label-text">Site</span>
              </label>
              <select v-model="newMachine.siteId" class="select select-bordered" required>
                <option value="">Sélectionner un site</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">
                  {{ site.name }}
                </option>
              </select>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Type de machine</span>
              </label>
              <select v-model="newMachine.typeMachineId" class="select select-bordered" required>
                <option value="">Sélectionner un type</option>
                <option v-for="type in machineTypes" :key="type.id" :value="type.id">
                  {{ type.name }} ({{ type.category }})
                </option>
              </select>
            </div>

            <div class="form-control">
              <label class="label">
                <span class="label-text">Référence</span>
              </label>
              <input 
                v-model="newMachine.reference" 
                type="text" 
                placeholder="Ex: PRESS-001" 
                class="input input-bordered"
              />
            </div>
          </div>

          <div class="form-control mb-4">
            <label class="label">
              <span class="label-text">Emplacement</span>
            </label>
            <input 
              v-model="newMachine.emplacement" 
              type="text" 
              placeholder="Ex: Atelier A, Zone 1" 
              class="input input-bordered"
            />
          </div>

          <!-- Type Preview -->
          <div v-if="selectedMachineType" class="mb-4 p-4 bg-gray-50 rounded-lg">
            <h4 class="font-semibold text-sm mb-2">Structure du type sélectionné :</h4>
            <div class="text-xs space-y-1">
              <div class="flex items-center gap-2">
                <span class="font-medium">Composants :</span>
                <span class="badge badge-sm">{{ selectedMachineType.components?.length || 0 }}</span>
              </div>
              <div class="flex items-center gap-2">
                <span class="font-medium">Pièces critiques :</span>
                <span class="badge badge-sm">{{ selectedMachineType.criticalParts?.length || 0 }}</span>
              </div>
              <div class="flex items-center gap-2">
                <span class="font-medium">Catégorie :</span>
                <span class="badge badge-outline badge-sm">{{ selectedMachineType.category }}</span>
              </div>
            </div>
          </div>

          <div class="modal-action">
            <button type="button" @click="showAddMachineModal = false" class="btn btn-outline">
              Annuler
            </button>
            <button type="submit" class="btn btn-primary">
              Créer la machine
            </button>
          </div>
        </form>
      </div>
    </div>
  </main>
</template>

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

const { machines, loading, loadMachines, createMachineFromType, deleteMachine } = useMachines()
const { sites, loadSites } = useSites()
const { machineTypes, loadMachineTypes } = useMachineTypesApi()

// Data
const showAddMachineModal = ref(false)
const selectedSite = ref('')
const selectedType = ref('')
const selectedCategory = ref('')

const newMachine = reactive({
  name: '',
  siteId: '',
  typeMachineId: '',
  reference: '',
  emplacement: ''
})

// Computed
const selectedMachineType = computed(() => {
  if (!newMachine.typeMachineId) return null
  return machineTypes.value.find(type => type.id === newMachine.typeMachineId)
})

const categories = computed(() => {
  const cats = new Set()
  machineTypes.value.forEach(type => {
    if (type.category) cats.add(type.category)
  })
  return Array.from(cats)
})

const filteredMachines = computed(() => {
  let filtered = machines.value

  if (selectedSite.value) {
    filtered = filtered.filter(machine => machine.siteId === selectedSite.value)
  }

  if (selectedType.value) {
    filtered = filtered.filter(machine => machine.typeMachineId === selectedType.value)
  }

  if (selectedCategory.value) {
    filtered = filtered.filter(machine => machine.typeMachine?.category === selectedCategory.value)
  }

  return filtered
})

// Methods
const handleCreateMachine = async () => {
  if (!selectedMachineType.value) {
    console.error('Aucun type de machine sélectionné')
    return
  }

  const machineData = {
    name: newMachine.name,
    siteId: newMachine.siteId,
    reference: newMachine.reference,
    emplacement: newMachine.emplacement
  }

  const result = await createMachineFromType(machineData, selectedMachineType.value)
  
  if (result.success) {
    // Reset form
    newMachine.name = ''
    newMachine.siteId = ''
    newMachine.typeMachineId = ''
    newMachine.reference = ''
    newMachine.emplacement = ''
    showAddMachineModal.value = false
  }
}

const viewMachineDetails = (machine) => {
  // Naviguer vers la page de détails de la machine en mode lecture seule
  navigateTo(`/machine/${machine.id}`)
}

const editMachine = (machine) => {
  // Naviguer vers la page machine en mode édition
  navigateTo(`/machine/${machine.id}?edit=true`)
}

const confirmDeleteMachine = async (machine) => {
  const { showError, showSuccess } = useToast()
  
  if (confirm(`Êtes-vous sûr de vouloir supprimer la machine "${machine.name}" ? Cette action est irréversible.`)) {
    try {
      const result = await deleteMachine(machine.id)
      if (result.success) {
        showSuccess(`Machine "${machine.name}" supprimée 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 Promise.all([
    loadMachines(),
    loadSites(),
    loadMachineTypes()
  ])
  
  // Vérifier si on doit ouvrir automatiquement la modale d'ajout
  const route = useRoute()
  if (route.query.add === 'true') {
    showAddMachineModal.value = true
    // Nettoyer l'URL
    await navigateTo('/machines', { replace: true })
  }
})
</script> 