<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useApi } from '@/composables/useApi'
import Logo from '@/components/ds/brand/Logo.vue'
import Input from '@/components/ds/forms/Input.vue'
import Button from '@/components/ds/core/Button.vue'
import Alert from '@/components/ds/feedback/Alert.vue'

const router = useRouter()
const auth = useAuthStore()
const api = useApi()

const step = ref(1)
const isLoading = ref(false)
const error = ref('')

const serverForm = ref({
  server_name: '',
  connection_type: 'bare_metal' as 'amp' | 'pterodactyl' | 'bare_metal',
  server_ip: '',
  server_port: 28016,
  game_port: 28015,
})

// String mirrors for the DS Input component (which binds defineModel<string>).
// Changes sync back to serverForm as numbers before submission.
const serverPortStr = ref(String(serverForm.value.server_port))
const gamePortStr = ref(String(serverForm.value.game_port))

function syncPorts() {
  serverForm.value.server_port = parseInt(serverPortStr.value, 10) || serverForm.value.server_port
  serverForm.value.game_port = parseInt(gamePortStr.value, 10) || serverForm.value.game_port
}

const connectionTypes = [
  { value: 'bare_metal', label: 'Bare metal / VPS', desc: 'Direct connection via Corrosion host agent' },
  { value: 'amp', label: 'AMP (CubeCoders)', desc: 'Connect through AMP panel API' },
  { value: 'pterodactyl', label: 'Pterodactyl', desc: 'Connect through Pterodactyl panel API' },
]

async function submitServerConfig() {
  syncPorts()

  if (!serverForm.value.server_name.trim()) {
    error.value = 'Server name is required.'
    return
  }

  error.value = ''
  isLoading.value = true

  try {
    await api.post('/setup/server', serverForm.value)
    step.value = 2
  } catch (err: unknown) {
    error.value = err instanceof Error ? err.message : 'Setup failed. Please try again.'
  } finally {
    isLoading.value = false
  }
}

async function completeSetup() {
  isLoading.value = true
  try {
    await api.post('/setup/complete')
    router.push('/')
  } catch {
    router.push('/')
  }
}
</script>

<template>
  <div class="setup-shell">
    <div class="setup-wrap">
      <!-- Brand header -->
      <div class="setup-brand">
        <div class="setup-brand__mark">
          <Logo :size="30" tagline="Setup" />
        </div>
      </div>

      <!-- Progress stepper -->
      <div class="setup-steps">
        <div
          v-for="(s, i) in [
            { label: 'Server', icon: 'server' },
            { label: 'Connect', icon: 'wifi' },
            { label: 'Done', icon: 'check' },
          ]"
          :key="i"
          class="setup-step"
          :class="{
            'setup-step--active': step === i + 1,
            'setup-step--done': step > i + 1,
          }"
        >
          <span class="setup-step__num">{{ step > i + 1 ? '✓' : i + 1 }}</span>
          <span class="setup-step__label">{{ s.label }}</span>
          <div v-if="i < 2" class="setup-step__connector" :class="step > i + 1 ? 'setup-step__connector--done' : ''" />
        </div>
      </div>

      <!-- Step 1: Server config -->
      <div v-if="step === 1" class="setup-card">
        <div class="setup-card__head">
          <h1 class="setup-card__title">Configure your server</h1>
          <p class="setup-card__sub">Connect your Rust server to Corrosion.</p>
        </div>

        <Alert v-if="error" tone="danger">{{ error }}</Alert>

        <form class="setup-form" @submit.prevent="submitServerConfig">
          <Input
            v-model="serverForm.server_name"
            label="Server name"
            type="text"
            placeholder="My Rust Server"
            :required="true"
          />

          <!-- Connection type selector -->
          <div class="conn-group">
            <span class="conn-group__label">Connection type</span>
            <div class="conn-options">
              <label
                v-for="ct in connectionTypes"
                :key="ct.value"
                class="conn-option"
                :class="serverForm.connection_type === ct.value ? 'conn-option--active' : ''"
              >
                <input
                  v-model="serverForm.connection_type"
                  :value="ct.value"
                  type="radio"
                  name="connection_type"
                  class="conn-option__radio"
                />
                <div class="conn-option__body">
                  <span class="conn-option__name">{{ ct.label }}</span>
                  <span class="conn-option__desc">{{ ct.desc }}</span>
                </div>
              </label>
            </div>
          </div>

          <!-- Port / IP row -->
          <div class="setup-ports">
            <Input
              v-model="serverForm.server_ip"
              label="Server IP"
              type="text"
              placeholder="0.0.0.0"
              :mono="true"
            />
            <Input
              v-model="serverPortStr"
              label="RCON port"
              type="text"
              placeholder="28016"
              :mono="true"
            />
            <Input
              v-model="gamePortStr"
              label="Game port"
              type="text"
              placeholder="28015"
              :mono="true"
            />
          </div>

          <Button
            type="submit"
            :loading="isLoading"
            :block="true"
            size="md"
            icon-right="arrow-right"
          >
            Continue
          </Button>
        </form>
      </div>

      <!-- Step 2: Corrosion host agent install -->
      <div v-if="step === 2" class="setup-card">
        <div class="setup-card__head setup-card__head--center">
          <div class="setup-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
              <path d="M5 12.55a11 11 0 0 1 14.08 0M1.42 9a16 16 0 0 1 21.16 0M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01" />
            </svg>
          </div>
          <h1 class="setup-card__title">Install the Corrosion host agent</h1>
          <p class="setup-card__sub">The agent runs on your server and connects to Corrosion — no inbound ports required.</p>
        </div>

        <div class="setup-code">
          <p class="setup-code__comment"># Download the Corrosion host agent (Linux)</p>
          <p class="setup-code__cmd">curl -LO https://cdn.corrosionmgmt.com/host-agent/latest/corrosion-host-agent-linux-amd64</p>
          <p class="setup-code__cmd">chmod +x corrosion-host-agent-linux-amd64</p>
          <p class="setup-code__comment setup-code__comment--mt"># Start with your license key</p>
          <p class="setup-code__cmd">export LICENSE_ID="{{ auth.license?.license_key ?? 'YOUR-LICENSE-KEY' }}"</p>
          <p class="setup-code__cmd">export NATS_URL="nats://nats.corrosionmgmt.com:4222"</p>
          <p class="setup-code__cmd">./corrosion-host-agent-linux-amd64</p>
        </div>

        <p class="setup-hint">
          On Windows, download the agent from the Server page after setup. The agent connects outbound and auto-registers with your panel.
        </p>

        <div class="setup-actions">
          <Button
            type="button"
            variant="secondary"
            size="md"
            @click="step = 3"
          >
            Skip for now
          </Button>
          <Button
            type="button"
            size="md"
            icon-right="arrow-right"
            @click="step = 3"
          >
            I've installed it
          </Button>
        </div>
      </div>

      <!-- Step 3: Complete -->
      <div v-if="step === 3" class="setup-card setup-card--center">
        <div class="setup-complete-icon">
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
            <polyline points="22 4 12 14.01 9 11.01" />
          </svg>
        </div>
        <h1 class="setup-card__title">You're all set</h1>
        <p class="setup-card__sub">Your server is configured. Head to the dashboard to start managing your game server.</p>
        <Button
          type="button"
          :loading="isLoading"
          :block="true"
          size="md"
          @click="completeSetup"
        >
          Go to dashboard
        </Button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.setup-shell {
  min-height: 100vh;
  background: var(--surface-canvas);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-4);
}

.setup-wrap {
  width: 100%;
  max-width: 500px;
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
}

/* Brand */
.setup-brand {
  display: flex;
  justify-content: center;
}
.setup-brand__mark {
  color: var(--accent);
}

/* Progress stepper */
.setup-steps {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
}

.setup-step {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  position: relative;
}

.setup-step__num {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-family: var(--font-mono);
  font-size: var(--text-xs);
  font-weight: 700;
  background: var(--surface-raised);
  box-shadow: var(--ring-default);
  color: var(--text-muted);
  flex: none;
  transition: background 200ms ease, color 200ms ease, box-shadow 200ms ease;
}

.setup-step--active .setup-step__num {
  background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
  color: var(--accent-text);
}

.setup-step--done .setup-step__num {
  background: var(--accent);
  box-shadow: none;
  color: var(--accent-contrast);
}

.setup-step__label {
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-muted);
  white-space: nowrap;
}

.setup-step--active .setup-step__label,
.setup-step--done .setup-step__label {
  color: var(--text-secondary);
}

.setup-step__connector {
  width: 40px;
  height: 1px;
  background: var(--border-default);
  margin: 0 var(--space-2);
  flex: none;
  transition: background 200ms ease;
}

.setup-step__connector--done {
  background: var(--accent-border);
}

/* Card */
.setup-card {
  background: var(--surface-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--ring-default), var(--shadow-lg);
  padding: var(--space-8);
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
}

.setup-card--center {
  align-items: center;
  text-align: center;
}

.setup-card__head {
  display: flex;
  flex-direction: column;
  gap: var(--space-1-5);
}

.setup-card__head--center {
  align-items: center;
  text-align: center;
}

.setup-card__title {
  margin: 0;
  font-size: var(--text-xl);
  font-weight: 700;
  color: var(--text-primary);
  letter-spacing: var(--tracking-tight);
}

.setup-card__sub {
  margin: 0;
  font-size: var(--text-sm);
  color: var(--text-secondary);
  line-height: var(--leading-normal);
}

/* Icon in step 2 header */
.setup-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
  color: var(--accent-text);
  flex: none;
}

/* Step 3 check icon */
.setup-complete-icon {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--status-online-soft);
  box-shadow: inset 0 0 0 1px var(--status-online-border);
  color: var(--status-online);
}

/* Form */
.setup-form {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

/* Connection type group */
.conn-group {
  display: flex;
  flex-direction: column;
  gap: var(--space-1-5);
}

.conn-group__label {
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-secondary);
}

.conn-options {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.conn-option {
  display: flex;
  align-items: flex-start;
  gap: var(--space-3);
  padding: var(--space-3);
  background: var(--surface-inset);
  border-radius: var(--radius-md);
  box-shadow: var(--ring-default);
  cursor: pointer;
  transition: box-shadow 120ms ease, background 120ms ease;
}

.conn-option--active {
  background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}

.conn-option__radio {
  margin-top: 2px;
  accent-color: var(--accent);
  flex: none;
}

.conn-option__body {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.conn-option__name {
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
}

.conn-option__desc {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}

/* Port grid */
.setup-ports {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  gap: var(--space-3);
}

/* Code block */
.setup-code {
  background: var(--surface-sunken);
  border-radius: var(--radius-md);
  box-shadow: var(--ring-subtle);
  padding: var(--space-4) var(--space-5);
  font-family: var(--font-mono);
  font-size: var(--text-xs);
  line-height: 1.8;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.setup-code__comment {
  margin: 0;
  color: var(--text-muted);
}

.setup-code__comment--mt {
  margin-top: var(--space-2);
}

.setup-code__cmd {
  margin: 0;
  color: var(--accent-text);
  word-break: break-all;
}

.setup-hint {
  margin: 0;
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  text-align: center;
  line-height: var(--leading-normal);
}

.setup-actions {
  display: flex;
  gap: var(--space-3);
}

.setup-actions > * {
  flex: 1;
}
</style>
