<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useAdminConfigStore } from '@/store/adminConfigStore'
import type { AdminConfig } from '@/types/admin-config'
import { API } from '@/Api'
import { Textarea } from '@/components/ui/textarea'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { Alert, AlertTitle } from '@/components/ui/alert'
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
} from '@/components/ui/select'
import AlertDescription from '../ui/alert/AlertDescription.vue'

const store = useAdminConfigStore()

type LLMOption = { id: string; name: string; type: string }
const availableTextModels = ref<LLMOption[]>([])
const loading = ref(false)

function updateDraft(mutator: (cfg: AdminConfig) => void) {
  if (!store.draft) return
  const next = JSON.parse(JSON.stringify(store.draft)) as AdminConfig
  mutator(next)
  store.draft = next
}

const agentHubLLM = computed({
  get: () => store.draft?.agentHubLLM ?? '',
  set: (v: string) => {
    updateDraft((cfg) => {
      cfg.agentHubLLM = v || undefined
    })
  },
})

const agentHubInstructions = computed({
  get: () => store.draft?.agentHubOptionalInstructions ?? '',
  set: (v: string) => {
    updateDraft((cfg) => {
      cfg.agentHubOptionalInstructions = v
    })
  },
})

const orchestrationMode = computed({
  get: () => store.draft?.orchestrationMode ?? 'tools',
  set: (v: string) => {
    updateDraft((cfg) => {
      cfg.orchestrationMode = v as 'tools' | 'manual'
    })
  },
})

const logsLevel = computed({
  get: () => store.draft?.logsLevel ?? 'info',
  set: (v: string) => {
    updateDraft((cfg) => {
      cfg.logsLevel = v as 'info' | 'debug'
    })
  },
})

const permanentlyDeleteMessages = computed({
  get: () => !!store.draft?.permanentlyDeleteMessages,
  set: (v: boolean) => {
    updateDraft((cfg) => {
      cfg.permanentlyDeleteMessages = v
    })
  },
})

const textModelsByType = computed(() => {
  const grouped: Record<string, LLMOption[]> = {}
  availableTextModels.value.forEach((model) => {
    if (!grouped[model.type]) {
      grouped[model.type] = []
    }
    grouped[model.type].push(model)
  })
  return grouped
})

onMounted(async () => {
  loading.value = true
  try {
    const { data } = await API.listAvailableLLMs()
    availableTextModels.value = data?.textCompletionModels ?? []
  } finally {
    loading.value = false
  }
})

const missing = (v?: string) => !v || !v.trim()
</script>

<template>
  <div class="space-y-6">
    <div class="border rounded-lg admin-collapsible-card">
      <div class="px-4 py-3">
        <h3 class="text-lg font-semibold admin-subsection-title">Agent Hub LLM</h3>
        <p class="admin-field-description">
          Model used internally by Agent Hub (orchestration, titles generation, etc.)
        </p>
      </div>

      <div class="px-4 pb-4">
        <Separator class="mb-4" />

        <div class="space-y-4 max-w-3xl">
          <div id="field-agentHubLLM">
            <label class="admin-field-label"
              >Choose the LLM model to use<span class="text-red-600">*</span>
            </label>
            <div class="w-full lg:w-[256px]">
              <Select v-model="agentHubLLM">
                <SelectTrigger
                  class="w-full admin-select-trigger"
                  :class="[missing(agentHubLLM) ? 'border-red-500' : '', 'admin-dropdown-trigger']"
                >
                  <SelectValue placeholder="Select a model" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <template v-for="(models, type) in textModelsByType" :key="type">
                    <SelectLabel class="admin-select-label text-xs font-semibold px-2 py-1.5">
                      {{ type }}
                    </SelectLabel>
                    <SelectGroup>
                      <SelectItem
                        v-for="model in models"
                        :key="model.id"
                        :value="model.id"
                        class="pl-6 admin-select-item"
                      >
                        {{ model.name }}
                      </SelectItem>
                    </SelectGroup>
                  </template>
                </SelectContent>
              </Select>
            </div>
            <div v-if="missing(agentHubLLM)" class="text-[11px] mt-1 text-red-600">
              <i class="dku-icon-warning-12 mr-1"></i>LLM is required
            </div>
          </div>

          <div class="max-w-3xl">
            <label class="admin-field-label">Optional instructions for the LLM.</label>
            <Textarea
              v-model="agentHubInstructions"
              rows="3"
              class="w-full !border !border-border rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary text-sm py-2 px-3 resize-y placeholder-muted-foreground min-h-[120px]"
              placeholder="Optional additional instructions"
            />
            <div class="admin-field-description">
              <p>Please note that these instructions apply only when:</p>
              <ul>
                <li>• The conversation involves multiple agents (orchestration)</li>
                <li>• The user is chatting directly with the LLM</li>
              </ul>
            </div>
          </div>

          <Separator />

          <div>
            <label class="admin-field-label">Agents Orchestration Mode</label>
            <div class="w-full lg:w-[256px]">
              <Select v-model="orchestrationMode">
                <SelectTrigger class="w-full admin-select-trigger admin-dropdown-trigger">
                  <SelectValue placeholder="Select mode" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem value="tools" class="admin-select-item">Tools</SelectItem>
                    <SelectItem value="manual" class="admin-select-item">Manual</SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
            <Alert
              variant="info"
              class="admin-alert admin-alert--info py-2 px-3 my-2"
              collapsible
              defaultCollapsed
            >
              <i class="dku-icon-info-circle-outline-16"></i>
              <AlertTitle>
                <div v-if="orchestrationMode === 'tools'">
                  <strong>Tools:</strong> Use this mode when the LLM supports tool calling. Active
                  agents in the conversation are used as callable tools, and it determines how they
                  are coordinated during the conversation.
                </div>
                <div v-else-if="orchestrationMode === 'manual'">
                  <strong>Manual:</strong> Use this mode when the LLM does not support tool calling.
                  Agent Hub manually selects the relevant agents, calls each one once, and combines
                  their outputs into a single response.
                </div>
              </AlertTitle>
              <AlertDescription>
                <p>
                  Depending on the setup<br />
                  <strong>- No active agents:</strong> The user interacts directly with the main
                  LLM.<br />
                  <strong>- One active agent:</strong> The user interacts directly with that
                  agent.<br />
                  <strong>- Multiple active agents:</strong> Agent Hub coordinates interactions
                  between agents to produce the final response.
                </p>
              </AlertDescription>
            </Alert>
          </div>
        </div>
      </div>
    </div>

    <div class="border rounded-lg admin-collapsible-card">
      <div class="px-4 py-3">
        <h3 class="text-lg font-semibold admin-subsection-title">System Settings</h3>
      </div>

      <div class="px-4 pb-4">
        <Separator class="mb-4" />

        <div class="space-y-4 pt-2 max-w-3xl">
          <div>
            <label class="admin-field-label">Choose the verbosity level for system logs</label>
            <div class="w-full lg:w-[256px]">
              <Select v-model="logsLevel">
                <SelectTrigger class="w-full admin-select-trigger admin-dropdown-trigger">
                  <SelectValue placeholder="Select logs level" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem value="info" class="admin-select-item">Info</SelectItem>
                    <SelectItem value="debug" class="admin-select-item">Debug</SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
          </div>

          <Separator />

          <div>
            <div class="flex items-center gap-2">
              <Switch
                class="admin-switch"
                v-model="permanentlyDeleteMessages"
                @update:modelValue="(v: boolean) => (permanentlyDeleteMessages = !!v)"
              />
              <label class="font-medium text-sm cursor-pointer">Permanently delete messages</label>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="text-sm flex">
      <p class="text-red-600 pr-1">*</p>
      fields marked with an asterisk are mandatory for publishing
    </div>
  </div>
</template>
