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

const store = useAdminConfigStore()

const availableLLMs = ref<Array<{ id: string; name: string; type?: string }>>([])

async function loadAvailableLLMs() {
  try {
    const { data } = await API.listAvailableLLMs()
    availableLLMs.value = data?.textCompletionModels ?? []
  } catch (error) {
    console.error('Failed to load available LLMs:', error)
    availableLLMs.value = []
  }
}

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 chartsEnabled = computed<boolean>({
  get: () => store.draft?.chartsGenerationMode !== 'disabled',
  set: (v: boolean) => {
    updateDraft((cfg) => {
      cfg.chartsGenerationMode = v ? 'auto' : 'disabled'
    })
  },
})

const generationModes = [
  { value: 'auto', label: 'Auto - Generate charts automatically' },
  { value: 'manual', label: 'Manual - User decides when to generate' },
]

const generationMode = computed({
  get: () => {
    const mode = store.draft?.chartsGenerationMode ?? 'auto'
    return mode === 'disabled' ? 'auto' : mode
  },
  set: (v: string) => {
    updateDraft((cfg) => {
      cfg.chartsGenerationMode = v as 'auto' | 'manual'
    })
  },
})

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

const maxArtifactsSize = computed({
  get: () =>
    store.draft?.chartsMaxArtifactsSize !== undefined
      ? String(store.draft.chartsMaxArtifactsSize)
      : '',
  set: (v: string) => {
    if (v === '') {
      updateDraft((cfg) => {
        cfg.chartsMaxArtifactsSize = undefined
      })
      return
    }
    const num = Math.max(1, Number.parseInt(v, 10))
    updateDraft((cfg) => {
      cfg.chartsMaxArtifactsSize = Number.isFinite(num) ? num : undefined
    })
  },
})

const maxArtifactsSizeError = computed(() => {
  const size = store.draft?.chartsMaxArtifactsSize
  return size === undefined || size === null || isNaN(Number(size)) || Number(size) < 1
})

onMounted(() => {
  loadAvailableLLMs()
})
</script>

<template>
  <div class="space-y-6">
    <div class="border rounded-lg admin-collapsible-card">
      <div class="px-4 py-3 flex items-center justify-between">
        <div class="flex items-center gap-2">
          <Switch
            class="admin-switch"
            v-model="chartsEnabled"
            @update:modelValue="(v: boolean) => (chartsEnabled = !!v)"
          />
          <label class="font-medium text-sm cursor-pointer admin-subsection-title"
            >Enable Charts Generation</label
          >
        </div>
      </div>

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

        <div class="space-y-4 pt-2">
          <div>
            <label class="admin-field-label"> Charts Generation Mode </label>
            <div class="w-full lg:w-[420px]">
              <Select v-model="generationMode">
                <SelectTrigger
                  class="w-full admin-select-trigger"
                  :class="{ 'admin-dropdown-trigger': true }"
                >
                  <SelectValue placeholder="Select generation mode" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem
                      v-for="mode in generationModes"
                      :key="mode.value"
                      :value="mode.value"
                      class="admin-select-item"
                    >
                      {{ mode.label }}
                    </SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
            <p class="admin-field-description">Choose when charts should be generated</p>
          </div>

          <div>
            <label class="admin-field-label"> LLM </label>
            <div class="w-full lg:w-[420px]">
              <Select v-model="textCompletionModel">
                <SelectTrigger
                  class="w-full admin-select-trigger admin-dropdown-trigger"
                  id="field-textCompletionModel"
                >
                  <SelectValue placeholder="Select a model" />
                </SelectTrigger>
                <SelectContent hide-indicator class="admin-select-content">
                  <SelectGroup>
                    <SelectItem
                      v-for="llm in availableLLMs"
                      :key="llm.id"
                      :value="llm.id"
                      class="admin-select-item"
                    >
                      {{ llm.name }}
                    </SelectItem>
                  </SelectGroup>
                  <div v-if="availableLLMs.length === 0" class="admin-select-empty">
                    No models available
                  </div>
                </SelectContent>
              </Select>
            </div>
            <p class="admin-field-description">Model used to generate charts from tabular data</p>
          </div>

          <div class="max-w-3xl">
            <label class="admin-field-label">
              Max Artifacts Size (in MB)<span class="text-red-600">*</span>
            </label>
            <Input
              v-model="maxArtifactsSize"
              inputmode="numeric"
              type="number"
              min="1"
              step="1"
              class="admin-input w-[200px]"
              :class="
                maxArtifactsSizeError
                  ? '!border-red-500 focus:!ring-red-500 focus:!border-red-500'
                  : ''
              "
              id="field-maxArtifactsSize"
            />
            <div v-if="maxArtifactsSizeError" class="text-[11px] mt-1 text-red-600">
              <i class="dku-icon-warning-12 mr-1"></i>Max Artifacts Size must be an integer ≥ 1
            </div>
            <p class="admin-field-description">
              Maximum size of data artifacts for chart generation
            </p>
          </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>
