<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 d'ensemble
          </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">Site</span>
              </label>
              <select v-model="selectedSiteFilter" 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>
        </div>
      </div>

      <!-- Loading State -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <span class="loading loading-spinner loading-lg" />
      </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 v-if="canEdit" class="btn btn-primary" @click="showAddSiteModal = true">
              Ajouter un site
            </button>
            <button
              v-if="canEdit"
              class="btn btn-secondary"
              @click="showAddMachineModal = true"
            >
              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>{{ formatPhoneDisplay(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
                  class="btn btn-ghost btn-sm"
                  @click="toggleSiteCollapse(site.id)"
                >
                  <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 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>

                    <div class="space-y-1 text-xs text-gray-600">
                      <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
                        v-if="canEdit"
                        class="btn btn-xs btn-outline"
                        @click.stop="editMachine(machine)"
                      >
                        Modifier
                      </button>
                      <button
                        v-if="canEdit"
                        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
                v-if="canEdit"
                class="btn btn-sm btn-primary"
                @click="addMachineToSite(site)"
              >
                Ajouter une machine
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Site Modal -->
    <HomeAddSiteModal
      :open="showAddSiteModal"
      :disabled="!canEdit"
      @close="showAddSiteModal = false"
      @create="handleCreateSite"
    />

    <!-- Add Machine Modal -->
    <HomeAddMachineModal
      :open="showAddMachineModal"
      :sites="sites"
      :disabled="!canEdit"
      :preselected-site-id="preselectedSiteId"
      @close="showAddMachineModal = false"
      @create="handleCreateMachine"
    />
  </main>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useSites } from '~/composables/useSites'
import { useMachines } from '~/composables/useMachines'
import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
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 IconLucideTag from '~icons/lucide/tag'
import { formatPhone } from '~/utils/formatters/phone'
import { extractRelationId } from '~/shared/apiRelations'

const { canEdit } = usePermissions()
const { sites, loading, loadSites, createSite } = useSites()
const { machines, loadMachines, createMachine, deleteMachine } = useMachines()

// Data
const showAddSiteModal = ref(false)
const showAddMachineModal = ref(false)
const searchTerm = ref('')
const selectedSiteFilter = ref('')
const collapsedSites = ref([])
const preselectedSiteId = ref('')

// Computed
const machinesBySiteId = computed(() => {
  const map = new Map()

  machines.value.forEach((machine) => {
    const siteId = machine.siteId || extractRelationId(machine.site)
    if (!siteId) { return }

    if (!map.has(siteId)) {
      map.set(siteId, [])
    }

    map.get(siteId).push(machine)
  })

  return map
})

const sitesWithMachines = computed(() => {
  return sites.value.map((site) => ({
    ...site,
    machines: machinesBySiteId.value.get(site.id) || []
  }))
})

const totalMachines = computed(() => {
  return sitesWithMachines.value.reduce((total, site) => {
    return total + (site.machines?.length || 0)
  }, 0)
})

const formatPhoneDisplay = (value) => {
  const formatted = formatPhone(value)
  if (formatted) {
    return formatted
  }
  return value || '—'
}

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

  // Filtrer par site
  if (selectedSiteFilter.value) {
    filtered = filtered.filter(site => site.id === selectedSiteFilter.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 => {
          const name = (machine.name || '').toLowerCase()
          const reference = (machine.reference || '').toLowerCase()
          return name.includes(lowerTerm) || reference.includes(lowerTerm)
        }
      )

      return siteMatches || machineMatches
    })
  }

  return filtered
})

// Methods
const handleCreateSite = async (data) => {
  const result = await createSite(data)
  if (result.success) {
    showAddSiteModal.value = false
  }
}

const handleCreateMachine = async (data) => {
  const result = await createMachine(data)

  if (result.success) {
    showAddMachineModal.value = false
    await loadMachines()
  }
}

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 { confirm: confirmDialog } = useConfirm()

const confirmDeleteMachine = async (machine) => {
  const { showError, showSuccess } = useToast()

  if (
    await confirmDialog({
      message: `Ê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`)
        await loadMachines()
      } else {
        showError(`Impossible de supprimer la machine : ${result.error}`)
      }
    } catch (error) {
      showError(`Impossible de supprimer la machine : ${humanizeError(error.message)}`)
    }
  }
}

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

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