<template>
  <div
    v-if="isOpen"
    class="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
    @click.self="close"
  >
    <div class="bg-monokai-bg border-2 border-monokai-cyan rounded-lg w-[800px] max-h-[80vh] flex flex-col">
      <!-- Header -->
      <div class="p-4 border-b border-monokai-comment flex justify-between items-center">
        <h2 class="text-xl font-bold text-monokai-cyan">Paramètres</h2>
        <button
          @click="close"
          class="text-monokai-comment hover:text-monokai-text text-2xl leading-none"
        >
          ×
        </button>
      </div>

      <!-- Content -->
      <div class="flex-1 overflow-auto p-4 space-y-4">
        <!-- Boutons d'action -->
        <div class="flex gap-2">
          <button
            @click="reloadConfig"
            :disabled="loading"
            class="px-4 py-2 bg-monokai-green text-monokai-bg rounded hover:bg-monokai-cyan transition-colors disabled:opacity-50"
          >
            {{ loading ? 'Chargement...' : 'Recharger Config' }}
          </button>

          <label class="px-4 py-2 bg-monokai-cyan text-monokai-bg rounded hover:bg-monokai-green transition-colors cursor-pointer">
            <input
              type="file"
              accept=".xml"
              @change="importIpscan"
              class="hidden"
            />
            Importer IPScan XML
          </label>
        </div>

        <!-- Lien hardware bench -->
        <div class="border border-monokai-comment rounded p-3">
          <div class="text-sm font-bold text-monokai-cyan mb-2">Lien hardware bench</div>
          <div class="flex items-center gap-2">
            <input
              v-model="hardwareBenchUrl"
              type="url"
              class="flex-1 px-3 py-2 bg-monokai-bg border border-monokai-comment rounded text-monokai-text text-sm"
              placeholder="http://10.0.0.50:8087/devices.html"
            />
            <button
              @click="saveHardwareBenchUrl"
              :disabled="loading"
              class="px-3 py-2 bg-monokai-purple text-monokai-bg rounded hover:bg-monokai-pink transition-colors disabled:opacity-50"
            >
              Enregistrer
            </button>
          </div>
        </div>

        <!-- Base OUI -->
        <div class="border border-monokai-comment rounded p-3">
          <div class="text-sm font-bold text-monokai-cyan mb-2">Base OUI (fabricants)</div>
          <div class="flex items-center justify-between gap-2">
            <div class="text-xs text-monokai-comment">
              <span v-if="ouiStatus.exists">Dernière MAJ: {{ formatDate(ouiStatus.updated_at) }}</span>
              <span v-else>Aucune liste locale</span>
            </div>
            <button
              @click="updateOui"
              :disabled="loading"
              class="px-3 py-2 bg-monokai-green text-monokai-bg rounded hover:bg-monokai-cyan transition-colors disabled:opacity-50"
            >
              Mettre à jour
            </button>
          </div>
          <label class="flex items-center gap-2 mt-3 text-xs text-monokai-text">
            <input v-model="forceVendorUpdate" type="checkbox" class="form-checkbox" @change="saveForceVendor" />
            Forcer la mise à jour du fabricant lors des scans
          </label>
        </div>

        <!-- Architecture -->
        <div class="border border-monokai-comment rounded p-3">
          <div class="text-sm font-bold text-monokai-cyan mb-2">Architecture</div>
          <div class="flex items-center gap-2">
            <label class="text-xs text-monokai-comment w-40">Taille titres</label>
            <input
              v-model.number="architectureTitleFontSize"
              type="number"
              min="10"
              max="32"
              class="w-24 px-2 py-1 bg-monokai-bg border border-monokai-comment rounded text-monokai-text text-xs"
            />
            <button
              @click="saveArchitectureUi"
              :disabled="loading"
              class="px-3 py-2 bg-monokai-purple text-monokai-bg rounded hover:bg-monokai-pink transition-colors disabled:opacity-50"
            >
              Enregistrer
            </button>
          </div>
        </div>

        <!-- Messages -->
        <div v-if="message" :class="['p-3 rounded', messageClass]">
          {{ message }}
        </div>

        <!-- Contenu config.yaml -->
        <div>
          <h3 class="text-monokai-cyan font-bold mb-2">Fichier config.yaml</h3>
          <pre class="bg-monokai-bg border border-monokai-comment rounded p-4 text-sm text-monokai-text overflow-auto max-h-[400px] font-mono">{{ configContent }}</pre>
        </div>
      </div>

      <!-- Footer -->
      <div class="p-4 border-t border-monokai-comment flex justify-end">
        <button
          @click="close"
          class="px-4 py-2 bg-monokai-comment text-monokai-bg rounded hover:bg-monokai-text transition-colors"
        >
          Fermer
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'configReloaded'])

const configContent = ref('')
const hardwareBenchUrl = ref('')
const ouiStatus = ref({ exists: false, updated_at: null })
const forceVendorUpdate = ref(false)
const architectureTitleFontSize = ref(18)
const loading = ref(false)
const message = ref('')
const messageType = ref('info')

// Computed class pour le message
const messageClass = ref('')

watch(() => props.isOpen, async (newVal) => {
  if (newVal) {
    await loadConfigContent()
  }
})

async function loadConfigContent() {
  try {
    const [contentResponse, optionsResponse, ouiResponse, uiResponse] = await Promise.all([
      fetch('/api/ips/config/content'),
      fetch('/api/ips/config/options'),
      fetch('/api/ips/oui/status'),
      fetch('/api/config/ui')
    ])
    if (contentResponse.ok) {
      const data = await contentResponse.json()
      configContent.value = data.content
    } else {
      configContent.value = 'Erreur de chargement du fichier config.yaml'
    }

    if (optionsResponse.ok) {
      const options = await optionsResponse.json()
      hardwareBenchUrl.value = options.hardware_bench_url || ''
      forceVendorUpdate.value = Boolean(options.force_vendor_update)
    }

    if (ouiResponse.ok) {
      ouiStatus.value = await ouiResponse.json()
    }

    if (uiResponse.ok) {
      const uiData = await uiResponse.json()
      architectureTitleFontSize.value = Number(uiData.architecture_title_font_size || 18)
    }
  } catch (error) {
    console.error('Erreur chargement config:', error)
    configContent.value = 'Erreur de chargement du fichier config.yaml'
  }
}

async function updateOui() {
  loading.value = true
  message.value = ''

  try {
    const response = await fetch('/api/ips/oui/update', {
      method: 'POST'
    })
    if (response.ok) {
      const data = await response.json()
      message.value = `${data.message} (${data.updated_vendors} mises à jour)`
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      await loadConfigContent()
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors de la mise à jour'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur mise à jour OUI:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    setTimeout(() => {
      message.value = ''
    }, 5000)
  }
}

async function saveForceVendor() {
  loading.value = true
  message.value = ''

  try {
    const response = await fetch('/api/ips/config/force-vendor', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ enabled: forceVendorUpdate.value })
    })

    if (response.ok) {
      const data = await response.json()
      message.value = data.message
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      await loadConfigContent()
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors de la mise à jour'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur mise à jour force vendeur:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    setTimeout(() => {
      message.value = ''
    }, 5000)
  }
}

async function saveArchitectureUi() {
  loading.value = true
  message.value = ''

  try {
    const response = await fetch('/api/config/ui', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        architecture_title_font_size: architectureTitleFontSize.value
      })
    })

    if (response.ok) {
      const data = await response.json()
      message.value = data.message
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      document.documentElement.style.setProperty(
        '--arch-title-size',
        `${architectureTitleFontSize.value}px`
      )
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors de la mise à jour'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur mise à jour UI architecture:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    setTimeout(() => {
      message.value = ''
    }, 5000)
  }
}

function formatDate(value) {
  if (!value) return 'N/A'
  const date = new Date(value)
  return date.toLocaleString('fr-FR')
}

async function saveHardwareBenchUrl() {
  loading.value = true
  message.value = ''

  try {
    const response = await fetch('/api/ips/config/hardware-bench', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ url: hardwareBenchUrl.value })
    })

    if (response.ok) {
      const data = await response.json()
      message.value = data.message
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      emit('configReloaded')
      await loadConfigContent()
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors de la mise à jour'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur mise à jour lien hardware bench:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    setTimeout(() => {
      message.value = ''
    }, 5000)
  }
}

async function reloadConfig() {
  loading.value = true
  message.value = ''

  try {
    const response = await fetch('/api/ips/config/reload', {
      method: 'POST'
    })

    if (response.ok) {
      const data = await response.json()
      message.value = data.message
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      emit('configReloaded')

      // Recharger le contenu du config
      await loadConfigContent()
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors du rechargement'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur rechargement config:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    setTimeout(() => {
      message.value = ''
    }, 5000)
  }
}

async function importIpscan(event) {
  const file = event.target.files[0]
  if (!file) return

  loading.value = true
  message.value = ''

  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetch('/api/ips/import/ipscan', {
      method: 'POST',
      body: formData
    })

    if (response.ok) {
      const data = await response.json()
      message.value = `Import réussi: ${data.imported} nouvelles IPs, ${data.updated} mises à jour`
      if (data.errors && data.errors.length > 0) {
        message.value += `\nErreurs: ${data.errors.join(', ')}`
      }
      messageType.value = 'success'
      messageClass.value = 'bg-monokai-green/20 text-monokai-green border border-monokai-green'
      emit('configReloaded')  // Rafraîchir la liste des IPs
    } else {
      const error = await response.json()
      message.value = error.detail || 'Erreur lors de l\'import'
      messageType.value = 'error'
      messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
    }
  } catch (error) {
    console.error('Erreur import:', error)
    message.value = 'Erreur de connexion au serveur'
    messageType.value = 'error'
    messageClass.value = 'bg-monokai-pink/20 text-monokai-pink border border-monokai-pink'
  } finally {
    loading.value = false
    event.target.value = ''  // Reset input
    setTimeout(() => {
      message.value = ''
    }, 8000)
  }
}

function close() {
  emit('close')
}
</script>
