<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useWipeStore } from '@/stores/wipe'
import { useServerStore } from '@/stores/server'
import { useToastStore } from '@/stores/toast'
import { useApi } from '@/composables/useApi'
import { RefreshCw, Zap, Clock, AlertTriangle, Loader2, Check, X } from 'lucide-vue-next'
import { RouterLink } from 'vue-router'
import { safeDate } from '@/utils/formatters'

const wipeStore = useWipeStore()
const server = useServerStore()
const toast = useToastStore()
const api = useApi()

const triggerType = ref<'map' | 'blueprint' | 'full'>('map')
const selectedProfileId = ref<string>('')
const triggerLoading = ref(false)
const dryRunLoading = ref(false)
const scheduleToggling = ref<string | null>(null)

interface DryRunResult {
  would_delete: string[]
  would_preserve: string[]
  estimated_duration_seconds: number
}

const dryRunResult = ref<DryRunResult | null>(null)

async function triggerWipe() {
  if (!confirm(`Trigger a ${triggerType.value} wipe? This cannot be undone.`)) return
  triggerLoading.value = true
  try {
    await wipeStore.triggerWipe(triggerType.value, selectedProfileId.value)
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to trigger wipe')
  } finally {
    triggerLoading.value = false
  }
}

async function triggerDryRun() {
  dryRunLoading.value = true
  dryRunResult.value = null
  try {
    const result = await wipeStore.triggerDryRun(triggerType.value, selectedProfileId.value)
    dryRunResult.value = result
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to run dry-run')
  } finally {
    dryRunLoading.value = false
  }
}

async function toggleSchedule(scheduleId: string, currentlyActive: boolean) {
  scheduleToggling.value = scheduleId
  try {
    await api.put(`/wipes/schedules/${scheduleId}`, { is_active: !currentlyActive })
    await wipeStore.fetchSchedules()
    toast.success(`Schedule ${currentlyActive ? 'paused' : 'activated'}`)
  } catch {
    toast.error('Failed to update schedule')
  } finally {
    scheduleToggling.value = null
  }
}

onMounted(async () => {
  await wipeStore.fetchProfiles()
  if (wipeStore.profiles.length > 0 && wipeStore.profiles[0]) {
    selectedProfileId.value = wipeStore.profiles[0].id
  }
  wipeStore.fetchSchedules()
  wipeStore.fetchHistory()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <RefreshCw class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Auto-Wiper</h1>
      </div>
      <div class="flex gap-2">
        <RouterLink
          to="/wipes/profiles"
          class="px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          Profiles
        </RouterLink>
        <RouterLink
          to="/wipes/calendar"
          class="px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          Calendar
        </RouterLink>
        <RouterLink
          to="/wipes/history"
          class="px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          History
        </RouterLink>
      </div>
    </div>

    <!-- Manual Trigger -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
      <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Manual Wipe</h2>
      <div v-if="wipeStore.profiles.length === 0" class="mb-4 flex items-center gap-2 text-sm text-yellow-400 bg-yellow-500/10 border border-yellow-500/20 rounded-lg px-4 py-2">
        <AlertTriangle class="w-4 h-4 shrink-0" />
        No wipe profiles found. <RouterLink to="/wipes/profiles" class="underline hover:text-yellow-300 ml-1">Create a profile</RouterLink> before triggering a wipe.
      </div>
      <div class="flex items-end gap-4">
        <div>
          <label class="block text-xs text-neutral-500 mb-2">Wipe Type</label>
          <div class="flex bg-neutral-800 rounded-lg border border-neutral-700 overflow-hidden">
            <button
              v-for="opt in (['map', 'blueprint', 'full'] as const)"
              :key="opt"
              @click="triggerType = opt"
              class="px-4 py-2 text-sm font-medium transition-colors capitalize"
              :class="triggerType === opt ? 'bg-oxide-500/15 text-oxide-400' : 'text-neutral-400 hover:text-neutral-200'"
            >
              {{ opt }}
            </button>
          </div>
        </div>
        <div>
          <label class="block text-xs text-neutral-500 mb-2">Profile</label>
          <select
            v-model="selectedProfileId"
            :disabled="wipeStore.profiles.length === 0"
            class="px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors disabled:opacity-50"
          >
            <option value="">No profile</option>
            <option v-for="profile in wipeStore.profiles" :key="profile.id" :value="profile.id">
              {{ profile.profile_name }}
            </option>
          </select>
        </div>
        <button
          @click="triggerDryRun"
          :disabled="dryRunLoading || wipeStore.profiles.length === 0"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 disabled:opacity-50 border border-neutral-700 rounded-lg transition-colors"
        >
          <Loader2 v-if="dryRunLoading" class="w-4 h-4 animate-spin" />
          <AlertTriangle v-else class="w-4 h-4" />
          Dry Run
        </button>
        <button
          @click="triggerWipe"
          :disabled="triggerLoading || wipeStore.profiles.length === 0 || server.connection?.connection_status !== 'connected'"
          class="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-red-600 hover:bg-red-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
        >
          <Loader2 v-if="triggerLoading" class="w-4 h-4 animate-spin" />
          <Zap v-else class="w-4 h-4" />
          Trigger Wipe
        </button>
      </div>
    </div>

    <!-- Dry-Run Results -->
    <div v-if="dryRunResult" class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">Dry-Run Results</h2>
        <div class="flex items-center gap-3">
          <span class="text-xs text-neutral-500">
            Estimated: {{ Math.round(dryRunResult.estimated_duration_seconds) }}s
          </span>
          <button
            @click="dryRunResult = null"
            class="p-1 text-neutral-500 hover:text-neutral-300 rounded transition-colors"
          >
            <X class="w-4 h-4" />
          </button>
        </div>
      </div>
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div>
          <p class="text-xs font-medium text-red-400 mb-2 flex items-center gap-1.5">
            <X class="w-3.5 h-3.5" />
            Would Delete ({{ dryRunResult.would_delete.length }})
          </p>
          <div v-if="dryRunResult.would_delete.length === 0" class="text-xs text-neutral-600 italic">Nothing to delete</div>
          <ul v-else class="space-y-1">
            <li
              v-for="item in dryRunResult.would_delete"
              :key="item"
              class="text-xs font-mono text-neutral-400 bg-red-500/5 border border-red-500/10 rounded px-2 py-1"
            >{{ item }}</li>
          </ul>
        </div>
        <div>
          <p class="text-xs font-medium text-green-400 mb-2 flex items-center gap-1.5">
            <Check class="w-3.5 h-3.5" />
            Would Preserve ({{ dryRunResult.would_preserve.length }})
          </p>
          <div v-if="dryRunResult.would_preserve.length === 0" class="text-xs text-neutral-600 italic">Nothing preserved</div>
          <ul v-else class="space-y-1">
            <li
              v-for="item in dryRunResult.would_preserve"
              :key="item"
              class="text-xs font-mono text-neutral-400 bg-green-500/5 border border-green-500/10 rounded px-2 py-1"
            >{{ item }}</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- Upcoming Schedules -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
      <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider mb-4">Scheduled Wipes</h2>
      <div v-if="wipeStore.schedules.length === 0" class="text-sm text-neutral-500 py-4 text-center">
        No wipe schedules configured. Create a profile and schedule to automate wipes.
      </div>
      <div v-else class="space-y-3">
        <div
          v-for="schedule in wipeStore.schedules"
          :key="schedule.id"
          class="flex items-center justify-between p-3 bg-neutral-800/50 rounded-lg"
        >
          <div class="flex items-center gap-3">
            <Clock class="w-4 h-4 text-neutral-500" />
            <div>
              <p class="text-sm font-medium text-neutral-200">{{ schedule.schedule_name }}</p>
              <p class="text-xs text-neutral-500">
                {{ schedule.wipe_type }} wipe &middot; {{ schedule.cron_expression }} ({{ schedule.timezone }})
              </p>
            </div>
          </div>
          <div class="flex items-center gap-3">
            <span
              class="text-xs font-medium px-2 py-0.5 rounded-full"
              :class="schedule.is_active ? 'bg-green-500/10 text-green-400' : 'bg-neutral-700/50 text-neutral-400'"
            >
              {{ schedule.is_active ? 'Active' : 'Paused' }}
            </span>
            <button
              @click="toggleSchedule(schedule.id, schedule.is_active)"
              :disabled="scheduleToggling === schedule.id"
              class="w-9 h-5 rounded-full transition-colors disabled:opacity-40 cursor-pointer"
              :class="schedule.is_active ? 'bg-oxide-500' : 'bg-neutral-700'"
              :title="schedule.is_active ? 'Pause schedule' : 'Activate schedule'"
            >
              <Loader2 v-if="scheduleToggling === schedule.id" class="w-3.5 h-3.5 text-white animate-spin mx-auto" />
              <div
                v-else
                class="w-4 h-4 bg-white rounded-full shadow transition-transform mt-0.5"
                :class="schedule.is_active ? 'translate-x-4.5' : 'translate-x-0.5'"
              />
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent History -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg p-5">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-sm font-medium text-neutral-400 uppercase tracking-wider">Recent Wipes</h2>
        <RouterLink to="/wipes/history" class="text-sm text-oxide-400 hover:text-oxide-300 transition-colors">
          View All
        </RouterLink>
      </div>
      <div v-if="wipeStore.history.length === 0" class="text-sm text-neutral-500 py-4 text-center">
        No wipe history yet.
      </div>
      <div v-else class="space-y-2">
        <div
          v-for="wipe in wipeStore.history.slice(0, 5)"
          :key="wipe.id"
          class="flex items-center justify-between p-3 bg-neutral-800/50 rounded-lg"
        >
          <div>
            <p class="text-sm text-neutral-200">{{ wipe.wipe_type }} wipe</p>
            <p class="text-xs text-neutral-500">{{ wipe.trigger_type }} &middot; {{ safeDate(wipe.started_at, 'Pending') }}</p>
          </div>
          <span
            class="text-xs font-medium px-2 py-0.5 rounded-full"
            :class="{
              'bg-green-500/10 text-green-400': wipe.status === 'success',
              'bg-red-500/10 text-red-400': wipe.status === 'failed' || wipe.status === 'rolled_back',
              'bg-yellow-500/10 text-yellow-400': wipe.status === 'wiping' || wipe.status === 'pre_wipe' || wipe.status === 'post_wipe',
              'bg-neutral-700/50 text-neutral-400': wipe.status === 'pending',
            }"
          >
            {{ wipe.status }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>
