<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { chatWithAI } from '@/services/ai'
import { getPrompt } from '@/services/prompts-db'
import { storage } from '@/services/storage'
import { useSettingsStore, AVAILABLE_MODELS, PROVIDER_CONFIG, hasProviderApiKey, type AIProvider } from '@/stores/settings'
import { useWorkItemsStore } from '@/stores/workitems'
import { useUsersStore } from '@/stores/users'
import { getSessionsByProject, getProjectState } from '@/services/transcriptions-db'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Send, Loader2, AlertCircle, Brain, Settings2, Check, ChevronDown } from 'lucide-vue-next'

const { t } = useI18n()
const settings = useSettingsStore()
const workItems = useWorkItemsStore()
const usersStore = useUsersStore()

const props = defineProps({
  projectId: { type: Number, required: true },
  projectName: { type: String, required: true },
  projectDescription: { type: String, default: '' },
  epicCount: { type: Number, required: true },
  huCount: { type: Number, required: true },
})

const emit = defineEmits<{
  'navigate-settings': []
}>()

const prompt = ref('')
const response = ref('')
const loading = ref(false)
const error = ref<string | null>(null)

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

function modelsForProvider(p: AIProvider) {
  return AVAILABLE_MODELS.filter(m => m.provider === p)
}

function switchModel(provider: AIProvider, modelId: string) {
  if (provider !== settings.provider) settings.setActiveProvider(provider)
  settings.setModel(modelId)
}

async function buildContext(): Promise<string> {
  const ctx: Record<string, unknown> = {}

  // 1. Team members asignados a este proyecto
  const teamIds = storage.getJSON<number[]>(`project_team_${props.projectId}`)
  if (teamIds && teamIds.length > 0) {
    const members = teamIds
      .map(id => usersStore.users.find(u => u.id === id))
      .filter(Boolean)
      .map(u => ({
        n: u!.full_name || u!.email,
        r: u!.role || '—',
        c: u!.cell || '—',
      }))
    ctx.team = { count: members.length, members }
  }

  // 2. HUs: todas, con story points, sprint y estado
  const hus = workItems.userStories
  if (hus.length > 0) {
    const pending = hus.filter(h => !['done','completed','closed','finalizado'].includes(String(h.status ?? '').toLowerCase()))
    ctx.hus = {
      total: hus.length,
      pending: pending.length,
      items: hus.map(h => ({
        t: h._cleanTitle || h.title,
        s: h.status,
        p: h.priority,
        sp: h.story_points ?? null,
        sprint: h.sprint ?? null,
      })),
    }
  }

  // 3. Épicas con asignación
  const epics = workItems.epics
  if (epics.length > 0) {
    ctx.epics = epics.map(e => ({
      n: e._cleanName || e.name || e.title,
      s: e.status,
      assigned: e.assigned_name || null,
      sp: e.story_points ?? null,
    }))
  }

  // 4. Sesiones: últimas 3
  const sessions = await getSessionsByProject(props.projectId)
  if (sessions.length > 0) {
    ctx.sessions = { total: sessions.length, recent: sessions.slice(-3).reverse().map(s => ({ d: s.date, t: s.title })) }
  }

  // 5. Estado
  const state = await getProjectState(props.projectId)
  if (state?.summary) ctx.summary = state.summary.slice(0, 300)

  return JSON.stringify(ctx)
}

async function sendPrompt() {
  const text = prompt.value.trim()
  if (!text || loading.value) return

  loading.value = true
  error.value = null
  response.value = ''
  prompt.value = ''

  try {
    const context = await buildContext()
    const rawPrompt = await getPrompt('chat')
    const systemPrompt = rawPrompt
      .replace(/\{\{projectName\}\}/g, props.projectName)
      .replace(/\{\{projectDescription\}\}/g, props.projectDescription || '')
      .replace(/\{\{epicCount\}\}/g, String(props.epicCount))
      .replace(/\{\{huCount\}\}/g, String(props.huCount))

    const msgs = [{ role: 'user' as const, content: `Datos del proyecto:\n${context || '{}'}\n\n${text}` }]
    const result = await chatWithAI(msgs, systemPrompt)
    response.value = result
  } catch (e: any) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <Card id="project-ai-chat">
    <CardHeader class="pb-3 flex flex-row items-center justify-between">
      <CardTitle class="text-sm font-medium flex items-center gap-2">
        <Brain class="size-4" />
        {{ t('projectAi.title') }}
      </CardTitle>
      <div class="flex items-center gap-2">
        <Button
          v-if="!settings.apiKeyConfigured"
          variant="ghost"
          size="sm"
          class="text-xs h-7"
          @click="emit('navigate-settings')"
        >
          <Settings2 class="size-3 mr-1" />
          {{ t('projectAi.configure') }}
        </Button>
        <DropdownMenu v-else>
          <DropdownMenuTrigger as-child>
            <Button variant="outline" size="sm" class="text-xs h-7 gap-1 font-mono">
              {{ settings.selectedModel?.label || settings.modelId }}
              <ChevronDown class="size-3" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" class="w-64">
            <DropdownMenuLabel>{{ t('projectAi.switchModel') }}</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <template v-for="p in allProviders" :key="p">
              <DropdownMenuItem
                v-if="modelsForProvider(p).length > 0"
                class="flex flex-col items-start py-2 cursor-default"
                disabled
              >
                <div class="flex items-center gap-2 w-full">
                  <span class="text-xs font-medium">{{ PROVIDER_CONFIG[p].label }}</span>
                  <Badge v-if="hasProviderApiKey(p)" variant="outline" class="text-[9px] text-green-600 border-green-300 dark:text-green-400 dark:border-green-700">{{ t('projectAi.keyReady') }}</Badge>
                  <Badge v-else variant="outline" class="text-[9px] text-muted-foreground">{{ t('projectAi.noKey') }}</Badge>
                </div>
              </DropdownMenuItem>
              <DropdownMenuItem
                v-for="m in modelsForProvider(p)"
                :key="m.id"
                :disabled="!hasProviderApiKey(p)"
                @click="switchModel(p, m.id)"
                class="flex items-center gap-2 py-1.5 pl-6"
              >
                <Check v-if="settings.provider === p && settings.modelId === m.id" class="size-3.5 text-primary shrink-0" />
                <div v-else class="size-3.5 shrink-0" />
                <span class="text-xs">{{ m.label }}</span>
                <code class="text-[9px] text-muted-foreground ml-auto truncate max-w-[120px]">{{ m.id }}</code>
              </DropdownMenuItem>
              <DropdownMenuSeparator v-if="p !== allProviders[allProviders.length - 1]" />
            </template>
            <DropdownMenuSeparator />
            <DropdownMenuItem class="text-xs text-muted-foreground justify-center" @click="emit('navigate-settings')">
              <Settings2 class="size-3 mr-1" />
              {{ t('projectAi.settings') }}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </CardHeader>
    <CardContent class="space-y-3">
      <div
        v-if="response || loading || error"
        id="project-ai-response"
        class="min-h-[80px] p-3 rounded-lg bg-muted/30 text-sm leading-relaxed whitespace-pre-wrap"
      >
        <div v-if="loading" class="flex items-center gap-2 text-muted-foreground">
          <Loader2 class="size-4 animate-spin" />
          <span>{{ t('projectAi.thinking') }}</span>
        </div>
        <p v-else-if="error" class="text-destructive text-xs flex items-start gap-2">
          <AlertCircle class="size-4 mt-0.5 shrink-0" />
          {{ error }}
        </p>
        <p v-else>{{ response }}</p>
      </div>

      <div
        v-if="!settings.apiKeyConfigured"
        class="text-xs text-muted-foreground p-3 rounded-lg border border-dashed text-center"
      >
        {{ t('projectAi.noKey') }}
        <button class="text-primary hover:underline cursor-pointer" @click="emit('navigate-settings')">{{ t('projectAi.configureLink') }}</button>.
      </div>

      <div class="flex gap-2">
        <textarea
          v-model="prompt"
          :placeholder="t('projectAi.placeholder')"
          class="flex-1 min-h-[40px] max-h-[120px] text-sm rounded-lg border bg-transparent px-3 py-2 resize-none"
          rows="1"
          @keydown.enter.ctrl="sendPrompt"
          @keydown.enter.meta="sendPrompt"
        />
        <Button
          size="icon"
          class="size-10 shrink-0 self-end"
          :disabled="!prompt.trim() || loading || !settings.apiKeyConfigured"
          @click="sendPrompt"
          id="project-ai-send-btn"
        >
          <Loader2 v-if="loading" class="size-4 animate-spin" />
          <Send v-else class="size-4" />
        </Button>
      </div>
      <p class="text-[10px] text-muted-foreground text-right">Ctrl+Enter</p>
    </CardContent>
  </Card>
</template>
