<template>
  <article class="glass-panel form-panel intune-config-panel">
    <div class="section-title">
      <div>
        <span class="eyebrow">CONFIG / VMWARE</span>
        <h3>VMware connections</h3>
        <p>Register vCenter inventory systems or standalone ESXi hosts for VMware-aware host management.</p>
      </div>
      <button class="primary-action compact" type="button" @click="openModal()">
        <i class="mdi mdi-server-network" aria-hidden="true"></i>Add VMware connection
      </button>
    </div>

    <div class="intune-config-grid">
      <section class="publisher-card">
        <strong>Inventory sources</strong>
        <p>vCenter entries import VM inventory and power-state checks. Standalone host entries validate direct ESXi connections through the vSphere Web Services API.</p>
        <div class="config-stat-row">
          <span><b>{{ connections.length }}</b><small>systems</small></span>
          <span><b>{{ enabledCount }}</b><small>enabled</small></span>
          <span><b>{{ vcenterCount }}</b><small>vCenter</small></span>
          <span><b>{{ standaloneCount }}</b><small>hosts</small></span>
          <span><b>{{ testedCount }}</b><small>tested</small></span>
        </div>
      </section>

      <section class="publisher-card graph-config-list">
        <strong>VMware systems</strong>
        <div v-for="connection in connections" :key="connection.id" class="check-row">
          <b>{{ connection.name }}</b>
          <small>{{ connection.baseUrl }} - {{ connectionTypeLabel(connection) }} - {{ connection.apiMode }} - {{ connection.lastTestStatus || 'untested' }}</small>
          <span>
            <button class="ghost-button compact" type="button" @click="openModal(connection)">
              <i class="mdi mdi-pencil-outline" aria-hidden="true"></i>Edit
            </button>
            <button class="ghost-button compact" type="button" @click="$emit('test', connection.id)">
              <i class="mdi mdi-lan-check" aria-hidden="true"></i>Test
            </button>
            <button class="ghost-button compact danger-text" type="button" @click="$emit('delete', connection.id)">
              <i class="mdi mdi-trash-can-outline" aria-hidden="true"></i>Delete
            </button>
          </span>
        </div>
        <p v-if="!connections.length" class="widget-empty">No saved VMware systems configured. The legacy env/settings default can still be used by vCenter import.</p>
      </section>
    </div>

    <BaseModal
      :open="modalOpen"
      :title="form.id ? 'Update VMware connection' : 'New VMware connection'"
      eyebrow="CONFIG / VMWARE"
      description="Store VMware credentials encrypted at rest. vCenter systems can import VM inventory; standalone hosts use the vSphere Web Services API for direct connection validation."
      wide
      @close="modalOpen = false"
    >
      <form class="form-grid" @submit.prevent="save">
        <label>
          <span>Connection type</span>
          <select v-model="form.targetType">
            <option value="vcenter">vCenter inventory</option>
            <option value="host">Standalone ESXi host</option>
          </select>
        </label>
        <label><span>Name</span><input v-model="form.name" required :placeholder="form.targetType === 'host' ? 'Rack ESXi host 01' : 'Production vCenter'" /></label>
        <label><span>Base URL</span><input v-model="form.baseUrl" required :placeholder="baseUrlPlaceholder" /></label>
        <label><span>Username</span><input v-model="form.username" required :placeholder="form.targetType === 'host' ? 'root or delegated ESXi account' : 'administrator@vsphere.local'" /></label>
        <label><span>{{ form.id ? 'Replace password' : 'Password' }}</span><input v-model="form.password" :required="!form.id" type="password" placeholder="Stored encrypted after save" /></label>
        <label>
          <span>API mode</span>
          <select v-model="form.apiMode" :disabled="form.targetType === 'host'">
            <option value="auto">Auto</option>
            <option value="api">vSphere /api</option>
            <option value="rest">Legacy /rest</option>
            <option value="web-services">vSphere Web Services</option>
          </select>
        </label>
        <label><span>Timeout (ms)</span><input v-model.number="form.requestTimeoutMs" type="number" min="1000" max="120000" /></label>
        <label><span>Visibility</span><select v-model="form.visibility"><option value="personal">Personal</option><option value="shared">Shared</option><option value="group">Group</option></select></label>
        <label v-if="form.visibility === 'group'"><span>Group</span><select v-model="form.groupId"><option value="">Choose group</option><option v-for="group in groups" :key="group.id" :value="group.id">{{ group.name }}</option></select></label>
        <label class="toggle modal-toggle"><input v-model="form.enabled" type="checkbox" /><span><strong>Enabled</strong><small>{{ enabledHelpText }}</small></span></label>
        <label class="toggle modal-toggle"><input v-model="form.allowUntrustedTls" type="checkbox" /><span><strong>Allow untrusted TLS</strong><small>Use only for internal/self-signed VMware certificates.</small></span></label>
        <div class="form-actions modal-actions full">
          <button class="ghost-button" type="button" @click="modalOpen = false">
            <i class="mdi mdi-close" aria-hidden="true"></i>Cancel
          </button>
          <button class="primary-action" type="submit">
            <i class="mdi mdi-content-save-outline" aria-hidden="true"></i>Save VMware connection
          </button>
        </div>
      </form>
    </BaseModal>
  </article>
</template>

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

const props = defineProps({
  connections: { type: Array, default: () => [] },
  groups: { type: Array, default: () => [] }
});

const emit = defineEmits(['save', 'delete', 'test']);

const modalOpen = ref(false);
const form = reactive(defaultForm());
const enabledCount = computed(() => props.connections.filter((connection) => connection.enabled).length);
const vcenterCount = computed(() => props.connections.filter((connection) => connection.targetType !== 'host').length);
const standaloneCount = computed(() => props.connections.filter((connection) => connection.targetType === 'host').length);
const testedCount = computed(() => props.connections.filter((connection) => connection.lastTestStatus).length);
const baseUrlPlaceholder = computed(() => form.targetType === 'host' ? 'https://esxi01.contoso.local' : 'https://vcenter.contoso.local');
const enabledHelpText = computed(() => form.targetType === 'host'
  ? 'Allow this standalone host connection to be tested and used for direct VMware host workflows.'
  : 'Allow this vCenter system to be used for import and power-state checks.');

watch(() => form.targetType, (targetType) => {
  if (targetType === 'host') {
    form.apiMode = 'web-services';
  } else if (form.apiMode === 'web-services') {
    form.apiMode = 'auto';
  }
});

function defaultForm() {
  return {
    id: null,
    name: '',
    targetType: 'vcenter',
    baseUrl: '',
    username: '',
    password: '',
    apiMode: 'auto',
    requestTimeoutMs: 20000,
    allowUntrustedTls: false,
    enabled: true,
    visibility: 'shared',
    groupId: ''
  };
}

function openModal(connection = null) {
  Object.assign(form, defaultForm(), connection || {});
  form.targetType = connection?.targetType || 'vcenter';
  form.apiMode = form.targetType === 'host' ? 'web-services' : (connection?.apiMode || 'auto');
  form.password = '';
  form.groupId = connection?.groupId || '';
  modalOpen.value = true;
}

function save() {
  emit('save', { ...form, groupId: form.groupId || null });
  modalOpen.value = false;
}

function connectionTypeLabel(connection) {
  return connection.targetType === 'host' ? 'Standalone ESXi host' : 'vCenter inventory';
}
</script>
