<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useSettingsStore, PROVIDER_CONFIG, type AIProvider } from '@/stores/settings'
import { useAuthStore } from '@/stores/auth'
import { getAllPromptKeys, getPrompt, savePrompt, resetPrompt, type PromptKey } from '@/services/prompts-db'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { getWebhookUrl, setWebhookUrl, sendTestMessage } from '@/services/teams'
import {
  Brain,
  Key,
  CheckCircle2,
  XCircle,
  ExternalLink,
  Info,
  LogOut,
  Sparkles,
  ChevronRight,
  MessageSquare,
} from 'lucide-vue-next'

const { t } = useI18n()
const settings = useSettingsStore()
const auth = useAuthStore()

// ─── Prompt editor ────────────────────────────────────
const promptKeys = getAllPromptKeys()
const promptContents = ref<Record<string, string>>({})
const promptSaving = ref<Record<string, boolean>>({})
const promptDirty = ref<Record<string, boolean>>({})

async function loadPrompts() {
  for (const { key } of promptKeys) {
    promptContents.value[key] = await getPrompt(key)
  }
}

async function savePromptHandler(key: PromptKey) {
  promptSaving.value[key] = true
  try {
    await savePrompt(key, promptContents.value[key])
    promptDirty.value[key] = false
  } catch (e: any) {
    console.error('[Alpha] Error saving prompt:', e)
  } finally {
    promptSaving.value[key] = false
  }
}

async function resetPromptHandler(key: PromptKey) {
  await resetPrompt(key)
  promptContents.value[key] = await getPrompt(key)
  promptDirty.value[key] = false
}

function markDirty(key: string) {
  promptDirty.value[key] = true
}

onMounted(loadPrompts)

// ─── Teams ───────────────────────────────────────────
const teamsUrl = ref(getWebhookUrl())
const teamsSending = ref(false)
const teamsStatus = ref<'idle' | 'ok' | 'error'>('idle')
const teamsStatusMsg = ref('')

function teamsUrlChanged() {
  setWebhookUrl(teamsUrl.value)
  teamsStatus.value = 'idle'
}

async function testTeams() {
  teamsSending.value = true
  teamsStatus.value = 'idle'
  teamsStatusMsg.value = ''
  try {
    const ok = await sendTestMessage()
    teamsStatus.value = ok ? 'ok' : 'error'
    teamsStatusMsg.value = ok ? 'Mensaje enviado a Teams' : 'Error al enviar. Verifica la URL del webhook.'
  } catch (e: any) {
    teamsStatus.value = 'error'
    teamsStatusMsg.value = e.message
  } finally {
    teamsSending.value = false
  }
}

const newKey = ref('')
const keySaved = ref(false)

const providers: AIProvider[] = ['openrouter', 'minimax', 'opencode']

function handleSaveKey() {
  if (newKey.value.trim()) {
    settings.saveApiKey(newKey.value.trim())
    newKey.value = ''
    keySaved.value = true
    setTimeout(() => { keySaved.value = false }, 3000)
  }
}

function handleRemoveKey() {
  settings.removeKey()
  keySaved.value = false
}

const tierColors: Record<string, string> = {
  free: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
  cheap: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  premium: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
}
</script>

<template>
  <div class="@container/main flex flex-1 flex-col gap-4 px-4 lg:px-6 py-4 max-w-3xl">
    <div>
      <h1 class="text-2xl font-bold tracking-tight">{{ t('settings.title') }}</h1>
      <p class="text-sm text-muted-foreground mt-1">{{ t('settings.subtitle') }}</p>
    </div>

    <!-- AI Provider Configuration -->
    <Card id="settings-ai-provider">
      <CardHeader>
        <CardTitle class="text-sm font-medium flex items-center gap-2">
          <Brain class="size-4" />
          {{ t('settings.aiProvider') }}
        </CardTitle>
        <CardDescription class="text-xs">{{ t('settings.aiProviderDesc') }}</CardDescription>
      </CardHeader>
      <CardContent class="space-y-3">
        <div
          v-for="p in providers"
          :key="p"
          :id="`settings-provider-${p}`"
          class="flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors"
          :class="settings.provider === p ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'"
          @click="settings.setActiveProvider(p)"
        >
          <div class="flex size-4 mt-0.5 shrink-0">
            <div
              class="size-4 rounded-full border-2 flex items-center justify-center"
              :class="settings.provider === p ? 'border-primary' : 'border-muted-foreground'"
            >
              <div v-if="settings.provider === p" class="size-2 rounded-full bg-primary" />
            </div>
          </div>
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium">{{ PROVIDER_CONFIG[p].label }}</span>
              <Badge
                v-if="PROVIDER_CONFIG[p].badgeKey"
                variant="outline"
                class="text-[10px]"
              >{{ t(PROVIDER_CONFIG[p].badgeKey!) }}</Badge>
              <Badge
                v-if="p === 'minimax'"
                variant="secondary"
                class="text-[10px]"
              >Nuevo</Badge>
            </div>
            <p class="text-xs text-muted-foreground mt-0.5">{{ t(PROVIDER_CONFIG[p].descKey) }}</p>
          </div>
          <ChevronRight
            class="size-4 shrink-0 mt-1"
            :class="settings.provider === p ? 'text-primary' : 'text-muted-foreground'"
          />
        </div>

        <Separator />

        <!-- API Key (for direct providers) -->
        <div v-if="settings.provider !== 'opencode'" id="settings-api-key" class="space-y-3">
          <Label class="text-sm font-medium">{{ PROVIDER_CONFIG[settings.provider].label }} API Key</Label>

          <div v-if="settings.apiKeyConfigured" class="flex items-center gap-2 text-sm">
            <CheckCircle2 class="size-4 text-green-500 shrink-0" />
            <span class="text-green-600 dark:text-green-400">{{ t('settings.keyConfigured') }}</span>
            <Button variant="ghost" size="sm" class="text-xs h-7 ml-auto" @click="handleRemoveKey">
              <XCircle class="size-3 mr-1" />
              {{ t('settings.removeKey') }}
            </Button>
          </div>

          <div v-else class="flex gap-2">
            <Input
              v-model="newKey"
              type="password"
              :placeholder="t('settings.apiKeyPlaceholder')"
              class="flex-1 font-mono text-xs"
            />
            <Button @click="handleSaveKey" :disabled="!newKey.trim()">
              {{ t('settings.saveKey') }}
            </Button>
          </div>

          <p v-if="keySaved" class="text-xs text-green-600 dark:text-green-400 flex items-center gap-1">
            <CheckCircle2 class="size-3" />
            {{ t('settings.keySaved') }}
          </p>

          <div class="text-xs text-muted-foreground space-y-1">
            <p>{{ t(PROVIDER_CONFIG[settings.provider].apiKeyHelp) }}</p>
            <a
              v-if="PROVIDER_CONFIG[settings.provider].apiKeyLink"
              :href="PROVIDER_CONFIG[settings.provider].apiKeyLink"
              target="_blank"
              class="inline-flex items-center gap-1 text-primary hover:underline"
            >
              {{ PROVIDER_CONFIG[settings.provider].apiKeyLink }}
              <ExternalLink class="size-3" />
            </a>
          </div>
        </div>

        <!-- MiniMax Group ID -->
        <div v-if="settings.provider === 'minimax'" id="settings-minimax-group" class="space-y-2 pt-2">
          <Label class="text-sm font-medium">{{ t('settings.minimaxGroupId') }}</Label>
          <div class="flex gap-2">
            <Input
              v-model="settings.minimaxGroupId"
              :placeholder="t('settings.minimaxGroupIdPlaceholder')"
              class="flex-1 font-mono text-xs"
              @update:model-value="settings.saveMinimaxGroupId(String($event))"
            />
          </div>
          <div class="text-xs text-muted-foreground space-y-1">
            <p>{{ t('settings.minimaxGroupIdHelp') }}</p>
            <a
              href="https://platform.minimaxi.com/user-center/basic-information/interface-key"
              target="_blank"
              class="inline-flex items-center gap-1 text-primary hover:underline"
            >
              platform.minimaxi.com
              <ExternalLink class="size-3" />
            </a>
          </div>
        </div>

        <!-- OpenCode info -->
        <div v-if="settings.provider === 'opencode'" id="settings-opencode-info" class="space-y-2 text-sm">
          <div class="flex items-start gap-2 p-3 rounded-lg bg-muted/50">
            <Info class="size-4 text-muted-foreground mt-0.5 shrink-0" />
            <div class="space-y-1">
              <p class="font-medium">{{ t('settings.opencodeInfoTitle') }}</p>
              <p class="text-xs text-muted-foreground">{{ t('settings.opencodeInfoDesc') }}</p>
              <code class="block text-xs bg-muted px-2 py-1 rounded mt-1">~/.local/share/opencode/auth.json</code>
              <p class="text-xs text-muted-foreground mt-1">{{ t('settings.opencodeInfoFuture') }}</p>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- Model Selection (only for direct providers with models) -->
    <Card
      v-if="settings.allModelsForProvider.length > 0"
      id="settings-model-select"
    >
      <CardHeader>
        <CardTitle class="text-sm font-medium flex items-center gap-2">
          <Sparkles class="size-4" />
          {{ t('settings.model') }}
        </CardTitle>
        <CardDescription class="text-xs">{{ t('settings.modelDesc') }}</CardDescription>
      </CardHeader>
      <CardContent class="space-y-4">
        <template v-for="(models, tier) in { free: settings.freeModels, cheap: settings.cheapModels, premium: settings.premiumModels }" :key="tier">
          <div v-if="models.length > 0">
            <Label class="text-xs text-muted-foreground uppercase tracking-wider font-semibold mb-2 block">
              {{ t(`settings.${tier}Models`) }}
            </Label>
            <div class="grid gap-2">
              <div
                v-for="m in models"
                :key="m.id"
                class="flex items-center gap-3 p-2 rounded-lg border cursor-pointer transition-colors"
                :class="settings.modelId === m.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'"
                @click="settings.setModel(m.id)"
              >
                <div class="flex size-3 shrink-0">
                  <div
                    class="size-3 rounded-full border-2"
                    :class="settings.modelId === m.id ? 'border-primary bg-primary' : 'border-muted-foreground'"
                  />
                </div>
                <div class="flex-1 min-w-0">
                  <span class="text-sm">{{ m.label }}</span>
                  <code class="block text-[10px] text-muted-foreground font-mono truncate">{{ m.id }}</code>
                </div>
                <Badge variant="outline" :class="tierColors[tier]" class="text-[10px] capitalize">{{ tier }}</Badge>
              </div>
            </div>
          </div>
        </template>

        <div v-if="settings.selectedModel" class="flex items-center gap-2 p-2 rounded-lg bg-muted/30 text-xs text-muted-foreground">
          <CheckCircle2 class="size-3 text-green-500 shrink-0" />
          {{ t('settings.currentModel') }}: <code class="font-mono text-foreground">{{ settings.modelId }}</code>
        </div>
      </CardContent>
    </Card>

    <!-- Teams -->
    <Card id="settings-teams">
      <CardHeader>
        <CardTitle class="text-sm font-medium flex items-center gap-2">
          <MessageSquare class="size-4" />
          Microsoft Teams
        </CardTitle>
        <CardDescription class="text-xs">
          Configurá un webhook para recibir notificaciones de Alpha en Teams.
        </CardDescription>
      </CardHeader>
      <CardContent class="space-y-3">
        <div class="space-y-1.5">
          <Label class="text-xs font-medium">URL del Webhook</Label>
          <Input
            v-model="teamsUrl"
            placeholder="https://...office.com/webhookb2/..."
            class="text-xs font-mono"
            @input="teamsUrlChanged"
          />
          <p class="text-[10px] text-muted-foreground">
            Creá un webhook en Teams: Canal → ... → Conectores → Webhook entrante
          </p>
        </div>
        <div v-if="teamsUrl" class="flex items-center gap-2">
          <Button size="sm" variant="outline" class="text-xs" :disabled="teamsSending" @click="testTeams">
            {{ teamsSending ? 'Enviando...' : 'Enviar prueba' }}
          </Button>
          <span v-if="teamsStatus === 'ok'" class="text-xs text-green-600 flex items-center gap-1">
            <CheckCircle2 class="size-3" /> {{ teamsStatusMsg }}
          </span>
          <span v-if="teamsStatus === 'error'" class="text-xs text-red-600 flex items-center gap-1">
            <XCircle class="size-3" /> {{ teamsStatusMsg }}
          </span>
        </div>
      </CardContent>
    </Card>

    <!-- Prompts -->
    <Card id="settings-prompts" class="border-dashed">
      <CardHeader>
        <CardTitle class="text-sm font-medium flex items-center gap-2">
          <Sparkles class="size-4" />
          Prompts de IA
        </CardTitle>
        <CardDescription class="text-xs">
          Editá los prompts que usa la IA para cada función. Los cambios se aplican inmediatamente.
        </CardDescription>
      </CardHeader>
      <CardContent class="space-y-4">
        <div v-for="{ key, label } in promptKeys" :key="key" class="space-y-1.5">
          <div class="flex items-center justify-between">
            <Label class="text-xs font-medium">{{ label }}</Label>
            <div class="flex gap-1">
              <Button
                v-if="promptDirty[key]"
                size="sm"
                variant="default"
                class="text-xs h-6 px-2"
                :disabled="promptSaving[key]"
                @click="savePromptHandler(key as PromptKey)"
              >
                {{ promptSaving[key] ? 'Guardando...' : 'Guardar' }}
              </Button>
              <Button
                size="sm"
                variant="ghost"
                class="text-xs h-6 px-2 text-muted-foreground"
                @click="resetPromptHandler(key as PromptKey)"
              >
                Restaurar
              </Button>
            </div>
          </div>
          <textarea
            :value="promptContents[key]"
            @input="(e: any) => { promptContents[key] = e.target.value; markDirty(key) }"
            class="w-full h-32 rounded-md border border-input bg-background p-2 text-xs font-mono outline-none focus:border-ring focus:ring-1 focus:ring-ring resize-y"
          />
        </div>
      </CardContent>
    </Card>

    <!-- Account -->
    <Card id="settings-account">
      <CardHeader>
        <CardTitle class="text-sm font-medium flex items-center gap-2">
          <Key class="size-4" />
          {{ t('settings.account') }}
        </CardTitle>
      </CardHeader>
      <CardContent class="space-y-3">
        <div class="text-sm">
          <span class="text-muted-foreground">{{ t('settings.loggedInAs') }}:</span>
          <span class="font-medium ml-1">{{ auth.user?.name || '—' }}</span>
          <code class="ml-2 text-xs text-muted-foreground">{{ auth.user?.email || '' }}</code>
        </div>
        <Button variant="outline" size="sm" @click="auth.logout()">
          <LogOut class="size-3 mr-1" />
          {{ t('settings.logout') }}
        </Button>
      </CardContent>
    </Card>
  </div>
</template>
