<template>
  <div class="min-h-screen flex flex-col items-center justify-center bg-gray-50 p-6">
    <div class="max-w-md w-full space-y-6">
      <div class="text-center">
        <div class="w-16 h-16 mx-auto bg-[var(--rebreak-primary)] rounded-xl flex items-center justify-center mb-4">
          <UIcon name="i-heroicons-lock-closed" class="w-8 h-8 text-white" />
        </div>
        <h1 class="text-2xl font-bold text-gray-900">
          iPhone supervisieren
        </h1>
        <p class="text-gray-600 mt-2">
          Wir schreiben die Supervision-Metadaten auf dein iPhone und starten es neu. Apps, Daten und Logins bleiben erhalten.
        </p>
      </div>

      <UCard>
        <div class="space-y-4">
          <div
            v-if="status"
            class="text-sm space-y-1 p-3 rounded-lg"
            :class="status.isSupervised ? 'bg-green-50 text-green-700' : 'bg-gray-100 text-gray-600'"
          >
            <p><strong>Status:</strong> {{ status.isSupervised ? 'Bereits supervised' : 'Nicht supervised' }}</p>
            <p v-if="status.organizationName"><strong>Organisation:</strong> {{ status.organizationName }}</p>
            <p v-if="status.findMyEnabled !== undefined"><strong>Find My:</strong> {{ status.findMyEnabled ? 'An' : 'Aus' }}</p>
          </div>

          <UButton
            size="lg"
            color="primary"
            block
            :loading="supervising"
            :disabled="skipBecauseOwned"
            @click="runSupervise"
          >
            {{ skipBecauseOwned ? 'Bereits von ReBreak supervised' : 'Supervision starten' }}
          </UButton>

          <div v-if="result" class="text-sm">
            <p v-if="result.success" class="text-green-600">
              ✅ Supervision abgeschlossen. Das iPhone startet neu.
            </p>
            <div v-else class="text-red-600 space-y-1">
              <p>❌ Supervision fehlgeschlagen</p>
              <pre class="text-xs bg-gray-100 p-2 rounded overflow-auto">{{ result.stderr || result.stdout }}</pre>
            </div>
          </div>

          <div v-if="logs.length > 0" class="text-xs bg-gray-100 p-3 rounded overflow-auto max-h-48">
            <p class="font-semibold text-gray-700 mb-1">Logs:</p>
            <pre class="whitespace-pre-wrap break-all">{{ logs.join('\n') }}</pre>
          </div>
        </div>
      </UCard>

      <div class="flex justify-between">
        <UButton to="/" variant="ghost" color="neutral">
          Zurück
        </UButton>
        <UButton
          to="/enroll"
          variant="solid"
          color="primary"
          :disabled="!canContinue"
        >
          Weiter
        </UButton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useTauri, type SuperviseResult, type SuperviseStatus } from "~/composables/useTauri";
import { useIphoneDevice } from "~/composables/useMagicState";

const { getSuperviseStatus, runSuperviseMagic } = useTauri();
const iphone = useIphoneDevice();
const status = ref<SuperviseStatus | null>(null);
const supervising = ref(false);
const result = ref<SuperviseResult | null>(null);
const logs = ref<string[]>([]);

const skipBecauseOwned = computed(() =>
  status.value?.isSupervised && status.value?.organizationName?.toLowerCase() === "rebreak",
);

const canContinue = computed(() =>
  skipBecauseOwned.value || result.value?.success === true,
);

onMounted(async () => {
  try {
    status.value = await getSuperviseStatus();
    if (skipBecauseOwned.value) {
      logs.value.push("✓ Bereits von ReBreak supervised — überspringe.");
      if (iphone.value) {
        iphone.value.isSupervised = true;
        iphone.value.organizationName = "ReBreak";
      }
    }
  } catch (e: any) {
    logs.value.push(`✗ Status konnte nicht gelesen werden: ${e?.message ?? e}`);
  }
});

async function runSupervise() {
  supervising.value = true;
  result.value = null;
  logs.value = [];

  try {
    const force = !status.value?.isSupervised;
    const args = ["-org", "ReBreak", "-yes"];
    if (force) args.push("-force");

    logs.value.push(`→ supervise-magic supervise ${args.join(" ")}`);
    result.value = await runSuperviseMagic("supervise", args);

    if (result.value.success) {
      logs.value.push("✓ Supervision abgeschlossen.");
      if (iphone.value) {
        iphone.value.isSupervised = true;
        iphone.value.organizationName = "ReBreak";
      }
    } else {
      logs.value.push(`✗ Fehler: ${result.value.stderr || result.value.stdout}`);
    }
  } catch (e: any) {
    result.value = { success: false, stdout: "", stderr: e?.message ?? String(e) };
    logs.value.push(`✗ Exception: ${e?.message ?? e}`);
  } finally {
    supervising.value = false;
  }
}
</script>
