<script setup lang="ts">
import { ref, computed } from 'vue'
import { rustItems } from '@/data/rust-items'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import IconButton from '@/components/ds/core/IconButton.vue'
import Icon from '@/components/ds/core/Icon.vue'
import Badge from '@/components/ds/core/Badge.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import DsInput from '@/components/ds/forms/Input.vue'
import type { LootGroupProfile } from '@/types'

const props = defineProps<{
  lootGroups: Record<string, any>
}>()

const emit = defineEmits<{
  dirty: []
}>()

const expandedGroup = ref<string | null>(null)
const newGroupName = ref('')

const groupEntries = computed(() => {
  return Object.entries(props.lootGroups).map(([name, data]) => ({
    name,
    data: data as LootGroupProfile,
    itemCount: data?.ItemList ? Object.keys(data.ItemList).length : 0,
  }))
})

function toggleGroup(name: string) {
  expandedGroup.value = expandedGroup.value === name ? null : name
}

function addGroup() {
  const name = newGroupName.value.trim()
  if (!name || props.lootGroups[name]) return
  props.lootGroups[name] = {
    Enabled: true,
    GuaranteedItems: {},
    ItemList: {},
  }
  newGroupName.value = ''
  expandedGroup.value = name
  emit('dirty')
}

function deleteGroup(name: string) {
  if (!confirm(`Delete group "${name}"?`)) return
  delete props.lootGroups[name]
  if (expandedGroup.value === name) expandedGroup.value = null
  emit('dirty')
}

function getItemName(shortname: string): string {
  return rustItems.find(i => i.shortname === shortname)?.name || shortname
}

function removeItemFromGroup(groupName: string, shortname: string) {
  delete props.lootGroups[groupName].ItemList[shortname]
  emit('dirty')
}

function updateGroupItemField(groupName: string, shortname: string, field: string, value: number) {
  if (props.lootGroups[groupName]?.ItemList?.[shortname]) {
    props.lootGroups[groupName].ItemList[shortname][field] = value
    emit('dirty')
  }
}
</script>

<template>
  <div class="lge-root">
    <!-- Add group panel -->
    <Panel>
      <div class="lge-add">
        <DsInput
          v-model="newGroupName"
          placeholder="New group name…"
          @keydown.enter="addGroup"
        />
        <Button
          icon="plus"
          :disabled="!newGroupName.trim()"
          @click="addGroup"
        >
          Add group
        </Button>
      </div>
    </Panel>

    <!-- Empty state -->
    <Panel v-if="groupEntries.length === 0">
      <EmptyState
        icon="layers"
        title="No loot groups"
        description="Groups let you create reusable item pools that can be assigned to multiple containers."
      />
    </Panel>

    <!-- Group cards -->
    <div
      v-for="entry in groupEntries"
      :key="entry.name"
      class="lge-card"
    >
      <!-- Group header -->
      <button
        class="lge-card__head"
        @click="toggleGroup(entry.name)"
      >
        <Icon
          :name="expandedGroup === entry.name ? 'chevron-down' : 'chevron-right'"
          :size="16"
          class="lge-card__chevron"
        />
        <span class="lge-card__name">{{ entry.name }}</span>
        <Badge tone="neutral" mono>{{ entry.itemCount }}</Badge>
        <IconButton
          icon="trash-2"
          variant="danger"
          size="sm"
          label="Delete group"
          class="lge-card__del"
          @click.stop="deleteGroup(entry.name)"
        />
      </button>

      <!-- Expanded items -->
      <div v-if="expandedGroup === entry.name" class="lge-card__body">
        <table v-if="entry.itemCount > 0" class="lge-table">
          <thead>
            <tr>
              <th class="lge-th">Item</th>
              <th class="lge-th lge-th--num">Min</th>
              <th class="lge-th lge-th--num">Max</th>
              <th class="lge-th lge-th--num">Prob %</th>
              <th class="lge-th lge-th--action"></th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(itemData, shortname) in entry.data.ItemList"
              :key="shortname"
              class="lge-tr"
            >
              <td class="lge-td">{{ getItemName(shortname as string) }}</td>
              <td class="lge-td lge-td--num">
                <input
                  type="number"
                  :value="(itemData as any).Min ?? 1"
                  @input="updateGroupItemField(entry.name, shortname as string, 'Min', Number(($event.target as HTMLInputElement).value))"
                  class="cc-num-input cc-num-input--center"
                  min="0"
                />
              </td>
              <td class="lge-td lge-td--num">
                <input
                  type="number"
                  :value="(itemData as any).Max ?? 1"
                  @input="updateGroupItemField(entry.name, shortname as string, 'Max', Number(($event.target as HTMLInputElement).value))"
                  class="cc-num-input cc-num-input--center"
                  min="0"
                />
              </td>
              <td class="lge-td lge-td--num">
                <input
                  type="number"
                  :value="(itemData as any).Probability ?? 100"
                  @input="updateGroupItemField(entry.name, shortname as string, 'Probability', Number(($event.target as HTMLInputElement).value))"
                  class="cc-num-input cc-num-input--center"
                  min="0"
                  max="100"
                />
              </td>
              <td class="lge-td lge-td--action">
                <IconButton
                  icon="trash-2"
                  variant="danger"
                  size="sm"
                  label="Remove item"
                  @click="removeItemFromGroup(entry.name, shortname as string)"
                />
              </td>
            </tr>
          </tbody>
        </table>
        <p v-else class="lge-card__empty">
          No items in this group yet. Add items from the container editor.
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.lge-root {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* Add group row */
.lge-add {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}
.lge-add > :first-child {
  flex: 1;
}

/* Group card */
.lge-card {
  background: var(--surface-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--ring-default);
  overflow: hidden;
}
.lge-card__head {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 14px;
  background: transparent;
  border: 0;
  cursor: pointer;
  font-family: var(--font-sans);
  text-align: left;
  transition: var(--transition-colors);
}
.lge-card__head:hover {
  background: var(--surface-hover);
}
.lge-card__chevron {
  color: var(--text-muted);
  flex: none;
}
.lge-card__name {
  flex: 1;
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
}
.lge-card__del {
  margin-left: auto;
  flex: none;
}

/* Expanded body */
.lge-card__body {
  border-top: 1px solid var(--border-subtle);
  padding: 12px;
}
.lge-card__empty {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  text-align: center;
  padding: 16px 0 8px;
}

/* Table */
.lge-table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--text-sm);
}
.lge-th {
  padding: 6px 10px;
  text-align: left;
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-tertiary);
  border-bottom: 1px solid var(--border-subtle);
  white-space: nowrap;
}
.lge-th--num {
  text-align: center;
  width: 80px;
}
.lge-th--action {
  width: 40px;
}
.lge-tr {
  border-bottom: 1px solid var(--border-subtle);
}
.lge-tr:last-child {
  border-bottom: 0;
}
.lge-tr:hover {
  background: var(--surface-hover);
}
.lge-td {
  padding: 7px 10px;
  color: var(--text-primary);
  vertical-align: middle;
}
.lge-td--num {
  text-align: center;
  width: 80px;
}
.lge-td--action {
  width: 40px;
  padding: 4px 6px;
}

/* Shared number input (same as LootItemEditor) */
.cc-num-input {
  width: 100%;
  background: var(--surface-inset);
  border: 0;
  border-radius: var(--radius-sm);
  box-shadow: var(--ring-default);
  padding: 5px 8px;
  font-family: var(--font-mono);
  font-size: var(--text-sm);
  font-variant-numeric: tabular-nums;
  color: var(--text-primary);
  outline: none;
  transition: var(--transition-colors);
}
.cc-num-input:focus {
  box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm);
}
.cc-num-input--center {
  text-align: center;
}
</style>
