<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import { useAdminConfigStore } from '@/store/adminConfigStore'
import type { AdminConfig } from '@/types/admin-config'
import { ExtractionMode } 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'
import { compareVersions, getDssVersion } from '@/lib/utils'

const store = useAdminConfigStore()

const managedFolders = ref<Array<{ id: string; name: string }>>([])
const loadingFolders = ref(false)
const availableVisionModels = ref<Array<{ id: string; name: string; type?: string }>>([])
const showVlmOption = computed(() => {
  return compareVersions(getDssVersion(), '14.3.0') >= 0
})

async function loadManagedFolders() {
  loadingFolders.value = true
  try {
    const response = await API.getManagedFolders()
    managedFolders.value = response.data || []
  } catch (error) {
    console.error('Failed to load managed folders:', error)
    managedFolders.value = []
  } finally {
    loadingFolders.value = false
  }
}

async function loadAvailableLLMs() {
  try {
    const { data } = await API.listAvailableLLMs()
    availableVisionModels.value = data?.textCompletionModels ?? []
  } catch (error) {
    console.error('Failed to load available LLMs:', error)
    availableVisionModels.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
}

// Reset VLM_ANNOTATE to IGNORE if DSS version is too old
watch([showVlmOption, () => store.draft?.textExtractionType], ([showVlm, currentType]) => {
  if (!showVlm && currentType === 'VLM_ANNOTATE') {
    updateDraft((cfg) => {
      cfg.textExtractionType = 'IGNORE'
    })
  }
})

onMounted(() => {
  loadManagedFolders()
  loadAvailableLLMs()
})

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

const extractionMode = computed({
  get: () => store.draft?.extractionMode ?? ExtractionMode.PagesScreenshots,
  set: (v: ExtractionMode) => {
    updateDraft((cfg) => {
      cfg.extractionMode = v
    })
  },
})

const textExtractionType = computed({
  get: () => store.draft?.textExtractionType ?? 'IGNORE',
  set: (v: 'IGNORE' | 'OCR' | 'VLM_ANNOTATE') => {
    updateDraft((cfg) => {
      cfg.textExtractionType = v
    })
  },
})

const maxImagesInConversation = computed({
  get: () => store.draft?.maxImagesInConversation ?? 50,
  set: (v: number) => {
    updateDraft((cfg) => {
      const n = Number(v)
      cfg.maxImagesInConversation = Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 50
    })
  },
})

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

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

const showMaxImages = computed(() => extractionMode.value === ExtractionMode.PagesScreenshots)

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 flex items-center justify-between">
        <div class="flex items-center gap-2">
          <Switch
            class="admin-switch"
            v-model="enableDocumentUpload"
            @update:modelValue="(v: boolean) => (enableDocumentUpload = !!v)"
          />
          <label class="font-medium text-sm cursor-pointer admin-subsection-title"
            >Enable Document Upload</label
          >
        </div>
      </div>

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

        <div class="space-y-4 pt-2 max-w-3xl">
          <div id="field-uploadManagedFolder">
            <label class="admin-field-label">
              Upload Managed Folder<span class="text-red-600">*</span>
            </label>
            <div class="w-full lg:w-[420px]">
              <Select v-model="uploadManagedFolder">
                <SelectTrigger
                  class="w-full admin-select-trigger admin-dropdown-trigger"
                  :class="[missing(uploadManagedFolder) ? 'border-red-500' : '']"
                >
                  <SelectValue placeholder="Select a managed folder" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem
                      v-for="folder in managedFolders"
                      :key="folder.id"
                      :value="folder.id"
                      class="admin-select-item"
                    >
                      {{ folder.name }}
                    </SelectItem>
                  </SelectGroup>
                  <div
                    v-if="managedFolders.length === 0"
                    class="admin-select-empty p-2 text-sm text-muted-foreground"
                  >
                    No managed folder available, please create one in your project to select it
                  </div>
                </SelectContent>
              </Select>
            </div>
            <div v-if="missing(uploadManagedFolder)" class="text-[11px] mt-1 text-red-600">
              <i class="dku-icon-warning-12 mr-1"></i>Upload Managed Folder is required
            </div>
            <p class="admin-field-description">
              Managed folder where uploaded files will be stored
            </p>
          </div>

          <Separator />

          <div>
            <label class="admin-field-label">Extraction Mode</label>
            <div class="w-full lg:w-[420px]">
              <Select v-model="extractionMode">
                <SelectTrigger class="w-full admin-select-trigger admin-dropdown-trigger">
                  <SelectValue placeholder="Select extraction mode" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem :value="ExtractionMode.PagesScreenshots" class="admin-select-item">
                      Use pages screenshots
                    </SelectItem>
                    <SelectItem :value="ExtractionMode.PagesText" class="admin-select-item">
                      Extract text
                    </SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
            <p class="admin-field-description">Extraction mode for PDF, PPTX, DOCX files</p>
          </div>

          <div v-if="extractionMode === ExtractionMode.PagesText">
            <label class="admin-field-label">Process Inline Images</label>
            <p class="admin-field-description">How to handle images during text extraction</p>
            <div class="w-full lg:w-[420px]">
              <Select v-model="textExtractionType">
                <SelectTrigger class="w-full admin-select-trigger admin-dropdown-trigger">
                  <SelectValue placeholder="Select text extraction type" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem value="IGNORE" class="admin-select-item">
                      No Processing
                    </SelectItem>
                    <SelectItem value="OCR" class="admin-select-item"> OCR </SelectItem>
                    <SelectItem v-if="showVlmOption" value="VLM_ANNOTATE" class="admin-select-item">
                      VLM
                    </SelectItem>
                  </SelectGroup>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div
            v-if="
              extractionMode === 'pagesScreenshots' ||
              (extractionMode === 'pagesText' && textExtractionType === 'VLM_ANNOTATE')
            "
          >
            <label class="admin-field-label">Vision LLM Model</label>
            <div class="w-full lg:w-[420px]">
              <Select v-model="conversationVisionLLM">
                <SelectTrigger class="w-full admin-select-trigger admin-dropdown-trigger">
                  <SelectValue placeholder="Select a model" />
                </SelectTrigger>
                <SelectContent hide-indicator>
                  <SelectGroup>
                    <SelectItem
                      v-for="model in availableVisionModels"
                      :key="model.id"
                      :value="model.id"
                      class="admin-select-item"
                    >
                      {{ model.name }}
                    </SelectItem>
                  </SelectGroup>
                  <div
                    v-if="availableVisionModels.length === 0"
                    class="admin-select-empty p-2 text-sm text-muted-foreground"
                  >
                    No models available
                  </div>
                </SelectContent>
              </Select>
            </div>
            <p class="admin-field-description">
              Model used for VLM image annotation during document extraction
            </p>
          </div>

          <div v-if="showMaxImages">
            <label class="admin-field-label">
              Max Images in Conversation<span class="text-red-600">*</span>
            </label>
            <Input
              v-model.number="maxImagesInConversation"
              type="number"
              min="0"
              step="1"
              class="admin-input w-[200px]"
            />
            <p class="admin-field-description">
              Maximum number of images that can be uploaded per conversation
            </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>
