<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useToastStore } from '@/stores/toast'
import { useApi } from '@/composables/useApi'

import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Badge from '@/components/ds/core/Badge.vue'
import Tabs from '@/components/ds/navigation/Tabs.vue'
import Input from '@/components/ds/forms/Input.vue'
import Switch from '@/components/ds/forms/Switch.vue'

const auth = useAuthStore()
const toast = useToastStore()
const api = useApi()

const saving = ref(false)
const section = ref<string>('account')

const accountForm = ref({
  username: '',
  email: '',
})

const domainForm = ref({
  subdomain: '',
  custom_domain: '',
})

const publicSiteForm = ref({
  show_on_status_page: false,
  status_page_description: '',
})

// --- Security: password change ---
const pwForm = ref({ current_password: '', new_password: '', confirm: '' })
const changingPw = ref(false)

// --- Security: 2FA enrollment flow ---
const totp = ref<{ qr: string; secret: string; code: string; setting: boolean }>({
  qr: '', secret: '', code: '', setting: false,
})
const disable2fa = ref({ open: false, code: '', busy: false })

// --- API keys ---
interface ApiKeyRow {
  id: string
  name: string
  key_prefix: string
  last_used_at: string | null
  is_active: boolean
  created_at: string
}
const apiKeys = ref<ApiKeyRow[]>([])
const newKeyName = ref('')
const creatingKey = ref(false)
const createdKey = ref<string | null>(null)
const loadingKeys = ref(false)

async function loadForms() {
  if (auth.user) {
    accountForm.value.username = auth.user.username
    accountForm.value.email = auth.user.email
  }
  if (auth.license) {
    domainForm.value.subdomain = auth.license.subdomain || ''
    domainForm.value.custom_domain = auth.license.custom_domain || ''
  }

  // Load public site config
  try {
    const config = await api.get<any>('/settings/public-site')
    publicSiteForm.value.show_on_status_page = config.show_on_status_page
    publicSiteForm.value.status_page_description = config.status_page_description || ''
  } catch (err) {
    console.error('Failed to load public site settings:', err)
  }
}

async function saveAccount() {
  saving.value = true
  try {
    await api.put('/auth/profile', accountForm.value)
    toast.success('Account saved successfully')
  } catch (err) {
    toast.error('Failed to save: ' + (err as Error).message)
  } finally {
    saving.value = false
  }
}

async function saveDomain() {
  saving.value = true
  try {
    await api.put('/settings/domain', domainForm.value)
    toast.success('Domain settings saved successfully')
  } catch (err) {
    toast.error('Failed to save: ' + (err as Error).message)
  } finally {
    saving.value = false
  }
}

async function savePublicSite() {
  saving.value = true
  try {
    await api.put('/settings/public-site', publicSiteForm.value)
    toast.success('Public site settings saved successfully')
  } catch (err) {
    toast.error('Failed to save: ' + (err as Error).message)
  } finally {
    saving.value = false
  }
}

async function changePassword() {
  if (pwForm.value.new_password.length < 8) {
    toast.error('New password must be at least 8 characters')
    return
  }
  if (pwForm.value.new_password !== pwForm.value.confirm) {
    toast.error('New password and confirmation do not match')
    return
  }
  changingPw.value = true
  try {
    await api.post('/auth/change-password', {
      current_password: pwForm.value.current_password,
      new_password: pwForm.value.new_password,
    })
    toast.success('Password changed')
    pwForm.value = { current_password: '', new_password: '', confirm: '' }
  } catch (err) {
    toast.error('Failed to change password: ' + (err as Error).message)
  } finally {
    changingPw.value = false
  }
}

async function startTotpSetup() {
  totp.value.setting = true
  try {
    const res = await api.post<{ qr_code: string; secret: string }>('/auth/2fa/setup', {})
    totp.value.qr = res.qr_code
    totp.value.secret = res.secret
  } catch (err) {
    totp.value.setting = false
    toast.error('Failed to start 2FA setup: ' + (err as Error).message)
  }
}

async function confirmTotpSetup() {
  if (totp.value.code.length !== 6) {
    toast.error('Enter the 6-digit code from your authenticator')
    return
  }
  try {
    await api.post('/auth/2fa/verify', { code: totp.value.code })
    await auth.validateSession()
    toast.success('Two-factor authentication enabled')
    totp.value = { qr: '', secret: '', code: '', setting: false }
  } catch (err) {
    toast.error('Invalid code — try again: ' + (err as Error).message)
  }
}

function cancelTotpSetup() {
  totp.value = { qr: '', secret: '', code: '', setting: false }
}

async function confirmDisable2fa() {
  if (disable2fa.value.code.length !== 6) {
    toast.error('Enter your current 6-digit code to disable 2FA')
    return
  }
  disable2fa.value.busy = true
  try {
    await api.post('/auth/2fa/disable', { code: disable2fa.value.code })
    await auth.validateSession()
    toast.success('Two-factor authentication disabled')
    disable2fa.value = { open: false, code: '', busy: false }
  } catch (err) {
    toast.error('Failed to disable 2FA: ' + (err as Error).message)
  } finally {
    disable2fa.value.busy = false
  }
}

async function loadApiKeys() {
  loadingKeys.value = true
  try {
    apiKeys.value = await api.get<ApiKeyRow[]>('/api-keys')
  } catch (err) {
    toast.error('Failed to load API keys: ' + (err as Error).message)
  } finally {
    loadingKeys.value = false
  }
}

async function createApiKey() {
  if (!newKeyName.value.trim()) {
    toast.error('Give the key a name')
    return
  }
  creatingKey.value = true
  createdKey.value = null
  try {
    const res = await api.post<{ plaintext_key: string }>('/api-keys', {
      name: newKeyName.value.trim(),
    })
    createdKey.value = res.plaintext_key
    newKeyName.value = ''
    await loadApiKeys()
  } catch (err) {
    toast.error('Failed to create API key: ' + (err as Error).message)
  } finally {
    creatingKey.value = false
  }
}

async function revokeApiKey(id: string) {
  try {
    await api.del(`/api-keys/${id}`)
    toast.success('API key revoked')
    await loadApiKeys()
  } catch (err) {
    toast.error('Failed to revoke key: ' + (err as Error).message)
  }
}

function copyKey(value: string) {
  navigator.clipboard?.writeText(value)
  toast.success('Copied to clipboard')
}

onMounted(() => {
  loadForms()
  loadApiKeys()
})

const tabItems = [
  { value: 'account', label: 'Account', icon: 'user' },
  { value: 'security', label: 'Security', icon: 'shield' },
  { value: 'api', label: 'API', icon: 'code' },
  { value: 'license', label: 'License', icon: 'key' },
  { value: 'domain', label: 'Domain', icon: 'globe' },
  { value: 'public', label: 'Public status', icon: 'eye' },
]

const swaggerUrl = '/api/docs'
function openApiDocs() {
  window.open(swaggerUrl, '_blank', 'noopener')
}
</script>

<template>
  <div class="settings">
    <!-- Page head -->
    <div class="page__head">
      <div>
        <div class="t-eyebrow">Management</div>
        <h1 class="page__title">Settings</h1>
      </div>
    </div>

    <!-- Section tabs -->
    <Tabs v-model="section" :items="tabItems" />

    <!-- Account -->
    <Panel v-if="section === 'account'" title="Account details" eyebrow="Identity">
      <template #actions>
        <Button size="sm" :loading="saving" icon="save" @click="saveAccount">Save</Button>
      </template>
      <div class="form-grid">
        <Input
          v-model="accountForm.username"
          label="Username"
          placeholder="your-handle"
          :required="true"
        />
        <Input
          v-model="accountForm.email"
          label="Email"
          type="email"
          placeholder="you@example.com"
          :required="true"
        />
      </div>
      <div class="totp-row">
        <span class="field-label">2FA status</span>
        <Badge
          :tone="auth.user?.totp_enabled ? 'online' : 'warn'"
          :dot="true"
        >
          {{ auth.user?.totp_enabled ? 'Enabled' : 'Not configured' }}
        </Badge>
        <span class="totp-hint">Manage in the Security tab</span>
      </div>
    </Panel>

    <!-- Security -->
    <Panel v-if="section === 'security'" title="Security" eyebrow="Password &amp; 2FA">
      <div class="sec-stack">
        <!-- Change password -->
        <div class="sec-block">
          <h3 class="sec-title">Change password</h3>
          <div class="pw-grid">
            <Input v-model="pwForm.current_password" type="password" label="Current password" placeholder="••••••••" />
            <Input v-model="pwForm.new_password" type="password" label="New password" placeholder="At least 8 characters" />
            <Input v-model="pwForm.confirm" type="password" label="Confirm new password" placeholder="Re-enter new password" />
          </div>
          <Button size="sm" icon="save" :loading="changingPw" @click="changePassword">Update password</Button>
        </div>

        <!-- Two-factor authentication -->
        <div class="sec-block">
          <div class="sec-head">
            <h3 class="sec-title">Two-factor authentication</h3>
            <Badge :tone="auth.user?.totp_enabled ? 'online' : 'warn'" :dot="true">
              {{ auth.user?.totp_enabled ? 'Enabled' : 'Not configured' }}
            </Badge>
          </div>

          <!-- Enabled -> offer disable -->
          <template v-if="auth.user?.totp_enabled">
            <p class="sec-note">Your account is protected with an authenticator app.</p>
            <Button v-if="!disable2fa.open" size="sm" variant="danger" icon="shield-off" @click="disable2fa.open = true">
              Disable 2FA
            </Button>
            <div v-else class="twofa-confirm">
              <p class="sec-note">Enter your current 6-digit code to confirm.</p>
              <Input v-model="disable2fa.code" label="Authenticator code" placeholder="123456" />
              <div class="btn-row">
                <Button size="sm" variant="danger" :loading="disable2fa.busy" @click="confirmDisable2fa">Confirm disable</Button>
                <Button size="sm" variant="ghost" @click="disable2fa.open = false">Cancel</Button>
              </div>
            </div>
          </template>

          <!-- Not enabled -> enrollment -->
          <template v-else>
            <p class="sec-note">Add a second factor with an authenticator app (Google Authenticator, Authy, 1Password).</p>
            <Button v-if="!totp.setting" size="sm" icon="shield" @click="startTotpSetup">Enable 2FA</Button>
            <div v-else class="twofa-enroll">
              <div v-if="totp.qr" class="qr-wrap">
                <img :src="totp.qr" alt="2FA QR code" class="qr-img" />
                <div class="qr-side">
                  <p class="sec-note">Scan with your authenticator app, or enter the secret manually:</p>
                  <code class="secret">{{ totp.secret }}</code>
                </div>
              </div>
              <Input v-model="totp.code" label="Enter the 6-digit code to confirm" placeholder="123456" />
              <div class="btn-row">
                <Button size="sm" icon="check" @click="confirmTotpSetup">Verify &amp; enable</Button>
                <Button size="sm" variant="ghost" @click="cancelTotpSetup">Cancel</Button>
              </div>
            </div>
          </template>
        </div>
      </div>
    </Panel>

    <!-- API access -->
    <Panel v-if="section === 'api'" title="API access" eyebrow="Programmatic">
      <template #actions>
        <Button size="sm" variant="secondary" icon="book-open" icon-right="external-link" @click="openApiDocs">API docs</Button>
      </template>
      <div class="api-stack">
        <p class="section-note">
          Create a key to call the Corrosion REST API from your own tooling. Send it as
          <code class="inline-code">Authorization: Bearer corr_…</code> — a key acts as the license owner.
          The full key is shown once at creation.
        </p>

        <!-- Create -->
        <div class="key-create">
          <Input v-model="newKeyName" label="New key name" placeholder="e.g. CI deploy, monitoring" style="flex:1" />
          <Button size="sm" icon="plus" :loading="creatingKey" @click="createApiKey">Create key</Button>
        </div>

        <!-- Just-created plaintext key (shown once) -->
        <div v-if="createdKey" class="key-reveal">
          <div class="key-reveal__head">
            <span class="field-label">Copy your key now — it won't be shown again</span>
            <Button size="sm" variant="ghost" icon="copy" @click="copyKey(createdKey!)">Copy</Button>
          </div>
          <code class="key-reveal__value">{{ createdKey }}</code>
        </div>

        <!-- Existing keys -->
        <div v-if="loadingKeys" class="key-empty">Loading…</div>
        <div v-else-if="apiKeys.length === 0" class="key-empty">No API keys yet.</div>
        <table v-else class="key-table">
          <thead>
            <tr><th>Name</th><th>Prefix</th><th>Last used</th><th>Status</th><th></th></tr>
          </thead>
          <tbody>
            <tr v-for="k in apiKeys" :key="k.id">
              <td>{{ k.name }}</td>
              <td><code class="field-mono">corr_{{ k.key_prefix }}…</code></td>
              <td>{{ k.last_used_at ? new Date(k.last_used_at).toLocaleString() : 'Never' }}</td>
              <td>
                <Badge :tone="k.is_active ? 'online' : 'offline'">{{ k.is_active ? 'Active' : 'Revoked' }}</Badge>
              </td>
              <td class="key-actions">
                <Button v-if="k.is_active" size="sm" variant="danger-soft" icon="trash-2" @click="revokeApiKey(k.id)">Revoke</Button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </Panel>

    <!-- License -->
    <Panel v-if="section === 'license'" title="License information" eyebrow="Subscription">
      <div class="lic-grid">
        <div class="lic-field">
          <span class="field-label">License key</span>
          <span class="field-mono">{{ auth.license?.license_key ?? '—' }}</span>
        </div>
        <div class="lic-field">
          <span class="field-label">Status</span>
          <Badge
            :tone="auth.license?.status === 'active' ? 'online' : auth.license?.status === 'suspended' ? 'warn' : 'offline'"
          >
            {{ auth.license?.status ?? 'Unknown' }}
          </Badge>
        </div>
        <div class="lic-field">
          <span class="field-label">Expires</span>
          <span class="field-value">
            {{ auth.license?.expires_at ? new Date(auth.license.expires_at).toLocaleDateString() : 'Never' }}
          </span>
        </div>
        <div class="lic-field">
          <span class="field-label">Server name</span>
          <span class="field-value">{{ auth.license?.server_name ?? 'Not set' }}</span>
        </div>
        <div class="lic-field">
          <span class="field-label">Webstore</span>
          <Badge :tone="auth.license?.webstore_active ? 'online' : 'neutral'">
            {{ auth.license?.webstore_active ? 'Active' : 'Inactive' }}
          </Badge>
        </div>
        <div class="lic-field">
          <span class="field-label">Modules</span>
          <span class="field-mono">{{ auth.license?.modules_enabled?.length ?? 0 }} enabled</span>
        </div>
      </div>
    </Panel>

    <!-- Domain -->
    <Panel v-if="section === 'domain'" title="Domain &amp; subdomain" eyebrow="Routing">
      <template #actions>
        <Button size="sm" :loading="saving" icon="save" @click="saveDomain">Save</Button>
      </template>
      <div class="domain-stack">
        <div class="cc-field">
          <span class="cc-field__label">Subdomain</span>
          <div class="subdomain-row">
            <Input
              v-model="domainForm.subdomain"
              placeholder="my-server"
              style="flex: 1"
            />
            <span class="subdomain-suffix">.corrosionmgmt.com</span>
          </div>
        </div>
        <Input
          v-model="domainForm.custom_domain"
          label="Custom domain"
          placeholder="panel.myserver.com"
          hint="Point a CNAME record to panel.corrosionmgmt.com"
        />
      </div>
    </Panel>

    <!-- Public status page -->
    <Panel v-if="section === 'public'" title="Public status page" eyebrow="Visibility">
      <template #actions>
        <Button size="sm" :loading="saving" icon="save" @click="savePublicSite">Save</Button>
      </template>
      <div class="public-stack">
        <p class="section-note">
          Showcase your server on the public Corrosion status page at
          <a href="https://status.corrosionmgmt.com" target="_blank" class="link">status.corrosionmgmt.com</a>.
        </p>

        <div class="toggle-row">
          <div>
            <p class="toggle-label">Show on status page</p>
            <p class="toggle-desc">Display your server publicly with live stats</p>
          </div>
          <Switch v-model="publicSiteForm.show_on_status_page" />
        </div>

        <div class="cc-field">
          <span class="cc-field__label">Description <span class="optional">(optional)</span></span>
          <textarea
            v-model="publicSiteForm.status_page_description"
            placeholder="Friendly 10x modded server with custom plugins..."
            rows="3"
            class="cc-textarea"
          />
          <span class="cc-field__hint">Brief description shown on the status page</span>
        </div>
      </div>
    </Panel>
  </div>
</template>

<style scoped>
.settings {
  max-width: 860px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.page__head { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
.page__title { font-size: var(--text-3xl); font-weight: 700; letter-spacing: -0.02em; color: var(--text-primary); margin-top: 5px; }

/* Account tab */
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.totp-row { display: flex; align-items: center; gap: 10px; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border-subtle); }

/* License tab */
.lic-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px 24px; }
.lic-field { display: flex; flex-direction: column; gap: 5px; }

/* Domain tab */
.domain-stack { display: flex; flex-direction: column; gap: 14px; }
.subdomain-row { display: flex; align-items: center; gap: 0; }
.subdomain-suffix {
  display: flex; align-items: center;
  height: var(--control-h-md); padding: 0 11px;
  background: var(--surface-raised-2); color: var(--text-muted);
  font-family: var(--font-mono); font-size: var(--text-xs);
  border-radius: 0 var(--radius-md) var(--radius-md) 0;
  box-shadow: var(--ring-default);
  white-space: nowrap; flex: none;
}
/* Remove the right-radius from the preceding Input's inner element */
.subdomain-row :deep(.cc-input) { border-radius: var(--radius-md) 0 0 var(--radius-md); }

/* Public status tab */
.public-stack { display: flex; flex-direction: column; gap: 16px; }
.section-note { font-size: var(--text-sm); color: var(--text-tertiary); margin: 0; }
.link { color: var(--accent-text); text-decoration: none; }
.link:hover { text-decoration: underline; }
.toggle-row {
  display: flex; align-items: center; justify-content: space-between; gap: 16px;
  padding: 13px 14px;
  background: var(--surface-raised-2); border-radius: var(--radius-md); box-shadow: var(--ring-default);
}
.toggle-label { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); margin: 0; }
.toggle-desc { font-size: var(--text-xs); color: var(--text-tertiary); margin: 3px 0 0; }

/* Shared field helpers */
.field-label { font-size: var(--text-xs); font-weight: 600; color: var(--text-secondary); }
.field-mono { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--text-primary); font-variant-numeric: tabular-nums; }
.field-value { font-size: var(--text-sm); color: var(--text-primary); }
.optional { font-weight: 400; color: var(--text-muted); }

/* Textarea (no DS component for textarea — minimal consistent styling) */
.cc-textarea {
  width: 100%; padding: 9px 11px; resize: vertical;
  background: var(--surface-inset); color: var(--text-primary);
  border: 0; border-radius: var(--radius-md); box-shadow: var(--ring-default);
  font-family: var(--font-sans); font-size: var(--text-sm); line-height: 1.5;
  outline: 0; transition: var(--transition-colors);
  box-sizing: border-box;
}
.cc-textarea::placeholder { color: var(--text-muted); }
.cc-textarea:focus { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }

.totp-hint { font-size: var(--text-xs); color: var(--text-muted); margin-left: auto; }

/* Security tab */
.sec-stack { display: flex; flex-direction: column; gap: 22px; }
.sec-block { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
.sec-block + .sec-block { padding-top: 20px; border-top: 1px solid var(--border-subtle); }
.sec-head { display: flex; align-items: center; gap: 10px; }
.sec-title { font-size: var(--text-sm); font-weight: 600; color: var(--text-primary); margin: 0; }
.sec-note { font-size: var(--text-sm); color: var(--text-tertiary); margin: 0; max-width: 60ch; }
.pw-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; width: 100%; }
.btn-row { display: flex; gap: 8px; }
.twofa-enroll, .twofa-confirm { display: flex; flex-direction: column; gap: 12px; width: 100%; max-width: 420px; }
.qr-wrap { display: flex; gap: 16px; align-items: center; }
.qr-img { width: 148px; height: 148px; border-radius: var(--radius-md); background: #fff; padding: 6px; flex: none; }
.qr-side { display: flex; flex-direction: column; gap: 8px; }
.secret { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-primary);
  background: var(--surface-inset); padding: 6px 9px; border-radius: var(--radius-sm); word-break: break-all; }

/* API tab */
.api-stack { display: flex; flex-direction: column; gap: 16px; }
.inline-code, .field-mono code, code.inline-code { font-family: var(--font-mono); font-size: var(--text-xs);
  background: var(--surface-inset); padding: 1px 5px; border-radius: var(--radius-sm); color: var(--text-primary); }
.key-create { display: flex; gap: 10px; align-items: flex-end; }
.key-reveal { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px;
  background: var(--surface-raised-2); border-radius: var(--radius-md); box-shadow: var(--ring-default); }
.key-reveal__head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.key-reveal__value { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--accent-text);
  word-break: break-all; }
.key-empty { font-size: var(--text-sm); color: var(--text-muted); padding: 12px 0; }
.key-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
.key-table th { text-align: left; font-size: var(--text-xs); font-weight: 600; color: var(--text-secondary);
  padding: 6px 10px; border-bottom: 1px solid var(--border-subtle); }
.key-table td { padding: 9px 10px; border-bottom: 1px solid var(--border-subtle); color: var(--text-primary); vertical-align: middle; }
.key-actions { text-align: right; }

@media (max-width: 680px) {
  .form-grid { grid-template-columns: 1fr; }
  .lic-grid { grid-template-columns: 1fr 1fr; }
  .pw-grid { grid-template-columns: 1fr; }
}
</style>
