<template>
  <article class="glass-panel form-panel intune-config-panel">
    <div class="section-title">
      <div>
        <span class="eyebrow">CONFIG / INTUNE</span>
        <h3>Microsoft Graph Intune</h3>
        <p>Configure Graph environments used for Intune app lookup, deployment linking, and install-status sync.</p>
      </div>
      <button class="primary-action compact" type="button" @click="openModal()">
        <CloudCog :size="15" />Add environment
      </button>
    </div>

    <div class="intune-config-grid">
      <section class="publisher-card">
        <strong>Environment routing</strong>
        <p>Graph credentials live here under Config / Intune. PSADT publishing screens consume these environments for tracking and sync.</p>
        <div class="config-stat-row">
          <span><b>{{ graphConnections.length }}</b><small>environments</small></span>
          <span><b>{{ enabledCount }}</b><small>enabled</small></span>
          <span><b>{{ testedCount }}</b><small>tested</small></span>
        </div>
      </section>

      <section class="publisher-card graph-config-list">
        <strong>Graph environments</strong>
        <div v-for="connection in graphConnections" :key="connection.id" class="check-row">
          <b>{{ connection.name }}</b>
          <small>{{ connection.cloud }} - {{ connection.tenantId }} - {{ connection.lastTestStatus || 'untested' }}</small>
          <span>
            <button class="ghost-button compact" type="button" @click="openModal(connection)">Edit</button>
            <button class="ghost-button compact" type="button" @click="$emit('test', connection.id)">Test</button>
            <button class="ghost-button compact danger-text" type="button" @click="$emit('delete', connection.id)">Delete</button>
          </span>
        </div>
        <p v-if="!graphConnections.length" class="widget-empty">No Microsoft Graph Intune environments configured.</p>
      </section>
    </div>

    <BaseModal
      :open="modalOpen"
      :title="form.id ? 'Update Graph environment' : 'New Graph environment'"
      eyebrow="CONFIG / INTUNE"
      description="Store the Entra app registration used for Microsoft Graph Intune access. Client secrets are encrypted by the API."
      wide
      @close="modalOpen = false"
    >
      <form class="form-grid" @submit.prevent="save">
        <label><span>Name</span><input v-model="form.name" required placeholder="Production Intune" /></label>
        <label><span>Cloud</span><select v-model="form.cloud" @change="applyCloudDefaults"><option value="global">Global</option><option value="gcc">GCC</option><option value="gcchigh">GCC High</option><option value="dod">DoD</option><option value="china">China</option><option value="custom">Custom</option></select></label>
        <label><span>Tenant ID</span><input v-model="form.tenantId" required placeholder="tenant-guid-or-domain" /></label>
        <label><span>Client ID</span><input v-model="form.clientId" required placeholder="app-registration-client-id" /></label>
        <label class="full"><span>Client secret</span><input v-model="form.clientSecret" :required="!form.id" type="password" placeholder="Stored encrypted; leave blank to keep existing secret" /></label>
        <label><span>Graph base URL</span><input v-model="form.graphBaseUrl" required /></label>
        <label><span>Authority host</span><input v-model="form.authorityHost" required /></label>
        <label><span>Default API version</span><select v-model="form.defaultApiVersion"><option value="v1.0">v1.0</option><option value="beta">beta</option></select></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>Allow this environment to be used by Intune tracking.</small></span></label>
        <label class="toggle modal-toggle"><input v-model="form.allowWrite" type="checkbox" /><span><strong>Allow tenant write-back</strong><small>Permit publishing/updating Win32 apps in this tenant. Admin only; leave off for read-only tracking.</small></span></label>
        <label class="toggle modal-toggle"><input v-model="form.requireApproval" type="checkbox" /><span><strong>Require approval</strong><small>Tenant-changing actions create a change request that an admin must approve before they run.</small></span></label>
        <template v-if="isAdmin">
          <label class="full"><span>Authorized publishers</span><select v-model="form.publisherIds" multiple size="3"><option v-for="u in users" :key="u.id" :value="u.id">{{ u.displayName }} ({{ u.email }})</option></select><small class="field-hint">Empty = any user with a write-enabled connection may publish.</small></label>
          <label class="full"><span>Authorized approvers</span><select v-model="form.approverIds" multiple size="3"><option v-for="u in users" :key="u.id" :value="u.id">{{ u.displayName }} ({{ u.email }})</option></select><small class="field-hint">Named approvers may approve change requests in addition to admins.</small></label>
        </template>
        <div class="form-actions modal-actions full">
          <button class="ghost-button" type="button" @click="modalOpen = false">Cancel</button>
          <button class="primary-action" type="submit"><Save :size="17" />Save environment</button>
        </div>
      </form>
    </BaseModal>
  </article>
</template>

<script setup>
import { computed, reactive, ref } from 'vue';
import { CloudCog, Save } from '@lucide/vue';
import BaseModal from '../ui/BaseModal.vue';

const props = defineProps({
  graphConnections: { type: Array, default: () => [] },
  groups: { type: Array, default: () => [] },
  users: { type: Array, default: () => [] },
  isAdmin: { type: Boolean, default: false }
});

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

const modalOpen = ref(false);
const form = reactive(defaultForm());
const enabledCount = computed(() => props.graphConnections.filter((connection) => connection.enabled).length);
const testedCount = computed(() => props.graphConnections.filter((connection) => connection.lastTestStatus).length);

function defaultForm() {
  return {
    id: null,
    name: '',
    tenantId: '',
    clientId: '',
    clientSecret: '',
    cloud: 'global',
    graphBaseUrl: 'https://graph.microsoft.com',
    authorityHost: 'https://login.microsoftonline.com',
    defaultApiVersion: 'v1.0',
    enabled: true,
    allowWrite: false,
    requireApproval: false,
    publisherIds: [],
    approverIds: [],
    visibility: 'personal',
    groupId: ''
  };
}

function openModal(connection = null) {
  Object.assign(form, defaultForm(), connection || {});
  form.clientSecret = '';
  form.groupId = connection?.groupId || '';
  modalOpen.value = true;
}

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

function applyCloudDefaults() {
  const defaults = {
    global: ['https://graph.microsoft.com', 'https://login.microsoftonline.com'],
    gcc: ['https://graph.microsoft.com', 'https://login.microsoftonline.com'],
    gcchigh: ['https://graph.microsoft.us', 'https://login.microsoftonline.us'],
    dod: ['https://dod-graph.microsoft.us', 'https://login.microsoftonline.us'],
    china: ['https://microsoftgraph.chinacloudapi.cn', 'https://login.chinacloudapi.cn']
  };
  const next = defaults[form.cloud];
  if (!next) return;
  form.graphBaseUrl = next[0];
  form.authorityHost = next[1];
}
</script>

<style scoped>
.intune-config-panel {
  margin-bottom: 18px;
}

.intune-config-grid {
  display: grid;
  grid-template-columns: minmax(260px, 0.65fr) minmax(0, 1.35fr);
  gap: 14px;
}

.config-stat-row {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 10px;
  margin-top: 14px;
}

.config-stat-row span {
  padding: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.055);
}

.config-stat-row b,
.config-stat-row small {
  display: block;
}

.config-stat-row small {
  color: rgba(255, 255, 255, 0.55);
  font-size: 0.72rem;
}

.graph-config-list {
  min-height: 180px;
}

@media (max-width: 900px) {
  .intune-config-grid {
    grid-template-columns: 1fr;
  }
}
</style>
