<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: '',
})

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
  }
}

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

const tabItems = [
  { value: 'account', label: 'Account', icon: 'user' },
  { value: 'license', label: 'License', icon: 'key' },
  { value: 'domain', label: 'Domain', icon: 'globe' },
  { value: 'public', label: 'Public status', icon: 'eye' },
]
</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>
      </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); }

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