<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useLootStore } from '@/stores/loot'
import { useToastStore } from '@/stores/toast'
import LootContainerSidebar from '@/components/loot/LootContainerSidebar.vue'
import LootItemEditor from '@/components/loot/LootItemEditor.vue'
import LootGroupEditor from '@/components/loot/LootGroupEditor.vue'
import LootItemPicker from '@/components/loot/LootItemPicker.vue'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Badge from '@/components/ds/core/Badge.vue'
import Icon from '@/components/ds/core/Icon.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import Tabs from '@/components/ds/navigation/Tabs.vue'
import DsSelect from '@/components/ds/forms/Select.vue'
import DsInput from '@/components/ds/forms/Input.vue'

const loot = useLootStore()
const toast = useToastStore()

const showCreateModal = ref(false)
const showImportModal = ref(false)
const showItemPicker = ref(false)
const newProfileName = ref('')
const newProfileDesc = ref('')
const selectedMultiplier = ref(1)
const showApplyDropdown = ref(false)
const importJson = ref('')
const importName = ref('')
const activeTab = ref<'items' | 'groups'>('items')

const multipliers = [1, 2, 5, 10]

const tabItems = [
  { value: 'items', label: 'Container items' },
  { value: 'groups', label: 'Loot groups', icon: 'layers' },
]

// Profile selector options for DS Select
const profileOptions = computed(() =>
  loot.profiles.map(p => ({
    value: p.id,
    label: p.profile_name + (p.is_active ? ' (active)' : ''),
  }))
)
const currentProfileId = computed(() => loot.currentProfile?.id ?? '')

onMounted(async () => {
  await loot.fetchProfiles()
  if (loot.profiles.length > 0 && loot.profiles[0]) {
    await loot.loadProfile(loot.profiles[0].id)
  }
})

async function handleCreateProfile() {
  if (!newProfileName.value.trim()) return
  const profile = await loot.createProfile(newProfileName.value.trim(), newProfileDesc.value.trim() || undefined)
  if (profile) {
    showCreateModal.value = false
    newProfileName.value = ''
    newProfileDesc.value = ''
  }
}

async function handleDeleteProfile() {
  if (!loot.currentProfile) return
  if (!confirm(`Delete "${loot.currentProfile.profile_name}"?`)) return
  await loot.deleteProfile(loot.currentProfile.id)
}

async function handleDuplicate() {
  if (!loot.currentProfile) return
  const dup = await loot.duplicateProfile(loot.currentProfile.id)
  if (dup) await loot.loadProfile(dup.id)
}

async function handleApply(mult: number) {
  if (!loot.currentProfile) return
  showApplyDropdown.value = false
  if (loot.isDirty) {
    await loot.saveCurrentProfile()
  }
  await loot.applyToServer(loot.currentProfile.id, mult)
}

async function handleImport() {
  if (!importName.value.trim() || !importJson.value.trim()) return
  try {
    const parsed = JSON.parse(importJson.value)
    // Support both full export format and raw LootTables format
    const lootTable = parsed.loot_table || parsed
    const lootGroups = parsed.loot_groups || {}
    await loot.importProfile(importName.value.trim(), lootTable, lootGroups)
    showImportModal.value = false
    importJson.value = ''
    importName.value = ''
  } catch {
    toast.error('Invalid JSON')
  }
}

async function handleExport() {
  if (!loot.currentProfile) return
  const data = await loot.exportProfile(loot.currentProfile.id, selectedMultiplier.value)
  if (!data) return
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${data.profile_name}_${data.multiplier}x.json`
  a.click()
  URL.revokeObjectURL(url)
}

async function handleProfileChange(id: string) {
  if (loot.isDirty) {
    if (!confirm('Unsaved changes will be lost. Continue?')) return
  }
  await loot.loadProfile(id)
}

function handleAddItem(shortname: string) {
  if (!loot.currentProfile || !loot.selectedContainer) return
  const table = loot.currentProfile.loot_table
  if (!table[loot.selectedContainer]) {
    table[loot.selectedContainer] = {
      Enabled: true,
      LootProfiles: [],
      GuaranteedItems: {},
      UngroupedItems: {},
      ItemSettings: { ItemsMin: 1, ItemsMax: 6, MinScrap: 0, MaxScrap: 0 },
    }
  }
  const container = table[loot.selectedContainer]!
  if (!container.UngroupedItems) container.UngroupedItems = {}
  if (!container.UngroupedItems[shortname]) {
    container.UngroupedItems[shortname] = {
      Min: 1,
      Max: 1,
      SkinId: 0,
      DisplayName: '',
      Probability: 50,
      DurabilitySettings: { MinDurability: 1, MaxDurability: 1 },
      ItemEntryModifications: { AmmoSettings: null, AttachmentSettings: null },
      BonusItems: {},
    }
    loot.markDirty()
  }
  showItemPicker.value = false
}
</script>

<template>
  <div class="lb-root">
    <!-- Page header -->
    <div class="lb-header">
      <div class="lb-header__left">
        <h1 class="lb-title">Loot builder</h1>
        <Badge v-if="loot.isDirty" tone="warn">Unsaved changes</Badge>
      </div>
      <Button size="sm" variant="secondary" icon="plus" @click="showCreateModal = true">
        New profile
      </Button>
    </div>

    <!-- Profile toolbar -->
    <Panel>
      <div class="lb-toolbar">
        <!-- Profile selector -->
        <div class="lb-toolbar__profile">
          <DsSelect
            v-if="loot.profiles.length > 0"
            :options="profileOptions"
            :model-value="currentProfileId"
            @update:model-value="(v: string | undefined) => { if (v) handleProfileChange(v) }"
          />
          <span v-else class="lb-toolbar__empty">No profiles yet</span>
        </div>

        <div class="lb-toolbar__actions">
          <!-- Save -->
          <Button
            size="sm"
            variant="primary"
            icon="save"
            :disabled="!loot.currentProfile || !loot.isDirty || loot.isSaving"
            :loading="loot.isSaving"
            @click="loot.saveCurrentProfile()"
          >
            {{ loot.isSaving ? 'Saving…' : 'Save' }}
          </Button>

          <!-- Apply to server with multiplier dropdown -->
          <div class="lb-apply-wrap">
            <Button
              size="sm"
              variant="outline"
              icon="play"
              :disabled="!loot.currentProfile || loot.isApplying"
              :loading="loot.isApplying"
              @click="showApplyDropdown = !showApplyDropdown"
            >
              {{ loot.isApplying ? 'Applying…' : 'Apply to server' }}
            </Button>
            <div v-if="showApplyDropdown" class="lb-dropdown">
              <button
                v-for="m in multipliers"
                :key="m"
                class="lb-dropdown__item"
                @click="handleApply(m)"
              >
                {{ m }}x multiplier
              </button>
            </div>
          </div>

          <!-- Duplicate -->
          <Button
            size="sm"
            variant="ghost"
            icon="copy"
            :disabled="!loot.currentProfile"
            @click="handleDuplicate"
          >
            Duplicate
          </Button>

          <!-- Import -->
          <Button
            size="sm"
            variant="ghost"
            icon="upload"
            @click="showImportModal = true"
          >
            Import
          </Button>

          <!-- Export -->
          <Button
            size="sm"
            variant="ghost"
            icon="download"
            :disabled="!loot.currentProfile"
            @click="handleExport"
          >
            Export
          </Button>

          <!-- Delete -->
          <Button
            size="sm"
            variant="danger-soft"
            icon="trash-2"
            :disabled="!loot.currentProfile"
            @click="handleDeleteProfile"
          >
            Delete
          </Button>
        </div>
      </div>
    </Panel>

    <!-- Loading -->
    <div v-if="loot.isLoading" class="lb-loading">
      <Icon name="loader" :size="28" class="lb-spin" />
    </div>

    <!-- Main editor layout -->
    <div v-else-if="loot.currentProfile" class="lb-workspace">
      <!-- Container sidebar -->
      <LootContainerSidebar
        :loot-table="loot.currentProfile.loot_table"
        :selected="loot.selectedContainer"
        @select="loot.selectedContainer = $event"
      />

      <!-- Editor area -->
      <div class="lb-editor">
        <Tabs
          v-model="activeTab"
          :items="tabItems"
          variant="line"
          class="lb-tabs"
        />

        <div class="lb-editor__body">
          <LootItemEditor
            v-if="activeTab === 'items' && loot.selectedContainer"
            :container-key="loot.selectedContainer"
            :loot-table="loot.currentProfile.loot_table"
            @dirty="loot.markDirty()"
            @add-item="showItemPicker = true"
          />
          <div v-else-if="activeTab === 'items'" class="lb-editor__placeholder">
            <EmptyState
              icon="box"
              title="No container selected"
              description="Select a container from the sidebar to configure its loot."
            />
          </div>

          <LootGroupEditor
            v-if="activeTab === 'groups'"
            :loot-groups="loot.currentProfile.loot_groups"
            @dirty="loot.markDirty()"
          />
        </div>
      </div>
    </div>

    <!-- Empty state — no profile -->
    <div v-else class="lb-empty-wrap">
      <Panel>
        <EmptyState
          icon="layers"
          title="No loot profile selected"
          description="Create a new profile or select one above."
        >
          <template #action>
            <Button icon="plus" @click="showCreateModal = true">Create first profile</Button>
          </template>
        </EmptyState>
      </Panel>
    </div>

    <!-- Create profile modal -->
    <Teleport to="body">
      <div v-if="showCreateModal" class="lb-overlay" @click.self="showCreateModal = false">
        <div class="lb-modal">
          <div class="lb-modal__head">
            <span class="lb-modal__title">New loot profile</span>
            <button class="lb-modal__close" @click="showCreateModal = false" aria-label="Close">
              <Icon name="x" :size="16" />
            </button>
          </div>
          <div class="lb-modal__body">
            <DsInput
              v-model="newProfileName"
              label="Profile name"
              placeholder="e.g. Vanilla 2x"
              @keydown.enter="handleCreateProfile"
            />
            <div class="lb-field">
              <label class="lb-field__label">Description <span class="lb-field__opt">(optional)</span></label>
              <textarea
                v-model="newProfileDesc"
                rows="2"
                placeholder="What is this profile for?"
                class="cc-textarea"
              />
            </div>
          </div>
          <div class="lb-modal__foot">
            <Button variant="ghost" size="sm" @click="showCreateModal = false">Cancel</Button>
            <Button
              size="sm"
              :disabled="!newProfileName.trim()"
              @click="handleCreateProfile"
            >
              Create
            </Button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- Import modal -->
    <Teleport to="body">
      <div v-if="showImportModal" class="lb-overlay" @click.self="showImportModal = false">
        <div class="lb-modal lb-modal--wide">
          <div class="lb-modal__head">
            <span class="lb-modal__title">Import loot profile</span>
            <button class="lb-modal__close" @click="showImportModal = false" aria-label="Close">
              <Icon name="x" :size="16" />
            </button>
          </div>
          <div class="lb-modal__body">
            <DsInput
              v-model="importName"
              label="Profile name"
              placeholder="Name for imported profile"
            />
            <div class="lb-field">
              <label class="lb-field__label">BetterLoot JSON</label>
              <textarea
                v-model="importJson"
                rows="10"
                placeholder="Paste LootTables.json content here…"
                class="cc-textarea cc-textarea--mono"
              />
            </div>
          </div>
          <div class="lb-modal__foot">
            <Button variant="ghost" size="sm" @click="showImportModal = false">Cancel</Button>
            <Button
              size="sm"
              :disabled="!importName.trim() || !importJson.trim()"
              @click="handleImport"
            >
              Import
            </Button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- Item picker modal -->
    <LootItemPicker
      v-if="showItemPicker"
      @select="handleAddItem"
      @close="showItemPicker = false"
    />

    <!-- Click-away for apply dropdown -->
    <div v-if="showApplyDropdown" class="lb-clickaway" @click="showApplyDropdown = false" />
  </div>
</template>

<style scoped>
.lb-root {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 24px;
  min-height: 0;
}

/* Header */
.lb-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.lb-header__left {
  display: flex;
  align-items: center;
  gap: 10px;
}
.lb-title {
  font-size: var(--text-lg);
  font-weight: 700;
  color: var(--text-primary);
}

/* Toolbar inside Panel */
.lb-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}
.lb-toolbar__profile {
  min-width: 200px;
  flex: none;
}
.lb-toolbar__empty {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}
.lb-toolbar__actions {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  margin-left: auto;
}

/* Apply dropdown */
.lb-apply-wrap {
  position: relative;
}
.lb-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  right: 0;
  z-index: 40;
  background: var(--surface-raised);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-lg);
  padding: 4px;
  min-width: 150px;
  display: flex;
  flex-direction: column;
}
.lb-dropdown__item {
  background: transparent;
  border: 0;
  padding: 8px 12px;
  font-family: var(--font-sans);
  font-size: var(--text-sm);
  color: var(--text-primary);
  cursor: pointer;
  text-align: left;
  border-radius: var(--radius-sm);
  transition: var(--transition-colors);
}
.lb-dropdown__item:hover {
  background: var(--surface-hover);
}

/* Loading */
.lb-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: var(--accent);
}
.lb-spin {
  animation: lb-spin 0.7s linear infinite;
}
@keyframes lb-spin { to { transform: rotate(360deg); } }

/* Workspace (sidebar + editor) */
.lb-workspace {
  display: flex;
  gap: 16px;
  flex: 1;
  min-height: 0;
  height: calc(100vh - 260px);
}

/* Editor column */
.lb-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}
.lb-tabs {
  margin-bottom: 4px;
}
.lb-editor__body {
  flex: 1;
  overflow-y: auto;
  padding-top: 12px;
}
.lb-editor__placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* Empty state wrapper */
.lb-empty-wrap {}

/* Click-away backdrop */
.lb-clickaway {
  position: fixed;
  inset: 0;
  z-index: 0;
}

/* Modal overlay */
.lb-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 50;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
}
.lb-modal {
  background: var(--surface-raised);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-xl);
  width: 100%;
  max-width: 420px;
  display: flex;
  flex-direction: column;
  gap: 0;
}
.lb-modal--wide {
  max-width: 560px;
}
.lb-modal__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px 14px;
  border-bottom: 1px solid var(--border-subtle);
}
.lb-modal__title {
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
}
.lb-modal__close {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border: 0;
  background: transparent;
  border-radius: var(--radius-sm);
  cursor: pointer;
  color: var(--text-secondary);
  transition: var(--transition-colors);
}
.lb-modal__close:hover {
  background: var(--surface-hover);
  color: var(--text-primary);
}
.lb-modal__body {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.lb-modal__foot {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 14px 20px 16px;
  border-top: 1px solid var(--border-subtle);
}

/* Field (textarea wrapper) */
.lb-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.lb-field__label {
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-secondary);
}
.lb-field__opt {
  font-weight: 400;
  color: var(--text-muted);
  margin-left: 3px;
}

/* Bare textarea with token styling */
.cc-textarea {
  width: 100%;
  background: var(--surface-inset);
  border: 0;
  border-radius: var(--radius-md);
  box-shadow: var(--ring-default);
  padding: 9px 11px;
  font-family: var(--font-sans);
  font-size: var(--text-sm);
  color: var(--text-primary);
  resize: none;
  outline: none;
  transition: var(--transition-colors);
  line-height: var(--leading-relaxed);
}
.cc-textarea::placeholder {
  color: var(--text-muted);
}
.cc-textarea:focus-within,
.cc-textarea:focus {
  box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm);
}
.cc-textarea--mono {
  font-family: var(--font-mono);
  font-size: var(--text-xs);
}
</style>
