<script setup lang="ts">
import { computed, ref } from 'vue'
import { useAdminConfigStore } from '@/store/adminConfigStore'
import type { AdminConfig, ConversationStarterExample } from '@/types/admin-config'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { MultiSelectComboBox } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'

const store = useAdminConfigStore()

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

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

const conversationExamples = computed({
  get: () => store.draft?.conversationStarterExamples ?? [],
  set: (examples: ConversationStarterExample[]) => {
    updateDraft((cfg) => {
      cfg.conversationStarterExamples = [...examples]
    })
  },
})

const enterpriseAgentOptions = computed(() => {
  return (store.draft?.enterpriseAgents ?? []).map((agent) => ({
    value: agent.id,
    label: agent.name || agent.sourceAgentName || agent.id,
    description: agent.projectKey,
  }))
})

const editingExampleId = ref<string | null>(null)
const editingExample = ref<Partial<ConversationStarterExample>>({
  label: '',
  query: '',
  enterpriseAgents: [],
})

function startNewExample() {
  editingExampleId.value = 'new'
  editingExample.value = {
    label: '',
    query: '',
    enterpriseAgents: [],
  }
}

function saveExample() {
  const label = editingExample.value.label?.trim()
  const query = editingExample.value.query?.trim()

  if (!label || !query) return

  if (editingExampleId.value === 'new') {
    const newExample: ConversationStarterExample = {
      id: `example-${Date.now()}`,
      label,
      query,
      enterpriseAgents: editingExample.value.enterpriseAgents ?? [],
    }
    conversationExamples.value = [...conversationExamples.value, newExample]
  } else if (editingExampleId.value) {
    conversationExamples.value = conversationExamples.value.map((ex) =>
      ex.id === editingExampleId.value
        ? { ...ex, label, query, enterpriseAgents: editingExample.value.enterpriseAgents ?? [] }
        : ex
    )
  }

  cancelEdit()
}

function startEdit(example: ConversationStarterExample) {
  editingExampleId.value = example.id
  editingExample.value = {
    label: example.label,
    query: example.query,
    enterpriseAgents: [...(example.enterpriseAgents ?? [])],
  }
}

function cancelEdit() {
  editingExampleId.value = null
  editingExample.value = { label: '', query: '', enterpriseAgents: [] }
}

function deleteExample(id: string) {
  conversationExamples.value = conversationExamples.value.filter((ex) => ex.id !== id)
}

function getAgentName(agentId: string): string {
  const agent = enterpriseAgentOptions.value.find((a) => a.value === agentId)
  return agent?.label || agentId
}

const selectedAgents = computed({
  get: () => editingExample.value.enterpriseAgents ?? [],
  set: (value: string[]) => {
    editingExample.value.enterpriseAgents = value
  },
})

const isEditing = computed(() => editingExampleId.value !== null)
const isCreating = computed(() => editingExampleId.value === 'new')

// Combined list: existing examples + virtual "new" item when creating
const displayItems = computed(() => {
  const items = conversationExamples.value.map((ex) => ({ ...ex, isNew: false }))
  if (isCreating.value) {
    items.push({ id: 'new', label: '', query: '', enterpriseAgents: [], isNew: true })
  }
  return items
})
</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">Interface Settings</h3>
      </div>

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

        <div class="space-y-4 pt-2 max-w-3xl">
          <div>
            <div class="flex items-center gap-2">
              <Switch
                class="admin-switch"
                v-model="smartMode"
                @update:modelValue="(v: boolean) => (smartMode = !!v)"
              />
              <label class="font-medium text-sm cursor-pointer">Smart Mode</label>
            </div>
            <p class="admin-field-description ml-10">Enable intelligent features and suggestions</p>
          </div>

          <Separator />

          <div>
            <div class="flex items-center gap-2">
              <Switch
                class="admin-switch"
                v-model="allowDisableAgents"
                @update:modelValue="(v: boolean) => (allowDisableAgents = !!v)"
              />
              <label class="font-medium text-sm cursor-pointer"
                >Allow users to disable agents</label
              >
            </div>
            <p class="admin-field-description ml-10">
              Give users the ability to disable agents and engage directly with LLMs in their
              conversations
            </p>
          </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">Conversation Starters</h3>
        <p class="admin-field-description">
          Example labels shown on the New Conversation page, with predefined queries and automatic
          selection of linked agent(s)
        </p>
      </div>

      <Separator class="px-4" />

      <div class="px-4 pb-4">
        <div class="space-y-3 pt-3">
          <!-- List of items (existing examples + virtual "new" item when creating) -->
          <div v-if="displayItems.length > 0" class="space-y-2">
            <template v-for="item in displayItems" :key="item.id">
              <!-- Edit/Create form (shown when this item is being edited or is the new item) -->
              <div v-if="editingExampleId === item.id" class="border border-border rounded-lg p-3">
                <div class="space-y-3">
                  <!-- Enterprise agents selection -->
                  <div>
                    <div class="mb-1">
                      <label class="admin-field-label">Enterprise Agents</label>
                      <p class="admin-field-description">
                        Will be automatically selected when the corresponding label is chosen.
                      </p>
                    </div>

                    <MultiSelectComboBox
                      v-model="selectedAgents"
                      :options="enterpriseAgentOptions"
                      placeholder="Select agents..."
                      class="w-full lg:w-[420px]"
                    />
                  </div>

                  <div>
                    <label class="admin-field-label mb-1 block">Label</label>
                    <Input
                      v-model="editingExample.label"
                      placeholder="e.g. ARR Request"
                      class="admin-input"
                    />
                    <p class="admin-field-description">
                      Example labels shown on the New Conversation page
                    </p>
                  </div>

                  <div>
                    <label class="admin-field-label mb-1 block">Query</label>
                    <Textarea
                      v-model="editingExample.query"
                      placeholder="Write your query here..."
                      rows="2"
                      class="w-full !border !border-border rounded-md shadow-sm admin-textarea text-sm py-2 px-3 resize-y placeholder-muted-foreground"
                    />
                    <p class="admin-field-description">
                      Predefined queries that automatically populate the text field
                    </p>
                  </div>

                  <div class="flex items-center justify-end gap-2">
                    <Button
                      variant="outline"
                      size="lg"
                      @click="cancelEdit"
                      class="admin-btn admin-btn--secondary"
                      >Cancel</Button
                    >
                    <Button
                      size="lg"
                      @click="saveExample"
                      :disabled="!editingExample.label || !editingExample.query"
                      class="admin-btn admin-btn--primary"
                    >
                      {{ item.isNew ? 'Create' : 'Update' }}
                    </Button>
                  </div>
                </div>
              </div>

              <!-- Read-only card (shown when not editing this item) -->
              <div v-else-if="!item.isNew" class="border rounded-lg p-3">
                <div class="flex items-start justify-between gap-2">
                  <div class="flex-1 min-w-0">
                    <div class="text-sm font-semibold">{{ item.label }}</div>
                    <div class="text-sm">{{ item.query }}</div>
                    <div
                      v-if="item.enterpriseAgents && item.enterpriseAgents.length > 0"
                      class="flex flex-wrap gap-1 mt-2"
                    >
                      <Badge
                        v-for="agentId in item.enterpriseAgents"
                        :key="agentId"
                        variant="secondary"
                        class="text-xs"
                      >
                        <i class="dku-icon-briefcase-12 mr-1"></i>
                        {{ getAgentName(agentId) }}
                      </Badge>
                    </div>
                  </div>
                  <div v-if="!isEditing" class="flex items-center gap-1 flex-shrink-0">
                    <Button size="sm" variant="ghost" @click="startEdit(item)" title="Edit">
                      <i class="dku-icon-edit-16"></i>
                      Edit
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      class="admin-icon--trash"
                      @click="deleteExample(item.id)"
                      title="Delete"
                    >
                      <i class="dku-icon-trash-16"></i>
                    </Button>
                  </div>
                </div>
              </div>
            </template>
          </div>

          <Button
            v-if="!isEditing"
            class="admin-btn admin-btn--secondary w-full sm:w-auto"
            size="lg"
            @click="startNewExample"
          >
            <i class="dku-icon-plus-16 mr-2"></i>
            Add Conversation Starter
          </Button>
        </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>
