<template>
  <main class="container mx-auto px-6 py-8">

    <!-- Hierarchical View -->
    <div class="my-8">
      <!-- Header with Stats -->
      <div class="flex justify-between items-center mb-6">
        <div>
          <h2 class="text-2xl font-bold text-gray-800">Vue Hiérarchique</h2>
          <p class="text-gray-600">Machines organisées par site</p>
        </div>
        <div class="stats shadow">
          <div class="stat">
            <div class="stat-title">Sites</div>
            <div class="stat-value text-primary">{{ sites.length }}</div>
          </div>
          <div class="stat">
            <div class="stat-title">Machines</div>
            <div class="stat-value text-secondary">{{ totalMachines }}</div>
          </div>
        </div>
      </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">Rechercher</span>
              </label>
              <input 
                v-model="searchTerm" 
                type="text" 
                placeholder="Nom de machine ou site..." 
                class="input input-bordered"
              />
            </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>

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

      <!-- Hierarchical Machines View -->
      <div v-else-if="filteredSites.length === 0" class="text-center py-12">
        <div class="max-w-md mx-auto">
          <IconLucideFactory class="w-16 h-16 mx-auto text-gray-400 mb-4" aria-hidden="true" />
          <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 des sites et des machines.</p>
          <div class="flex gap-2 justify-center">
            <button @click="showAddSiteModal = true" class="btn btn-primary">
              Ajouter un site
            </button>
            <button @click="showAddMachineModal = true" class="btn btn-secondary">
              Ajouter une machine
            </button>
          </div>
        </div>
      </div>

      <div v-else class="space-y-6">
        <div 
          v-for="site in filteredSites" 
          :key="site.id"
          class="card bg-base-100 shadow-lg"
        >
          <!-- Site Header -->
          <div class="card-body">
            <div class="flex items-center justify-between mb-4">
              <div class="flex items-center gap-3">
                <div class="avatar placeholder">
                  <div class="bg-primary text-primary-content rounded-lg w-12 grid place-items-center">
                    <IconLucideMapPin class="w-6 h-6" aria-hidden="true" />
                  </div>
                </div>
                <div>
                  <h3 class="text-xl font-bold">{{ site.name }}</h3>
                  <div class="text-sm text-gray-600 space-y-1">
                    <div class="flex items-center gap-2">
                      <IconLucideUser class="w-4 h-4 text-primary" aria-hidden="true" />
                      <span class="font-medium">{{ site.contactName }}</span>
                    </div>
                    <div class="flex items-center gap-2">
                      <IconLucidePhone class="w-4 h-4 text-secondary" aria-hidden="true" />
                      <span>{{ site.contactPhone }}</span>
                    </div>
                    <div class="flex items-start gap-2">
                      <IconLucideMapPinned class="w-4 h-4 text-accent mt-1" aria-hidden="true" />
                      <span>
                        {{ site.contactAddress }}<br />
                        {{ site.contactPostalCode }} {{ site.contactCity }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="flex items-center gap-2">
                <div class="badge badge-primary badge-lg">{{ site.machines?.length || 0 }} machines</div>
                <button @click="toggleSiteCollapse(site.id)" class="btn btn-ghost btn-sm">
                  <IconLucideChevronDown
                    class="w-5 h-5 transition-transform"
                    :class="collapsedSites.includes(site.id) ? 'rotate-180' : ''"
                    aria-hidden="true"
                  />
                </button>
              </div>
            </div>

            <!-- Machines List -->
            <div v-if="!collapsedSites.includes(site.id) && site.machines && site.machines.length > 0" class="space-y-3">
              <div class="divider"></div>
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div 
                  v-for="machine in site.machines" 
                  :key="machine.id"
                  class="card bg-base-200 hover:bg-base-300 transition-colors cursor-pointer"
                  @click="viewMachineDetails(machine)"
                >
                  <div class="card-body p-4">
                    <div class="flex items-center justify-between mb-2">
                      <h4 class="font-semibold text-sm">{{ machine.name }}</h4>
                      <div class="badge badge-sm" :class="getCategoryBadgeClass(machine.typeMachine?.category)">
                        {{ machine.typeMachine?.category || 'N/A' }}
                      </div>
                    </div>
                    
                    <div class="space-y-1 text-xs text-gray-600">
                      <div class="flex items-center gap-1">
                        <IconLucideSettings2 class="w-3 h-3" aria-hidden="true" />
                        <span>{{ machine.typeMachine?.name || 'Type inconnu' }}</span>
                      </div>
                      
                      <div v-if="machine.reference" class="flex items-center gap-1">
                        <IconLucideTag class="w-3 h-3" aria-hidden="true" />
                        <span>{{ machine.reference }}</span>
                      </div>

                    </div>
                    
                    <div class="card-actions justify-end mt-3">
                      <button class="btn btn-xs btn-outline" @click.stop="editMachine(machine)">
                        Modifier
                      </button>
                      <button class="btn btn-xs btn-error" @click.stop="confirmDeleteMachine(machine)">
                        Supprimer
                      </button>
                      <NuxtLink :to="`/machine/${machine.id}`" class="btn btn-xs btn-primary">
                        Détails
                      </NuxtLink>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Empty Site State -->
            <div v-else-if="!collapsedSites.includes(site.id) && (!site.machines || site.machines.length === 0)" class="text-center py-6">
              <div class="text-gray-400 mb-2">
                <IconLucideFactory class="w-8 h-8 mx-auto" aria-hidden="true" />
              </div>
              <p class="text-sm text-gray-500 mb-3">Aucune machine dans ce site</p>
              <button @click="addMachineToSite(site)" class="btn btn-sm btn-primary">
                Ajouter une machine
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Site Modal -->
    <div v-if="showAddSiteModal" class="modal modal-open">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">Ajouter un nouveau site</h3>
        <form @submit.prevent="handleCreateSite" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Nom du site</span>
            </label>
            <input 
              v-model="newSite.name" 
              type="text" 
              placeholder="Ex: Usine de production" 
              class="input input-bordered" 
              required
            />
          </div>

          <SiteContactFormFields :form="newSite" />

          <div class="modal-action">
            <button type="button" @click="showAddSiteModal = false" class="btn btn-outline">
              Annuler
            </button>
            <button type="submit" class="btn btn-primary">
              Créer le site
            </button>
          </div>
        </form>
      </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>

          <!-- 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">Familles de composants :</span>
                <span class="badge badge-sm">{{ selectedMachineType.componentRequirements?.length || 0 }}</span>
              </div>
              <div class="flex items-center gap-2">
                <span class="font-medium">Groupes de pièces :</span>
                <span class="badge badge-sm">{{ selectedMachineType.pieceRequirements?.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 SiteContactFormFields from '~/components/sites/SiteContactFormFields.vue'
import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useMachines } from '~/composables/useMachines'
import { useToast } from '~/composables/useToast'
import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin'
import IconLucideUser from '~icons/lucide/user'
import IconLucidePhone from '~icons/lucide/phone'
import IconLucideMapPinned from '~icons/lucide/map-pinned'
import IconLucideChevronDown from '~icons/lucide/chevron-down'
import IconLucideSettings2 from '~icons/lucide/settings-2'
import IconLucideTag from '~icons/lucide/tag'


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

// Data
const showAddSiteModal = ref(false)
const showAddMachineModal = ref(false)
const searchTerm = ref('')
const selectedType = ref('')
const selectedCategory = ref('')
const collapsedSites = ref([])

const newSite = reactive({
  name: '',
  contactName: '',
  contactPhone: '',
  contactAddress: '',
  contactPostalCode: '',
  contactCity: ''
})

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

// 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 totalMachines = computed(() => {
  return sites.value.reduce((total, site) => {
    return total + (site.machines?.length || 0)
  }, 0)
})

const filteredSites = computed(() => {
  let filtered = sites.value

  // Filtrer par terme de recherche
  if (searchTerm.value) {
    filtered = filtered.filter(site => {
      const lowerTerm = searchTerm.value.toLowerCase()
      const siteMatches = [
        site.name,
        site.contactName,
        site.contactPhone,
        site.contactAddress,
        site.contactPostalCode,
        site.contactCity
      ].some(field => {
        if (!field) return false
        return field.toLowerCase().includes(lowerTerm)
      })
      
      const machineMatches = site.machines?.some(machine => 
        machine.name.toLowerCase().includes(lowerTerm) ||
        machine.reference?.toLowerCase().includes(lowerTerm)
      )
      
      return siteMatches || machineMatches
    })
  }

  // Filtrer par type de machine
  if (selectedType.value) {
    filtered = filtered.map(site => ({
      ...site,
      machines: site.machines?.filter(machine => machine.typeMachineId === selectedType.value) || []
    })).filter(site => site.machines.length > 0)
  }

  // Filtrer par catégorie
  if (selectedCategory.value) {
    filtered = filtered.map(site => ({
      ...site,
      machines: site.machines?.filter(machine => machine.typeMachine?.category === selectedCategory.value) || []
    })).filter(site => site.machines.length > 0)
  }

  return filtered
})

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

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
  }

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

const toggleSiteCollapse = (siteId) => {
  const index = collapsedSites.value.indexOf(siteId)
  if (index > -1) {
    collapsedSites.value.splice(index, 1)
  } else {
    collapsedSites.value.push(siteId)
  }
}

const viewMachineDetails = (machine) => {
  // Navigation vers la page de détails de la machine
  navigateTo(`/machine/${machine.id}`)
}

const editMachine = (machine) => {
  // Rediriger vers la page d'édition de la machine
  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}`)
    }
  }
}

const addMachineToSite = (site) => {
  newMachine.siteId = site.id
  showAddMachineModal.value = true
}

const getCategoryBadgeClass = (category) => {
  const classes = {
    'Production': 'badge-primary',
    'Transformation': 'badge-secondary',
    'Manutention': 'badge-accent',
    'Traitement': 'badge-info',
    'Contrôle': 'badge-warning'
  }
  return classes[category] || 'badge-neutral'
}

// Lifecycle
onMounted(async () => {
  await Promise.all([
    loadSites(),
    loadMachineTypes()
  ])
})
</script> 
