<template>
  <div class="p-4 max-w-4xl mx-auto">
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-bold text-green">📷 Bibliothèque</h1>
      <button @click="showIdentify = true"
        class="bg-green text-bg px-4 py-2 rounded-lg text-sm font-semibold hover:opacity-90">
        Identifier une plante
      </button>
    </div>

    <!-- Filtres -->
    <div class="flex gap-2 mb-4 flex-wrap">
      <button v-for="f in filters" :key="f.val" @click="activeFilter = f.val"
        :class="['px-3 py-1 rounded-full text-xs font-medium transition-colors',
          activeFilter === f.val ? 'bg-green text-bg' : 'bg-bg-soft text-text-muted hover:text-text']">
        {{ f.label }}
      </button>
    </div>

    <!-- Grille -->
    <div v-if="loading" class="text-text-muted text-sm">Chargement...</div>
    <div v-else-if="!filtered.length" class="text-text-muted text-sm py-4">Aucune photo.</div>
    <div v-else class="grid grid-cols-3 md:grid-cols-4 gap-2">
      <div v-for="m in filtered" :key="m.id"
        class="aspect-square rounded-lg overflow-hidden bg-bg-hard relative group cursor-pointer"
        @click="openLightbox(m)">
        <img :src="m.thumbnail_url || m.url" :alt="m.titre || ''" class="w-full h-full object-cover" />
        <div v-if="m.identified_common"
          class="absolute bottom-0 left-0 right-0 bg-black/70 text-xs text-green px-1 py-0.5 truncate">
          {{ m.identified_common }}
        </div>
        <div class="absolute top-1 left-1 bg-black/60 text-text-muted text-xs px-1 rounded">
          {{ labelFor(m.entity_type) }}
        </div>
        <button @click.stop="deleteMedia(m)"
          class="hidden group-hover:flex absolute top-1 right-1 bg-red/80 text-white text-xs rounded px-1">✕</button>
      </div>
    </div>

    <!-- Lightbox -->
    <div v-if="lightbox" class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4" @click.self="lightbox = null">
      <div class="max-w-lg w-full bg-bg-hard rounded-xl overflow-hidden border border-bg-soft">
        <img :src="lightbox.url" class="w-full" />
        <div class="p-4">
          <!-- Infos identification -->
          <div v-if="lightbox.identified_species" class="text-center mb-3">
            <div class="text-green font-semibold text-base">{{ lightbox.identified_common }}</div>
            <div class="italic text-text-muted text-sm">{{ lightbox.identified_species }}</div>
            <div class="text-xs text-text-muted mt-1">
              Confiance : {{ Math.round((lightbox.identified_confidence || 0) * 100) }}% — via {{ lightbox.identified_source }}
            </div>
          </div>
          <!-- Lien actuel -->
          <div class="text-xs text-text-muted mb-3 text-center">
            {{ labelFor(lightbox.entity_type) }}
            <span v-if="lightbox.entity_type === 'plante' && plantName(lightbox.entity_id)">
              : <span class="text-green font-medium">{{ plantName(lightbox.entity_id) }}</span>
            </span>
          </div>
          <!-- Actions -->
          <div class="flex gap-2 flex-wrap">
            <button @click="startLink(lightbox!)"
              class="flex-1 bg-blue/20 text-blue hover:bg-blue/30 px-3 py-2 rounded-lg text-xs font-medium transition-colors">
              🔗 Associer à une plante
            </button>
            <button @click="deleteMedia(lightbox!); lightbox = null"
              class="bg-red/20 text-red hover:bg-red/30 px-3 py-2 rounded-lg text-xs font-medium transition-colors">
              🗑 Supprimer
            </button>
          </div>
          <button class="mt-3 w-full text-text-muted hover:text-text text-sm" @click="lightbox = null">Fermer</button>
        </div>
      </div>
    </div>

    <!-- Modal associer à une plante -->
    <div v-if="linkMedia" class="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4" @click.self="linkMedia = null">
      <div class="bg-bg-hard rounded-xl p-6 w-full max-w-sm border border-bg-soft">
        <h3 class="text-text font-bold mb-4">Associer à une plante</h3>
        <select v-model="linkPlantId"
          class="bg-bg border border-bg-soft rounded-lg px-3 py-2 text-text text-sm w-full outline-none focus:border-green mb-4">
          <option :value="null">-- Choisir une plante --</option>
          <option v-for="p in plantsStore.plants" :key="p.id" :value="p.id">
            {{ p.nom_commun }}{{ p.variete ? ' — ' + p.variete : '' }}
          </option>
        </select>
        <div class="flex gap-2 justify-end">
          <button @click="linkMedia = null" class="px-4 py-2 text-text-muted hover:text-text text-sm">Annuler</button>
          <button @click="confirmLink" :disabled="!linkPlantId"
            class="bg-green text-bg px-4 py-2 rounded-lg text-sm font-semibold hover:opacity-90 disabled:opacity-40">
            Associer
          </button>
        </div>
      </div>
    </div>

    <!-- Modal identification -->
    <PhotoIdentifyModal v-if="showIdentify" @close="showIdentify = false" @identified="onIdentified" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import axios from 'axios'
import PhotoIdentifyModal from '@/components/PhotoIdentifyModal.vue'
import { usePlantsStore } from '@/stores/plants'

interface Media {
  id: number; entity_type: string; entity_id: number
  url: string; thumbnail_url?: string; titre?: string
  identified_species?: string; identified_common?: string
  identified_confidence?: number; identified_source?: string
}

const medias = ref<Media[]>([])
const loading = ref(false)
const lightbox = ref<Media | null>(null)
const showIdentify = ref(false)
const activeFilter = ref('')
const linkMedia = ref<Media | null>(null)
const linkPlantId = ref<number | null>(null)

const plantsStore = usePlantsStore()

const filters = [
  { val: '', label: 'Toutes' },
  { val: 'plante', label: '🌱 Plantes' },
  { val: 'jardin', label: '🏡 Jardins' },
  { val: 'plantation', label: '🥕 Plantations' },
  { val: 'outil', label: '🔧 Outils' },
  { val: 'bibliotheque', label: '📷 Sans lien' },
]

const filtered = computed(() =>
  activeFilter.value ? medias.value.filter(m => m.entity_type === activeFilter.value) : medias.value
)

function labelFor(type: string) {
  const map: Record<string, string> = {
    plante: '🌱 Plante', jardin: '🏡 Jardin',
    plantation: '🥕 Plantation', outil: '🔧 Outil', bibliotheque: '📷'
  }
  return map[type] ?? '📷'
}

function plantName(id: number) {
  return plantsStore.plants.find(p => p.id === id)?.nom_commun ?? ''
}

function openLightbox(m: Media) { lightbox.value = m }

function startLink(m: Media) {
  linkMedia.value = m
  linkPlantId.value = m.entity_type === 'plante' ? m.entity_id : null
}

async function confirmLink() {
  if (!linkMedia.value || !linkPlantId.value) return
  await axios.patch(`/api/media/${linkMedia.value.id}`, {
    entity_type: 'plante', entity_id: linkPlantId.value,
  })
  const m = medias.value.find(x => x.id === linkMedia.value!.id)
  if (m) { m.entity_type = 'plante'; m.entity_id = linkPlantId.value! }
  if (lightbox.value?.id === linkMedia.value.id) {
    lightbox.value = { ...lightbox.value, entity_type: 'plante', entity_id: linkPlantId.value! }
  }
  linkMedia.value = null
  linkPlantId.value = null
}

async function deleteMedia(m: Media) {
  if (!confirm('Supprimer cette photo ?')) return
  await axios.delete(`/api/media/${m.id}`)
  medias.value = medias.value.filter(x => x.id !== m.id)
  if (lightbox.value?.id === m.id) lightbox.value = null
}

async function fetchAll() {
  loading.value = true
  try {
    const { data } = await axios.get<Media[]>('/api/media/all')
    medias.value = data
  } finally {
    loading.value = false
  }
}

function onIdentified() { fetchAll() }

onMounted(() => {
  fetchAll()
  plantsStore.fetchAll()
})
</script>
