<template>
  <BaseModal
    :open="open"
    title="Test / Run script"
    eyebrow="SCRIPT EXPLORER"
    :description="script ? `Run ${script.name} against one selected host with one selected vault credential.` : 'Run the selected script against one host.'"
    wide
    @close="$emit('close')"
  >
    <form class="modal-form script-test-form" @submit.prevent="execute">
      <div class="script-test-grid">
        <label>
          <span>Target host</span>
          <select v-model="hostId" required>
            <option value="" disabled>Choose host</option>
            <option v-for="host in hosts" :key="host.id" :value="host.id">
              {{ host.name }} - {{ host.address }} ({{ host.transport }})
            </option>
          </select>
        </label>
        <label>
          <span>Vault credential</span>
          <select v-model="credentialId" required>
            <option value="" disabled>Choose credential</option>
            <option v-for="credential in credentials" :key="credential.id" :value="credential.id">
              {{ credential.name }} - {{ credential.kind }}{{ credential.username ? ` / ${credential.username}` : '' }}
            </option>
          </select>
        </label>
      </div>

      <div class="script-test-context">
        <span><Server :size="16" />{{ selectedHostSummary }}</span>
        <span><KeyRound :size="16" />{{ selectedCredentialSummary }}</span>
      </div>

      <div class="form-actions modal-actions full">
        <button class="ghost-button" type="button" @click="$emit('close')">Close</button>
        <button class="primary-action" type="submit" :disabled="running || !hostId || !credentialId">
          <Play :size="16" />{{ running ? 'Executing...' : 'Execute test' }}
        </button>
      </div>

      <section v-if="job" class="script-test-output">
        <header>
          <div>
            <span class="eyebrow">TERMINAL OUTPUT</span>
            <strong>{{ job.status || 'queued' }}</strong>
          </div>
          <div class="script-test-output-meta">
            <small>{{ terminalLineCount }} lines</small>
            <small>{{ selectedHost?.name || 'host' }}</small>
          </div>
        </header>
        <textarea readonly spellcheck="false" :value="terminalOutput"></textarea>
      </section>
    </form>
  </BaseModal>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { KeyRound, Play, Server } from '@lucide/vue';
import BaseModal from '../ui/BaseModal.vue';

const props = defineProps({
  open: Boolean,
  script: { type: Object, default: null },
  hosts: { type: Array, default: () => [] },
  credentials: { type: Array, default: () => [] },
  job: { type: Object, default: null },
  running: Boolean,
  error: { type: String, default: '' }
});

const emit = defineEmits(['close', 'execute']);

const hostId = ref('');
const credentialId = ref('');

const selectedHost = computed(() => props.hosts.find((host) => host.id === hostId.value));
const selectedCredential = computed(() => props.credentials.find((credential) => credential.id === credentialId.value));
const selectedHostSummary = computed(() => selectedHost.value
  ? `${selectedHost.value.name} / ${selectedHost.value.transport} / ${selectedHost.value.address}`
  : 'No host selected');
const selectedCredentialSummary = computed(() => selectedCredential.value
  ? `${selectedCredential.value.name}${selectedCredential.value.username ? ` as ${selectedCredential.value.username}` : ''}`
  : 'No credential selected');
const terminalRows = computed(() => {
  if (!props.job) return [];
  const lines = [
    `POSHManager script test job ${props.job.id}`,
    `Script: ${props.job.scriptName || props.script?.name || 'selected script'}`,
    `Host: ${selectedHostSummary.value}`,
    `Credential: ${selectedCredentialSummary.value}`,
    `Status: ${props.job.status || 'queued'}`,
    ''
  ];
  if (props.error) lines.push(`[${new Date().toISOString()}] [ERROR] ${props.error}`);
  for (const log of props.job.logs || []) {
    lines.push(`[${log.createdAt || ''}] [${String(log.stream || 'system').toUpperCase()}] [${log.hostName || selectedHost.value?.name || 'host'}] ${log.line}`);
  }
  return lines;
});
const terminalOutput = computed(() => terminalRows.value.join('\n'));
const terminalLineCount = computed(() => terminalRows.value.length);

watch(() => props.open, (open) => {
  if (!open) return;
  hostId.value = props.hosts[0]?.id || '';
  credentialId.value = selectedHost.value?.credentialId || props.credentials[0]?.id || '';
}, { immediate: true });

watch(hostId, () => {
  if (selectedHost.value?.credentialId && props.credentials.some((credential) => credential.id === selectedHost.value.credentialId)) {
    credentialId.value = selectedHost.value.credentialId;
  }
});

function execute() {
  emit('execute', { hostId: hostId.value, credentialId: credentialId.value });
}
</script>
