<template>
  <BaseModal
    :open="open"
    title="Import VMware hosts"
    eyebrow="VMWARE"
    description="Import virtual machines from vCenter or standalone ESXi inventory into the Host Library."
    wide
    @close="$emit('close')"
  >
    <form class="vcenter-import-form" @submit.prevent="submitImport">
      <section class="wizard-section">
        <div class="section-heading">
          <span>1</span>
          <div>
            <h4>{{ isStandaloneHost ? 'ESXi VM inventory' : 'Search filter' }}</h4>
            <p>{{ isStandaloneHost ? 'Use the vSphere Web Services API on the selected ESXi host to enumerate guest VMs before writing hosts.' : 'Use vCenter VM names, guest hostnames, FQDNs, or IPs to narrow the import set before writing hosts.' }}</p>
          </div>
        </div>
        <div class="vcenter-filter-grid">
          <label class="filter-value">
            <span>VMware connection</span>
            <select v-model="draft.connectionId">
              <option :value="null">Configured default</option>
              <option v-for="connection in importConnections" :key="connection.id" :value="connection.id">
                {{ connection.name }} - {{ connection.targetType === 'host' ? 'Standalone ESXi' : 'vCenter' }} - {{ connection.baseUrl }}
              </option>
            </select>
          </label>
          <label>
            <span>Field</span>
            <select v-model="draft.filter.field">
              <option value="hostname">Hostname / VM name</option>
              <option value="name">VM name only</option>
              <option value="fqdn">Guest FQDN</option>
              <option value="ip">IP address</option>
            </select>
          </label>
          <label>
            <span>Operator</span>
            <select v-model="draft.filter.operator">
              <option value="contains">Contains</option>
              <option value="equals">Equals</option>
              <option value="startsWith">Starts with</option>
              <option value="endsWith">Ends with</option>
            </select>
          </label>
          <label class="filter-value">
            <span>Value</span>
            <input v-model="draft.filter.value" placeholder="ENG-ENT" />
          </label>
          <label>
            <span>Preview limit</span>
            <input v-model.number="draft.limit" type="number" min="1" max="500" />
          </label>
          <div v-if="isStandaloneHost" class="standalone-host-callout">
            <strong>{{ selectedConnection?.name || 'Selected ESXi host' }}</strong>
            <span>{{ selectedConnection?.baseUrl || 'Choose a standalone ESXi connection above.' }}</span>
            <small>Standalone ESXi inventory is queried through the /sdk Web Services endpoint.</small>
          </div>
        </div>
        <div class="wizard-actions">
          <button class="ghost-button" type="button" :disabled="loading" @click="emitPreview">
            <i class="mdi mdi-magnify" aria-hidden="true"></i>{{ isStandaloneHost ? 'Preview VMs' : 'Preview matches' }}
          </button>
          <span v-if="status" class="vcenter-status">
            <span :class="['status-dot', activeStatus.configured ? 'success' : 'warning']"></span>
            {{ activeStatus.configured ? `Using ${activeStatus.name || activeStatus.typeLabel || 'VMware'} at ${activeStatus.baseUrl}` : 'VMware settings incomplete' }}
          </span>
          <button v-if="traceCount" class="ghost-button compact" type="button" @click="$emit('open-trace')">
            <i class="mdi mdi-file-search-outline" aria-hidden="true"></i>View API trace
          </button>
        </div>
      </section>

      <section class="wizard-section">
        <div class="section-heading">
          <span>2</span>
          <div>
            <h4>Import options</h4>
            <p>Attach authentication and host defaults once so every created host is ready for RunPlans.</p>
          </div>
        </div>
        <div class="vcenter-options-grid">
          <label>
            <span>Vault credential</span>
            <select v-model="draft.credentialId">
              <option :value="null">No credential</option>
              <option v-for="credential in credentials" :key="credential.id" :value="credential.id">{{ credential.name }}</option>
            </select>
          </label>
          <label>
            <span>Transport</span>
            <select v-model="draft.transport">
              <option value="winrm">WinRM</option>
              <option value="ssh">SSH</option>
              <option value="local">Local</option>
              <option value="api">API</option>
            </select>
          </label>
          <label>
            <span>Port</span>
            <input v-model.number="draft.port" type="number" min="1" max="65535" placeholder="Default" />
          </label>
          <label>
            <span>Visibility</span>
            <select v-model="draft.visibility">
              <option value="shared">Shared</option>
              <option value="personal">Personal</option>
              <option value="group">Group</option>
            </select>
          </label>
          <label v-if="draft.visibility === 'group'">
            <span>Group</span>
            <select v-model="draft.groupId">
              <option :value="null">Choose group</option>
              <option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</option>
            </select>
          </label>
          <label class="option-tags">
            <span>Additional tags</span>
            <input v-model="draft.tagsText" placeholder="engineering, intune-ready" />
          </label>
        </div>
      </section>

      <section class="wizard-section preview-section">
        <div class="section-heading">
          <span>3</span>
          <div>
            <h4>Preview and select</h4>
            <p>{{ isStandaloneHost ? 'Guest FQDN/IP data comes from VMware Tools through ESXi. Missing values are imported with the VM name as the address fallback.' : 'Guest FQDN/IP data depends on VMware Tools. Missing values are imported with the VM name as the address fallback.' }}</p>
          </div>
        </div>
        <div v-if="error" class="inline-error">{{ error }}</div>
        <div v-if="diagnostics && !diagnostics.standaloneHost" class="vcenter-diagnostics">
          <strong>Preview diagnostics</strong>
          <span>{{ diagnostics.totalFromVCenter }} VM(s) returned by vCenter</span>
          <span>{{ diagnostics.summaryMatched }} VM(s) matched before guest enrichment</span>
          <span>{{ diagnostics.scanned }} VM(s) scanned for guest FQDN/IP details</span>
          <button v-if="traceCount" class="ghost-button compact" type="button" @click="$emit('open-trace')">
            <i class="mdi mdi-file-search-outline" aria-hidden="true"></i>Trace
          </button>
          <small v-if="diagnostics.sampleNames?.length">Sample inventory names: {{ diagnostics.sampleNames.join(', ') }}</small>
        </div>
        <div v-else-if="diagnostics?.standaloneHost" class="vcenter-diagnostics">
          <strong>Standalone ESXi preview</strong>
          <span>{{ diagnostics.totalFromVCenter }} VM(s) returned by ESXi Web Services inventory</span>
          <span>{{ diagnostics.summaryMatched }} VM(s) matched the current filter</span>
          <span>{{ diagnostics.scanned }} VM(s) scanned for guest FQDN/IP details</span>
          <button v-if="traceCount" class="ghost-button compact" type="button" @click="$emit('open-trace')">
            <i class="mdi mdi-file-search-outline" aria-hidden="true"></i>Trace
          </button>
        </div>
        <div class="preview-toolbar">
          <button class="ghost-button compact" type="button" :disabled="!previewRows.length" @click="toggleAll">
            <i class="mdi mdi-checkbox-marked-outline" aria-hidden="true"></i>{{ allSelected ? 'Clear selection' : 'Select all' }}
          </button>
          <span>{{ selectedIds.length }} of {{ previewRows.length }} selected</span>
        </div>
        <div class="vcenter-preview-table">
          <table>
            <thead>
              <tr>
                <th>Select</th>
                <th>VM / Hostname</th>
                <th>FQDN</th>
                <th>Address</th>
                <th>OS</th>
                <th>Power</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in previewRows" :key="row.id">
                <td>
                  <input type="checkbox" :checked="selectedIds.includes(row.id)" @change="toggleRow(row.id)" />
                </td>
                <td>
                  <strong>{{ row.name }}</strong>
                  <small>{{ row.id }}</small>
                </td>
                <td><code>{{ row.fqdn || 'Unavailable' }}</code></td>
                <td><code>{{ row.address || row.ipAddress || 'Unavailable' }}</code></td>
                <td><span class="status-pill">{{ row.osFamily }}</span></td>
                <td>{{ row.powerState || '-' }}</td>
              </tr>
            </tbody>
          </table>
          <div v-if="!previewRows.length" class="wizard-empty">
            Run a preview to see matching virtual machines before importing hosts.
          </div>
        </div>
      </section>

      <div class="form-actions modal-actions">
        <button class="ghost-button" type="button" @click="$emit('close')">Cancel</button>
        <button class="primary-action" type="submit" :disabled="loading || !selectedIds.length">
          <i class="mdi mdi-cloud-download-outline" aria-hidden="true"></i>Import {{ selectedIds.length || '' }} host{{ selectedIds.length === 1 ? '' : 's' }}
        </button>
      </div>
    </form>
  </BaseModal>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue';
import BaseModal from '../ui/BaseModal.vue';

const props = defineProps({
  open: Boolean,
  previewRows: { type: Array, default: () => [] },
  credentials: { type: Array, default: () => [] },
  groups: { type: Array, default: () => [] },
  connections: { type: Array, default: () => [] },
  loading: Boolean,
  error: { type: String, default: '' },
  status: { type: Object, default: null },
  diagnostics: { type: Object, default: null },
  traceCount: { type: Number, default: 0 }
});

const emit = defineEmits(['close', 'preview', 'import', 'open-trace']);

const draft = reactive({
  connectionId: null,
  filter: { field: 'hostname', operator: 'contains', value: 'ENG-ENT' },
  limit: 100,
  credentialId: null,
  transport: 'winrm',
  port: null,
  visibility: 'shared',
  groupId: null,
  tagsText: ''
});
const selectedIds = ref([]);

const importConnections = computed(() => props.connections);
const selectedConnection = computed(() => props.connections.find((item) => item.id === draft.connectionId) || null);
const isStandaloneHost = computed(() => selectedConnection.value?.targetType === 'host');
const allSelected = computed(() => props.previewRows.length > 0 && selectedIds.value.length === props.previewRows.length);
const activeStatus = computed(() => {
  if (draft.connectionId) {
    const connection = selectedConnection.value;
    return {
      name: connection?.name || 'Selected VMware connection',
      typeLabel: connection?.targetType === 'host' ? 'ESXi host' : 'vCenter',
      configured: Boolean(connection?.baseUrl && (connection?.credentialId || connection?.username)),
      baseUrl: connection?.baseUrl || ''
    };
  }
  return props.status?.defaultConnection || props.status || {};
});

watch(importConnections, (connections) => {
  if (draft.connectionId && !connections.some((connection) => connection.id === draft.connectionId)) {
    draft.connectionId = null;
  }
});

watch(() => props.previewRows, (rows) => {
  selectedIds.value = rows.map((row) => row.id);
});

watch(() => props.open, (open) => {
  if (open && props.previewRows.length) selectedIds.value = props.previewRows.map((row) => row.id);
});

function payloadBase() {
  return {
    connectionId: draft.connectionId || null,
    filter: { ...draft.filter, value: draft.filter.value.trim() },
    limit: Number(draft.limit) || 100
  };
}

function emitPreview() {
  emit('preview', payloadBase());
}

function toggleRow(id) {
  selectedIds.value = selectedIds.value.includes(id)
    ? selectedIds.value.filter((selectedId) => selectedId !== id)
    : [...selectedIds.value, id];
}

function toggleAll() {
  selectedIds.value = allSelected.value ? [] : props.previewRows.map((row) => row.id);
}

function submitImport() {
  emit('import', {
    ...payloadBase(),
    vmIds: selectedIds.value,
    credentialId: draft.credentialId || null,
    transport: draft.transport,
    port: draft.port ? Number(draft.port) : null,
    visibility: draft.visibility,
    groupId: draft.visibility === 'group' ? draft.groupId : null,
    tags: draft.tagsText.split(',').map((tag) => tag.trim()).filter(Boolean)
  });
}
</script>
