<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useTimedExecuteStore } from '@/stores/timedexecute'
import {
  Save,
  Play,
  Download,
  Plus,
  Trash2,
  Clock,
  Settings as SettingsIcon,
  UserPlus,
  UserMinus,
} from 'lucide-vue-next'

const store = useTimedExecuteStore()

const activeTab = ref<'timed' | 'realtime' | 'connect' | 'disconnect'>('timed')
const showCreateModal = ref(false)
const showImportModal = ref(false)
const newConfigName = ref('')
const newConfigDesc = ref('')
const importConfigName = ref('')

const tabs = [
  { key: 'timed', label: 'Timed Commands', icon: Clock },
  { key: 'realtime', label: 'Real-Time', icon: SettingsIcon },
  { key: 'connect', label: 'On Connect', icon: UserPlus },
  { key: 'disconnect', label: 'On Disconnect', icon: UserMinus },
]

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()
}

// --- TimerRepeat helpers ---

const timerRepeatEntries = computed(() => {
  const obj = getConfigValue('TimerRepeat', {}) as Record<string, number>
  return Object.entries(obj).map(([command, interval]) => ({ command, interval }))
})

function addTimerRepeat() {
  const obj = { ...getConfigValue('TimerRepeat', {}) as Record<string, number> }
  obj['new.command'] = 300
  setConfigValue('TimerRepeat', obj)
}

function updateTimerRepeatCommand(oldCmd: string, newCmd: string) {
  const obj = { ...getConfigValue('TimerRepeat', {}) as Record<string, number> }
  const interval = obj[oldCmd] ?? 300
  delete obj[oldCmd]
  obj[newCmd] = interval
  setConfigValue('TimerRepeat', obj)
}

function updateTimerRepeatInterval(cmd: string, interval: number) {
  const obj = { ...getConfigValue('TimerRepeat', {}) as Record<string, number> }
  obj[cmd] = interval
  setConfigValue('TimerRepeat', obj)
}

function removeTimerRepeat(cmd: string) {
  const obj = { ...getConfigValue('TimerRepeat', {}) as Record<string, number> }
  delete obj[cmd]
  setConfigValue('TimerRepeat', obj)
}

function addPresetTimer(command: string, interval: number) {
  const obj = { ...getConfigValue('TimerRepeat', {}) as Record<string, number> }
  obj[command] = interval
  setConfigValue('TimerRepeat', obj)
}

// --- RealTime-Timer helpers ---

const realTimeEntries = computed(() => {
  const obj = getConfigValue('RealTime-Timer', {}) as Record<string, string>
  return Object.entries(obj).map(([time, command]) => ({ time, command }))
})

function addRealTimeEntry() {
  const obj = { ...getConfigValue('RealTime-Timer', {}) as Record<string, string> }
  obj['12:00:00'] = 'say Scheduled message'
  setConfigValue('RealTime-Timer', obj)
}

function updateRealTimeTime(oldTime: string, newTime: string) {
  const obj = { ...getConfigValue('RealTime-Timer', {}) as Record<string, string> }
  const command = obj[oldTime] ?? ''
  delete obj[oldTime]
  obj[newTime] = command
  setConfigValue('RealTime-Timer', obj)
}

function updateRealTimeCommand(time: string, command: string) {
  const obj = { ...getConfigValue('RealTime-Timer', {}) as Record<string, string> }
  obj[time] = command
  setConfigValue('RealTime-Timer', obj)
}

function removeRealTimeEntry(time: string) {
  const obj = { ...getConfigValue('RealTime-Timer', {}) as Record<string, string> }
  delete obj[time]
  setConfigValue('RealTime-Timer', obj)
}

// --- OnPlayerConnected helpers ---

const connectCommands = computed(() => {
  return (getConfigValue('OnPlayerConnectCommands', []) as string[])
})

function addConnectCommand() {
  const cmds = [...connectCommands.value, '']
  setConfigValue('OnPlayerConnectCommands', cmds)
}

function updateConnectCommand(index: number, value: string) {
  const cmds = [...connectCommands.value]
  cmds[index] = value
  setConfigValue('OnPlayerConnectCommands', cmds)
}

function removeConnectCommand(index: number) {
  const cmds = [...connectCommands.value]
  cmds.splice(index, 1)
  setConfigValue('OnPlayerConnectCommands', cmds)
}

// --- OnPlayerDisconnected helpers ---

const disconnectCommands = computed(() => {
  return (getConfigValue('OnPlayerDisconnectCommands', []) as string[])
})

function addDisconnectCommand() {
  const cmds = [...disconnectCommands.value, '']
  setConfigValue('OnPlayerDisconnectCommands', cmds)
}

function updateDisconnectCommand(index: number, value: string) {
  const cmds = [...disconnectCommands.value]
  cmds[index] = value
  setConfigValue('OnPlayerDisconnectCommands', cmds)
}

function removeDisconnectCommand(index: number) {
  const cmds = [...disconnectCommands.value]
  cmds.splice(index, 1)
  setConfigValue('OnPlayerDisconnectCommands', cmds)
}

// --- 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 TimedExecute 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">Timed Execute</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">
      <Clock class="w-12 h-12 text-neutral-600 mx-auto mb-4" />
      <h2 class="text-lg font-semibold text-neutral-300 mb-2">No TimedExecute 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">
      <!-- Tab Bar -->
      <div class="flex border-b border-neutral-800">
        <button
          v-for="tab in tabs"
          :key="tab.key"
          @click="activeTab = tab.key as typeof activeTab"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 transition-colors"
          :class="activeTab === tab.key
            ? 'border-oxide-500 text-oxide-400'
            : 'border-transparent text-neutral-500 hover:text-neutral-300'"
        >
          <component :is="tab.icon" class="w-4 h-4" />
          {{ tab.label }}
        </button>
      </div>

      <!-- Timed Commands Tab -->
      <div v-if="activeTab === 'timed'" class="space-y-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">Timer Repeat</h3>
              <p class="text-xs text-neutral-500 mt-1">Commands executed repeatedly at set intervals (seconds)</p>
            </div>
            <div class="flex items-center gap-2">
              <!-- Enable toggle -->
              <span class="text-xs text-neutral-400 mr-2">Enabled</span>
              <button
                @click="setConfigValue('EnableTimerRepeat', !getConfigValue('EnableTimerRepeat', true))"
                class="relative w-11 h-6 rounded-full transition-colors"
                :class="getConfigValue('EnableTimerRepeat', 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('EnableTimerRepeat', true) ? 'translate-x-5' : 'translate-x-0'"
                />
              </button>
            </div>
          </div>

          <!-- Preset Buttons -->
          <div class="flex items-center gap-2 flex-wrap">
            <span class="text-xs text-neutral-500">Quick add:</span>
            <button
              @click="addPresetTimer('server.save', 300)"
              class="px-2 py-1 text-xs bg-neutral-800 text-neutral-300 rounded hover:bg-neutral-700"
            >
              server.save (5m)
            </button>
            <button
              @click="addPresetTimer('say Server restart warning!', 3600)"
              class="px-2 py-1 text-xs bg-neutral-800 text-neutral-300 rounded hover:bg-neutral-700"
            >
              Restart warning (1h)
            </button>
            <button
              @click="addPresetTimer('oxide.reload *', 7200)"
              class="px-2 py-1 text-xs bg-neutral-800 text-neutral-300 rounded hover:bg-neutral-700"
            >
              Reload plugins (2h)
            </button>
          </div>

          <!-- Entries -->
          <div v-if="timerRepeatEntries.length === 0" class="py-4 text-center text-neutral-500 text-sm">
            No timed commands configured. Add a command or use a preset above.
          </div>

          <div v-else class="space-y-2">
            <div
              v-for="(entry, index) in timerRepeatEntries"
              :key="index"
              class="flex items-center gap-3 bg-neutral-800/50 rounded-lg p-3"
            >
              <input
                :value="entry.command"
                @change="updateTimerRepeatCommand(entry.command, ($event.target as HTMLInputElement).value)"
                placeholder="console command"
                class="flex-1 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-1.5 text-neutral-200 text-sm"
              />
              <div class="flex items-center gap-1">
                <input
                  :value="entry.interval"
                  @input="updateTimerRepeatInterval(entry.command, Number(($event.target as HTMLInputElement).value))"
                  type="number"
                  min="1"
                  class="w-24 bg-neutral-800 border border-neutral-700 rounded-lg px-2 py-1.5 text-neutral-200 text-sm text-right"
                />
                <span class="text-xs text-neutral-500">sec</span>
              </div>
              <button
                @click="removeTimerRepeat(entry.command)"
                class="p-1.5 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded"
              >
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          </div>

          <button
            @click="addTimerRepeat"
            class="flex items-center gap-2 px-3 py-1.5 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
          >
            <Plus class="w-4 h-4" />
            Add Command
          </button>
        </div>
      </div>

      <!-- Real-Time Tab -->
      <div v-else-if="activeTab === 'realtime'" class="space-y-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">Real-Time Timer</h3>
              <p class="text-xs text-neutral-500 mt-1">Commands executed at specific times of day (HH:MM:SS)</p>
            </div>
            <div class="flex items-center gap-2">
              <span class="text-xs text-neutral-400 mr-2">Enabled</span>
              <button
                @click="setConfigValue('EnableRealTime-Timer', !getConfigValue('EnableRealTime-Timer', false))"
                class="relative w-11 h-6 rounded-full transition-colors"
                :class="getConfigValue('EnableRealTime-Timer', false) ? '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('EnableRealTime-Timer', false) ? 'translate-x-5' : 'translate-x-0'"
                />
              </button>
            </div>
          </div>

          <div v-if="realTimeEntries.length === 0" class="py-4 text-center text-neutral-500 text-sm">
            No real-time commands configured. Add a time-based command below.
          </div>

          <div v-else class="space-y-2">
            <div
              v-for="(entry, index) in realTimeEntries"
              :key="index"
              class="flex items-center gap-3 bg-neutral-800/50 rounded-lg p-3"
            >
              <input
                :value="entry.time"
                @change="updateRealTimeTime(entry.time, ($event.target as HTMLInputElement).value)"
                placeholder="HH:MM:SS"
                class="w-32 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-1.5 text-neutral-200 text-sm"
              />
              <input
                :value="entry.command"
                @change="updateRealTimeCommand(entry.time, ($event.target as HTMLInputElement).value)"
                placeholder="console command"
                class="flex-1 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-1.5 text-neutral-200 text-sm"
              />
              <button
                @click="removeRealTimeEntry(entry.time)"
                class="p-1.5 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded"
              >
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          </div>

          <button
            @click="addRealTimeEntry"
            class="flex items-center gap-2 px-3 py-1.5 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
          >
            <Plus class="w-4 h-4" />
            Add Time Entry
          </button>
        </div>
      </div>

      <!-- On Connect Tab -->
      <div v-else-if="activeTab === 'connect'" class="space-y-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-4">
          <div>
            <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">On Player Connect</h3>
            <p class="text-xs text-neutral-500 mt-1">Commands executed when a player joins the server</p>
          </div>

          <div v-if="connectCommands.length === 0" class="py-4 text-center text-neutral-500 text-sm">
            No connect commands configured. Add a command below.
          </div>

          <div v-else class="space-y-2">
            <div
              v-for="(cmd, index) in connectCommands"
              :key="index"
              class="flex items-center gap-3 bg-neutral-800/50 rounded-lg p-3"
            >
              <input
                :value="cmd"
                @change="updateConnectCommand(index, ($event.target as HTMLInputElement).value)"
                placeholder='e.g. say Welcome {player.name}!'
                class="flex-1 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-1.5 text-neutral-200 text-sm"
              />
              <button
                @click="removeConnectCommand(index)"
                class="p-1.5 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded"
              >
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          </div>

          <button
            @click="addConnectCommand"
            class="flex items-center gap-2 px-3 py-1.5 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
          >
            <Plus class="w-4 h-4" />
            Add Command
          </button>
        </div>
      </div>

      <!-- On Disconnect Tab -->
      <div v-else-if="activeTab === 'disconnect'" class="space-y-4">
        <div class="bg-neutral-900 border border-neutral-800 rounded-xl p-6 space-y-4">
          <div>
            <h3 class="text-sm font-semibold text-neutral-300 uppercase tracking-wider">On Player Disconnect</h3>
            <p class="text-xs text-neutral-500 mt-1">Commands executed when a player leaves the server</p>
          </div>

          <div v-if="disconnectCommands.length === 0" class="py-4 text-center text-neutral-500 text-sm">
            No disconnect commands configured. Add a command below.
          </div>

          <div v-else class="space-y-2">
            <div
              v-for="(cmd, index) in disconnectCommands"
              :key="index"
              class="flex items-center gap-3 bg-neutral-800/50 rounded-lg p-3"
            >
              <input
                :value="cmd"
                @change="updateDisconnectCommand(index, ($event.target as HTMLInputElement).value)"
                placeholder='e.g. say {player.name} has left'
                class="flex-1 bg-neutral-800 border border-neutral-700 rounded-lg px-3 py-1.5 text-neutral-200 text-sm"
              />
              <button
                @click="removeDisconnectCommand(index)"
                class="p-1.5 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded"
              >
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          </div>

          <button
            @click="addDisconnectCommand"
            class="flex items-center gap-2 px-3 py-1.5 bg-neutral-800 text-neutral-300 rounded-lg hover:bg-neutral-700 text-sm"
          >
            <Plus class="w-4 h-4" />
            Add Command
          </button>
        </div>
      </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 TimedExecute 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 Timer 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 TimedExecute 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>
