<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useFurnaceSplitterStore } from '@/stores/furnacesplitter'
import {
  Save,
  Play,
  Download,
  Plus,
  Trash2,
  Flame,
  Settings as SettingsIcon,
} from 'lucide-vue-next'

const store = useFurnaceSplitterStore()

const showCreateModal = ref(false)
const showImportModal = ref(false)
const newConfigName = ref('')
const newConfigDesc = ref('')
const importConfigName = ref('')

onMounted(async () => {
  await store.fetchConfigs()
  if (store.configs.length > 0 && store.configs[0]) {
    await store.loadConfig(store.configs[0].id)
  }
})

// --- Config data helpers ---

function getConfigValue(path: string, defaultValue: any = false): any {
  if (!store.currentConfig?.config_data) return defaultValue
  const parts = path.split('.')
  let current: any = store.currentConfig.config_data
  for (const part of parts) {
    if (current == null || typeof current !== 'object') return defaultValue
    current = current[part]
  }
  return current ?? defaultValue
}

function setConfigValue(path: string, value: any) {
  if (!store.currentConfig) return
  if (!store.currentConfig.config_data) store.currentConfig.config_data = {}
  const parts = path.split('.')
  let current: any = store.currentConfig.config_data
  for (let i = 0; i < parts.length - 1; i++) {
    const part = parts[i]!
    if (current[part] == null || typeof current[part] !== 'object') {
      current[part] = {}
    }
    current = current[part]
  }
  current[parts[parts.length - 1]!] = value
  store.markDirty()
}

// Furnace types with display names
const furnaceTypes = [
  { key: 'furnace', label: 'Small Furnace', description: 'Standard furnace for smelting ores' },
  { key: 'furnace.large', label: 'Large Furnace', description: 'Large furnace with more slots' },
  { key: 'campfire', label: 'Campfire', description: 'Basic campfire for cooking' },
  { key: 'refinery_small_deployed', label: 'Small Oil Refinery', description: 'Refines crude oil into low grade fuel' },
  { key: 'skull_fire_pit', label: 'Skull Fire Pit', description: 'Decorative fire pit for cooking' },
  { key: 'hobobarrel_static', label: 'Hobo Barrel', description: 'Barrel fire for cooking' },
  { key: 'electricfurnace.deployed', label: 'Electric Furnace', description: 'Electricity-powered furnace' },
]

// --- Action handlers ---

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

async function handleCreateConfig() {
  if (!newConfigName.value.trim()) return
  const config = await store.createConfig(
    newConfigName.value.trim(),
    newConfigDesc.value.trim() || undefined,
  )
  if (config) {
    showCreateModal.value = false
    newConfigName.value = ''
    newConfigDesc.value = ''
  }
}

async function handleDeleteConfig() {
  if (!store.currentConfig) return
  if (!confirm(`Delete "${store.currentConfig.config_name}"? This cannot be undone.`)) return
  await store.deleteConfig(store.currentConfig.id)
}

async function handleApply() {
  if (!store.currentConfig) return
  if (!confirm('Apply this FurnaceSplitter config to the server? This will overwrite the current config.')) return
  if (store.isDirty) {
    await store.saveCurrentConfig()
  }
  await store.applyToServer(store.currentConfig.id)
}

async function handleImport() {
  if (!importConfigName.value.trim()) return
  const config = await store.importFromServer(importConfigName.value.trim())
  if (config) {
    showImportModal.value = false
    importConfigName.value = ''
  }
}
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <h1 class="text-2xl font-bold text-white">Furnace Splitter Config</h1>
      <div class="flex items-center gap-3">
        <button
          @click="showCreateModal = true"
          class="flex items-center gap-2 px-3 py-2 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
        >
          <Plus class="w-4 h-4" />
          New Config
        </button>
      </div>
    </div>

    <!-- Config Selector + Action Bar -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-4">
      <div class="flex items-center gap-3 flex-wrap">
        <!-- Config Selector -->
        <select
          v-if="store.configs.length > 0"
          :value="store.currentConfig?.id || ''"
          @change="handleConfigChange(($event.target as HTMLSelectElement).value)"
          class="bg-neutral-800 border border-neutral-700 text-neutral-200 rounded-lg px-3 py-2 text-sm min-w-[200px]"
        >
          <option v-for="c in store.configs" :key="c.id" :value="c.id">
            {{ c.config_name }}
            <template v-if="c.is_active"> (Active)</template>
          </option>
        </select>
        <span v-else class="text-neutral-500 text-sm">No configs yet</span>

        <!-- Save -->
        <button
          @click="store.saveCurrentConfig()"
          :disabled="!store.currentConfig || !store.isDirty || store.isSaving"
          class="flex items-center gap-2 px-3 py-2 bg-oxide-500 text-white rounded-lg hover:bg-oxide-600 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
        >
          <Save class="w-4 h-4" />
          {{ store.isSaving ? 'Saving...' : 'Save' }}
        </button>

        <!-- Apply to Server -->
        <button
          @click="handleApply"
          :disabled="!store.currentConfig || store.isApplying"
          class="flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
        >
          <Play class="w-4 h-4" />
          {{ store.isApplying ? 'Applying...' : 'Apply to Server' }}
        </button>

        <!-- Import from Server -->
        <button
          @click="showImportModal = true"
          class="flex items-center gap-2 px-3 py-2 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
        >
          <Download class="w-4 h-4" />
          Import from Server
        </button>

        <!-- Delete -->
        <button
          @click="handleDeleteConfig"
          :disabled="!store.currentConfig"
          class="flex items-center gap-2 px-3 py-2 bg-red-500/10 text-red-400 rounded-lg hover:bg-red-500/20 disabled:opacity-50 text-sm ml-auto"
        >
          <Trash2 class="w-4 h-4" />
          Delete
        </button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="store.isLoading" class="flex items-center justify-center py-20">
      <div class="animate-spin w-8 h-8 border-2 border-oxide-500 border-t-transparent rounded-full" />
    </div>

    <!-- No Config Selected -->
    <div v-else-if="!store.currentConfig" class="bg-neutral-900 border border-neutral-800 rounded-xl p-12 text-center">
      <Flame class="w-12 h-12 text-neutral-600 mx-auto mb-4" />
      <h2 class="text-lg font-semibold text-neutral-300 mb-2">No FurnaceSplitter Config Selected</h2>
      <p class="text-neutral-500 mb-4">Create a new config, import from server, or select one from the dropdown above.</p>
      <button
        @click="showCreateModal = true"
        class="px-4 py-2 bg-oxide-500 text-white rounded-lg hover:bg-oxide-600"
      >
        Create First Config
      </button>
    </div>

    <!-- Config Editor -->
    <div v-else class="space-y-6">
      <!-- Furnace Splitter Settings -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-6">
        <div class="flex items-center gap-2">
          <SettingsIcon class="w-5 h-5 text-neutral-400" />
          <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">Splitter Settings</h3>
        </div>

        <!-- Global enabled -->
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm text-neutral-200">Enabled</label>
            <p class="text-xs text-neutral-500">Globally enable or disable furnace splitting</p>
          </div>
          <button
            @click="setConfigValue('Enabled', !getConfigValue('Enabled', true))"
            class="relative w-11 h-6 rounded-full transition-colors"
            :class="getConfigValue('Enabled', true) ? 'bg-oxide-500' : 'bg-neutral-700'"
          >
            <span
              class="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform"
              :class="getConfigValue('Enabled', true) ? 'translate-x-5' : 'translate-x-0'"
            />
          </button>
        </div>
      </div>

      <!-- Per-Furnace Type Settings -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-6">
        <div class="flex items-center gap-2">
          <Flame class="w-5 h-5 text-neutral-400" />
          <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">Furnace Type Settings</h3>
        </div>

        <div class="space-y-4">
          <div
            v-for="furnace in furnaceTypes"
            :key="furnace.key"
            class="bg-neutral-800/50 border border-neutral-700/50 rounded-lg p-4"
          >
            <div class="flex items-center justify-between mb-3">
              <div>
                <h4 class="text-sm font-medium text-neutral-200">{{ furnace.label }}</h4>
                <p class="text-xs text-neutral-500">{{ furnace.description }}</p>
              </div>
              <button
                @click="setConfigValue(`Furnaces.${furnace.key}.Enabled`, !getConfigValue(`Furnaces.${furnace.key}.Enabled`, true))"
                class="relative w-11 h-6 rounded-full transition-colors"
                :class="getConfigValue(`Furnaces.${furnace.key}.Enabled`, true) ? 'bg-oxide-500' : 'bg-neutral-700'"
              >
                <span
                  class="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform"
                  :class="getConfigValue(`Furnaces.${furnace.key}.Enabled`, true) ? 'translate-x-5' : 'translate-x-0'"
                />
              </button>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-xs text-neutral-500 mb-1">Default Split Stacks</label>
                <input
                  type="number"
                  :value="getConfigValue(`Furnaces.${furnace.key}.DefaultSplitCount`, 0)"
                  @input="setConfigValue(`Furnaces.${furnace.key}.DefaultSplitCount`, Number(($event.target as HTMLInputElement).value))"
                  min="0"
                  class="w-full bg-neutral-800 border border-neutral-700 rounded px-3 py-2 text-neutral-200 text-sm"
                  placeholder="0 = fill all slots"
                />
              </div>
              <div>
                <label class="block text-xs text-neutral-500 mb-1">Fuel Multiplier</label>
                <input
                  type="number"
                  step="0.1"
                  :value="getConfigValue(`Furnaces.${furnace.key}.FuelMultiplier`, 1.0)"
                  @input="setConfigValue(`Furnaces.${furnace.key}.FuelMultiplier`, Number(($event.target as HTMLInputElement).value))"
                  min="0"
                  class="w-full bg-neutral-800 border border-neutral-700 rounded px-3 py-2 text-neutral-200 text-sm"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Permission Groups -->
      <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-4">
        <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">Permission</h3>
        <p class="text-xs text-neutral-500">
          The permission <code class="text-neutral-300 bg-neutral-800 px-1 rounded">furnacesplitter.use</code> controls which players can use the furnace splitting feature. Assign this permission via your Oxide permission system.
        </p>
      </div>
    </div>

    <!-- Create Config Modal -->
    <div v-if="showCreateModal" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" @click.self="showCreateModal = false">
      <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 w-full max-w-md">
        <h2 class="text-lg font-semibold text-neutral-100 mb-4">New FurnaceSplitter Config</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-neutral-400 mb-1">Config Name</label>
            <input
              v-model="newConfigName"
              placeholder="e.g. Default Furnace Settings"
              class="w-full bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-2 text-neutral-200 text-sm"
              @keydown.enter="handleCreateConfig"
            />
          </div>
          <div>
            <label class="block text-sm text-neutral-400 mb-1">Description (optional)</label>
            <textarea
              v-model="newConfigDesc"
              rows="2"
              placeholder="What is this config for?"
              class="w-full bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-2 text-neutral-200 text-sm resize-none"
            />
          </div>
          <div class="flex justify-end gap-2">
            <button @click="showCreateModal = false" class="px-4 py-2 text-sm text-neutral-400 hover:text-neutral-200">Cancel</button>
            <button
              @click="handleCreateConfig"
              :disabled="!newConfigName.trim()"
              class="px-4 py-2 bg-oxide-500 text-white rounded-lg hover:bg-oxide-600 disabled:opacity-50 text-sm"
            >
              Create
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Import from Server Modal -->
    <div v-if="showImportModal" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" @click.self="showImportModal = false">
      <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 w-full max-w-md">
        <h2 class="text-lg font-semibold text-neutral-100 mb-4">Import from Server</h2>
        <p class="text-sm text-neutral-400 mb-4">
          Import the current FurnaceSplitter config from your live server. This will create a new config profile.
        </p>
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-neutral-400 mb-1">Config Name</label>
            <input
              v-model="importConfigName"
              placeholder="e.g. Imported Server Config"
              class="w-full bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-2 text-neutral-200 text-sm"
              @keydown.enter="handleImport"
            />
          </div>
          <div class="flex justify-end gap-2">
            <button @click="showImportModal = false" class="px-4 py-2 text-sm text-neutral-400 hover:text-neutral-200">Cancel</button>
            <button
              @click="handleImport"
              :disabled="!importConfigName.trim()"
              class="px-4 py-2 bg-oxide-500 text-white rounded-lg hover:bg-oxide-600 disabled:opacity-50 text-sm"
            >
              Import
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
