<template>
  <div class="modal-overlay" @click.self="$emit('close')">
    <div class="modal">

      <!-- Header -->
      <div class="modal-header">
        <div class="header-title">
          <span class="header-icon">🔍</span>
          <h2>{{ t('autoDiscovery') }}</h2>
        </div>
        <button class="close-btn" @click="$emit('close')">✕</button>
      </div>

      <!-- ── Step 1 : Configuration ── -->
      <template v-if="step === 'config'">
        <div class="modal-body">

          <div class="field">
            <label>{{ t('dnsServer') }}</label>
            <div class="input-hint">{{ t('dnsHint') }}</div>
            <input v-model="dnsServer" type="text" placeholder="192.168.1.16" />
          </div>

          <div class="field">
            <label>{{ t('vlansToScan') }}</label>
            <div class="input-hint">{{ t('vlansHint') }}</div>

            <div v-if="scanableVlans.length === 0" class="warn-box">
              {{ t('noCidrWarning') }}
            </div>

            <div class="vlan-checklist">
              <label
                v-for="vlan in props.vlans"
                :key="vlan.id"
                class="vlan-check"
                :class="{ disabled: !vlan.cidr }"
              >
                <input
                  type="checkbox"
                  :value="vlan.id"
                  v-model="selectedVlanIds"
                  :disabled="!vlan.cidr"
                />
                <div class="vlan-check-body">
                  <span class="vlan-badge" :style="{ background: vlan.color }">VLAN {{ vlan.vlan_id }}</span>
                  <span class="vlan-check-name">{{ vlan.name }}</span>
                  <code v-if="vlan.cidr" class="vlan-check-cidr">{{ vlan.cidr }}</code>
                  <span v-else class="no-cidr">{{ t('noCidr') }}</span>
                  <span v-if="vlan.cidr" class="host-count">
                    (~{{ hostCount(vlan.cidr) }} hôtes)
                  </span>
                </div>
              </label>
            </div>
          </div>

          <div class="field field-toggle">
            <label class="toggle-row">
              <input type="checkbox" v-model="tcpCheck" class="toggle-checkbox" />
              <span class="toggle-label">{{ t('tcpCheckLabel') }}</span>
            </label>
            <div class="input-hint">{{ t('tcpCheckHint') }}</div>
          </div>

          <div v-if="configError" class="error-box">{{ configError }}</div>
        </div>

        <div class="modal-footer">
          <button class="btn-secondary" @click="$emit('close')">{{ t('cancel') }}</button>
          <button
            class="btn-primary"
            :disabled="selectedVlanIds.length === 0"
            @click="startScan"
          >
            {{ t('startDiscovery') }}
          </button>
        </div>
      </template>

      <!-- ── Step 2 : Scan en cours ── -->
      <template v-if="step === 'scanning'">
        <div class="modal-body scanning-body">
          <div class="spinner"></div>
          <p class="scan-msg">{{ t('scanning') }}</p>
          <p class="scan-detail">
            {{ totalToScan }} {{ t('scanAddresses') }} {{ selectedVlanIds.length }} {{ t('scanVlans') }}
          </p>
          <p class="scan-note">{{ t('scanNote') }}</p>
        </div>
      </template>

      <!-- ── Step 3 : Résultats ── -->
      <template v-if="step === 'results'">
        <div class="modal-body">

          <div class="results-summary">
            <span class="summary-found">{{ results.length }} {{ t('hostsFound') }}</span>
            <span class="summary-meta">
              {{ t('scanAddresses') }} {{ scanMeta.total_scanned }} {{ t('addressesScanned') }}
              — {{ scanMeta.duration_s }}s
            </span>
            <span v-if="newCount > 0" class="summary-new">{{ newCount }} {{ t('newHosts') }}</span>
          </div>

          <div v-if="results.length === 0" class="empty-results">
            {{ t('noHosts') }}
          </div>

          <div v-else class="results-table-wrap">
            <table class="results-table">
              <thead>
                <tr>
                  <th>
                    <input type="checkbox" @change="toggleAll" :checked="allNewSelected" />
                  </th>
                  <th>{{ t('colIp') }}</th>
                  <th>{{ t('colDns') }}</th>
                  <th>VLAN</th>
                  <th>{{ t('colStatus') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="host in results"
                  :key="host.ip"
                  :class="{ 'row-existing': isExisting(host.ip) }"
                >
                  <td>
                    <input
                      type="checkbox"
                      :value="host.ip"
                      v-model="selectedIps"
                      :disabled="isExisting(host.ip)"
                    />
                  </td>
                  <td><code class="ip">{{ host.ip }}</code></td>
                  <td class="hostname">
                    <span v-if="host.hostname">{{ shortHostname(host.hostname) }}</span>
                    <span v-else class="no-dns">—</span>
                  </td>
                  <td>
                    <span class="vlan-badge sm" :style="{ background: vlanColor(host.vlan_id) }">
                      VLAN {{ vlanNum(host.vlan_id) }}
                    </span>
                  </td>
                  <td>
                    <span v-if="isExisting(host.ip)" class="status existing">{{ t('statusExisting') }}</span>
                    <span v-else class="status new">{{ t('statusNew') }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="importError" class="error-box">{{ importError }}</div>
        </div>

        <div class="modal-footer">
          <button class="btn-secondary" @click="step = 'config'">{{ t('newScan') }}</button>
          <button
            class="btn-primary"
            :disabled="selectedIps.length === 0 || importing"
            @click="doImport"
          >
            {{ importing ? t('importingBtn') : `${t('importBtn')} (${selectedIps.length})` }}
          </button>
        </div>
      </template>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { devicesApi, discoveryApi } from '../api.js'
import { t } from '../i18n.js'

const props = defineProps({
  vlans:   { type: Array, default: () => [] },
  devices: { type: Array, default: () => [] },
})
const emit = defineEmits(['close', 'refresh'])

const step           = ref('config')
const dnsServer      = ref('')
const tcpCheck       = ref(false)
const selectedVlanIds = ref([])
const results        = ref([])
const selectedIps    = ref([])
const scanMeta       = ref({ total_scanned: 0, duration_s: 0 })
const configError    = ref('')
const importError    = ref('')
const importing      = ref(false)

onMounted(async () => {
  try {
    const resp = await discoveryApi.config()
    dnsServer.value = resp.data.dns_server || ''
  } catch { /* ignore — field stays empty */ }
})

const scanableVlans = computed(() => props.vlans.filter(v => v.cidr))

const existingIps = computed(() => {
  const ips = new Set()
  for (const d of props.devices)
    for (const i of d.interfaces)
      if (i.ip_address) ips.add(i.ip_address.trim())
  return ips
})

const totalToScan = computed(() => {
  let n = 0
  for (const id of selectedVlanIds.value) {
    const vlan = props.vlans.find(v => v.id === id)
    if (vlan?.cidr) n += hostCount(vlan.cidr)
  }
  return n
})

const newCount = computed(() =>
  results.value.filter(h => !isExisting(h.ip)).length
)

const allNewSelected = computed(() => {
  const newHosts = results.value.filter(h => !isExisting(h.ip))
  return newHosts.length > 0 && newHosts.every(h => selectedIps.value.includes(h.ip))
})

function hostCount(cidr) {
  try {
    const parts = cidr.split('/')
    const prefix = parseInt(parts[1])
    if (prefix >= 31) return 0
    return Math.pow(2, 32 - prefix) - 2
  } catch { return 0 }
}

function isExisting(ip) { return existingIps.value.has(ip) }
function vlanColor(vlanId) { return props.vlans.find(v => v.id === vlanId)?.color || '#94A3B8' }
function vlanNum(vlanId) { return props.vlans.find(v => v.id === vlanId)?.vlan_id || '?' }
function shortHostname(fqdn) { return fqdn.split('.')[0] }

function toggleAll(e) {
  if (e.target.checked) {
    selectedIps.value = results.value.filter(h => !isExisting(h.ip)).map(h => h.ip)
  } else {
    selectedIps.value = []
  }
}

async function startScan() {
  configError.value = ''
  if (selectedVlanIds.value.length === 0) {
    configError.value = t('selectVlan')
    return
  }

  const targets = selectedVlanIds.value.map(id => {
    const vlan = props.vlans.find(v => v.id === id)
    return { vlan_id: id, cidr: vlan.cidr }
  })

  step.value = 'scanning'
  results.value = []
  selectedIps.value = []

  try {
    const resp = await discoveryApi.scan({
      dns_server: dnsServer.value.trim(),
      targets,
      tcp_check: tcpCheck.value,
    })
    results.value = resp.data.hosts
    scanMeta.value = { total_scanned: resp.data.total_scanned, duration_s: resp.data.duration_s }
    selectedIps.value = results.value.filter(h => !isExisting(h.ip)).map(h => h.ip)
    step.value = 'results'
  } catch (e) {
    configError.value = e.response?.data?.detail || t('scanError')
    step.value = 'config'
  }
}

async function doImport() {
  importing.value = true
  importError.value = ''
  const toImport = results.value.filter(h => selectedIps.value.includes(h.ip) && !isExisting(h.ip))

  try {
    for (const host of toImport) {
      const name = host.hostname ? shortHostname(host.hostname) : host.ip
      await devicesApi.create({
        name,
        type: 'server',
        description: host.hostname || '',
        is_gateway: false,
        is_livebox: false,
        interfaces: [{
          name: 'eth0',
          ip_address: host.ip,
          vlan_id: host.vlan_id,
          is_upstream: false,
        }],
      })
    }
    emit('refresh')
    emit('close')
  } catch (e) {
    importError.value = e.response?.data?.detail || t('importError')
  } finally {
    importing.value = false
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed; inset: 0;
  background: var(--modal-overlay);
  display: flex; align-items: center; justify-content: center;
  z-index: 200;
}
.modal {
  background: var(--bg-card); border-radius: 18px;
  width: 680px; max-width: 96vw; max-height: 88vh;
  display: flex; flex-direction: column;
  box-shadow: var(--shadow-modal);
  overflow: hidden;
}

.modal-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 20px 24px; border-bottom: 1px solid var(--border); flex-shrink: 0;
}
.header-title { display: flex; align-items: center; gap: 10px; }
.header-icon { font-size: 22px; }
h2 { font-size: 18px; font-weight: 700; color: var(--text-primary); }
.close-btn {
  width: 30px; height: 30px; border: none; border-radius: 8px;
  background: var(--bg-page); color: var(--text-muted); font-size: 14px; cursor: pointer;
}
.close-btn:hover { background: var(--border); }

.modal-body { padding: 24px; overflow-y: auto; flex: 1; }

.field { margin-bottom: 20px; }
.field label { display: block; font-size: 13px; font-weight: 700; color: var(--text-secondary); margin-bottom: 4px; }
.input-hint { font-size: 12px; color: var(--text-faint); margin-bottom: 8px; }
.field input[type="text"] {
  width: 100%; padding: 9px 12px; border: 1.5px solid var(--border);
  border-radius: 8px; font-size: 14px; color: var(--text-primary); background: var(--bg-input);
}
.field input:focus { outline: none; border-color: #3B82F6; }

.vlan-checklist { display: flex; flex-direction: column; gap: 8px; }
.vlan-check {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 12px; border: 1.5px solid var(--border); border-radius: 10px;
  cursor: pointer; transition: border-color 0.15s;
}
.vlan-check:hover:not(.disabled) { border-color: #93C5FD; background: var(--bg-card-hover); }
.vlan-check.disabled { opacity: 0.5; cursor: not-allowed; }
.vlan-check input[type="checkbox"] { width: 16px; height: 16px; flex-shrink: 0; cursor: pointer; }
.vlan-check-body { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.vlan-badge {
  color: #fff; font-size: 11px; font-weight: 800;
  padding: 2px 9px; border-radius: 20px;
}
.vlan-badge.sm { font-size: 10px; padding: 1px 7px; }
.vlan-check-name { font-size: 14px; font-weight: 600; color: var(--text-primary); }
.vlan-check-cidr { font-size: 12px; color: var(--text-muted); font-family: monospace; background: var(--bg-page); padding: 1px 5px; border-radius: 4px; }
.no-cidr { font-size: 12px; color: var(--text-faint); font-style: italic; }
.host-count { font-size: 12px; color: var(--text-faint); }

.scanning-body {
  display: flex; flex-direction: column; align-items: center;
  justify-content: center; padding: 60px 24px; gap: 16px;
}
.spinner {
  width: 48px; height: 48px; border-radius: 50%;
  border: 4px solid var(--border); border-top-color: #3B82F6;
  animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.scan-msg { font-size: 18px; font-weight: 700; color: var(--text-primary); }
.scan-detail { font-size: 14px; color: var(--text-muted); }
.scan-note { font-size: 12px; color: var(--text-faint); }

.results-summary {
  display: flex; align-items: center; gap: 10px;
  margin-bottom: 16px; flex-wrap: wrap;
}
.summary-found { font-size: 16px; font-weight: 700; color: var(--text-primary); }
.summary-meta { font-size: 13px; color: var(--text-muted); }
.summary-new {
  background: #D1FAE5; color: #065F46;
  font-size: 12px; font-weight: 700; padding: 2px 10px; border-radius: 20px;
}

.empty-results { text-align: center; padding: 32px; color: var(--text-faint); font-size: 15px; }

.results-table-wrap { overflow-x: auto; border: 1.5px solid var(--border); border-radius: 10px; }
.results-table { width: 100%; border-collapse: collapse; }
.results-table thead { background: var(--bg-thead); }
.results-table th {
  padding: 10px 12px; text-align: left;
  font-size: 11px; font-weight: 700; color: var(--text-muted);
  text-transform: uppercase; letter-spacing: 0.05em;
}
.results-table td { padding: 10px 12px; font-size: 13px; border-top: 1px solid var(--border); color: var(--text-primary); }
.results-table tr:hover td { background: var(--bg-card-hover); }
.row-existing td { opacity: 0.5; }

code.ip { font-family: monospace; font-size: 13px; color: var(--text-primary); }
.hostname { color: #1D4ED8; font-weight: 600; }
.no-dns { color: var(--text-faint); }

.status {
  font-size: 11px; font-weight: 700; padding: 2px 9px; border-radius: 20px;
}
.status.new      { background: #DBEAFE; color: #1D4ED8; }
.status.existing { background: var(--bg-page); color: var(--text-faint); }

.field-toggle { border: 1.5px solid var(--border); border-radius: 10px; padding: 12px; }
.toggle-row { display: flex; align-items: center; gap: 10px; cursor: pointer; }
.toggle-checkbox { width: 16px; height: 16px; flex-shrink: 0; cursor: pointer; accent-color: #3B82F6; }
.toggle-label { font-size: 13px; font-weight: 700; color: var(--text-secondary); }
.field-toggle .input-hint { margin-top: 6px; margin-bottom: 0; }

.warn-box {
  background: #FFFBEB; border: 1.5px solid #FCD34D; border-radius: 8px;
  padding: 12px; font-size: 13px; color: #92400E;
}
.error-box {
  background: #FEF2F2; border: 1.5px solid #FCA5A5; border-radius: 8px;
  padding: 12px; font-size: 13px; color: #B91C1C; margin-top: 12px;
}

.modal-footer {
  padding: 16px 24px; border-top: 1px solid var(--border);
  display: flex; justify-content: flex-end; gap: 10px; flex-shrink: 0;
}
.btn-primary {
  padding: 9px 20px; background: #3B82F6; color: #fff;
  border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer;
}
.btn-primary:hover:not(:disabled) { background: #2563EB; }
.btn-primary:disabled { opacity: 0.45; cursor: not-allowed; }
.btn-secondary {
  padding: 9px 20px; background: var(--bg-page); color: var(--text-secondary);
  border: none; border-radius: 8px; font-size: 14px; font-weight: 500; cursor: pointer;
}
.btn-secondary:hover { background: var(--border); }
</style>
