<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useWipeStore } from '@/stores/wipe'
import { useToastStore } from '@/stores/toast'
import { useThemeGame } from '@/composables/useThemeGame'
import { useGameProfile } from '@/config/gameProfiles'
import type { WipeProfile } from '@/types'
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 IconButton from '@/components/ds/core/IconButton.vue'
import Input from '@/components/ds/forms/Input.vue'
import Checkbox from '@/components/ds/forms/Checkbox.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const wipeStore = useWipeStore()
const toast = useToastStore()
const { activeGame } = useThemeGame()
const gameProfile = computed(() => useGameProfile(activeGame.value === 'all' ? 'rust' : activeGame.value))

const expandedId = ref<string | null>(null)
const showModal = ref(false)
const editingProfile = ref<WipeProfile | null>(null)
const isSaving = ref(false)

const defaultForm = () => ({
  profile_name: '',
  description: '',
  pre_wipe_config: {
    enabled: true,
    backup_before_wipe: true,
    countdown_warnings: [30, 10, 5],
    countdown_unit: 'minutes',
    countdown_messages: {} as Record<string, string>,
    kick_players_before_wipe: false,
    kick_message: 'Server is wiping, back soon!',
    run_final_save: true,
    discord_pre_announce: false,
    pushbullet_notify: false,
    custom_commands_before: [] as string[],
  },
  post_wipe_config: {
    enabled: true,
    verify_server_started: true,
    verify_correct_map: true,
    verify_plugins_loaded: true,
    verify_player_slots_open: false,
    max_restart_attempts: 3,
    health_check_timeout_seconds: 120,
    discord_post_announce: false,
    pushbullet_notify: false,
    rollback_on_failure: true,
    post_wipe_commands: [] as string[],
  },
})

const form = ref(defaultForm())

function toggle(id: string) {
  expandedId.value = expandedId.value === id ? null : id
}

function openCreateModal() {
  editingProfile.value = null
  form.value = defaultForm()
  showModal.value = true
}

function openEditModal(profile: WipeProfile) {
  editingProfile.value = profile
  form.value = {
    profile_name: profile.profile_name,
    description: profile.description || '',
    pre_wipe_config: {
      enabled: profile.pre_wipe_config.enabled,
      backup_before_wipe: profile.pre_wipe_config.backup_before_wipe,
      countdown_warnings: [...profile.pre_wipe_config.countdown_warnings],
      countdown_unit: profile.pre_wipe_config.countdown_unit,
      countdown_messages: { ...profile.pre_wipe_config.countdown_messages },
      kick_players_before_wipe: profile.pre_wipe_config.kick_players_before_wipe,
      kick_message: profile.pre_wipe_config.kick_message,
      run_final_save: profile.pre_wipe_config.run_final_save,
      discord_pre_announce: profile.pre_wipe_config.discord_pre_announce,
      pushbullet_notify: profile.pre_wipe_config.pushbullet_notify,
      custom_commands_before: [...profile.pre_wipe_config.custom_commands_before],
    },
    post_wipe_config: {
      enabled: profile.post_wipe_config.enabled,
      verify_server_started: profile.post_wipe_config.verify_server_started,
      verify_correct_map: profile.post_wipe_config.verify_correct_map,
      verify_plugins_loaded: profile.post_wipe_config.verify_plugins_loaded,
      verify_player_slots_open: profile.post_wipe_config.verify_player_slots_open,
      max_restart_attempts: profile.post_wipe_config.max_restart_attempts,
      health_check_timeout_seconds: profile.post_wipe_config.health_check_timeout_seconds,
      discord_post_announce: profile.post_wipe_config.discord_post_announce,
      pushbullet_notify: profile.post_wipe_config.pushbullet_notify,
      rollback_on_failure: profile.post_wipe_config.rollback_on_failure,
      post_wipe_commands: [...profile.post_wipe_config.post_wipe_commands],
    },
  }
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  editingProfile.value = null
}

async function saveProfile() {
  if (!form.value.profile_name.trim()) {
    toast.error('Profile name is required')
    return
  }
  isSaving.value = true
  try {
    if (editingProfile.value) {
      await wipeStore.updateProfile(editingProfile.value.id, form.value)
      toast.success(`Profile "${form.value.profile_name}" updated`)
    } else {
      await wipeStore.createProfile(form.value)
      toast.success(`Profile "${form.value.profile_name}" created`)
    }
    closeModal()
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to save profile')
  } finally {
    isSaving.value = false
  }
}

async function deleteProfile(profile: WipeProfile) {
  if (!confirm(`Delete profile "${profile.profile_name}"? This cannot be undone.`)) return
  try {
    await wipeStore.deleteProfile(profile.id)
    toast.success(`Profile "${profile.profile_name}" deleted`)
    if (expandedId.value === profile.id) expandedId.value = null
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to delete profile')
  }
}

onMounted(() => {
  wipeStore.fetchProfiles()
})
</script>

<template>
  <div class="profiles">
    <!-- Page head -->
    <div class="page__head">
      <div>
        <div class="t-eyebrow">Operations</div>
        <h1 class="page__title">Wipe profiles</h1>
      </div>
      <Button icon="plus" @click="openCreateModal">New profile</Button>
    </div>

    <!-- Empty state -->
    <Panel v-if="wipeStore.profiles.length === 0">
      <EmptyState
        icon="file-text"
        title="No wipe profiles"
        description="Create a profile to define pre-wipe and post-wipe behavior."
      >
        <template #action>
          <Button icon="plus" size="sm" @click="openCreateModal">New profile</Button>
        </template>
      </EmptyState>
    </Panel>

    <!-- Profile list -->
    <div v-else class="profile-list">
      <Panel
        v-for="profile in wipeStore.profiles"
        :key="profile.id"
        :flush-body="true"
      >
        <template #title-append>
          <!-- Nothing — title is injected via Panel slot at row level instead -->
        </template>

        <!-- Accordion row header -->
        <div class="profile-row">
          <button
            type="button"
            class="profile-toggle"
            @click="toggle(profile.id)"
          >
            <div class="profile-meta">
              <span class="profile-name">{{ profile.profile_name }}</span>
              <span class="profile-desc">{{ profile.description || 'No description' }}</span>
            </div>
            <span class="profile-chev" :class="expandedId === profile.id && 'profile-chev--open'">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="6 9 12 15 18 9" />
              </svg>
            </span>
          </button>
          <div class="profile-actions">
            <IconButton icon="pencil" size="sm" label="Edit" @click="openEditModal(profile)" />
            <IconButton icon="trash-2" variant="danger" size="sm" label="Delete" @click="deleteProfile(profile)" />
          </div>
        </div>

        <!-- Expanded detail -->
        <div v-if="expandedId === profile.id" class="profile-detail">
          <div class="detail-grid">
            <!-- Pre-wipe -->
            <div>
              <div class="t-eyebrow detail-eyebrow">Pre-wipe</div>
              <div class="detail-rows">
                <div class="detail-kv">
                  <span class="detail-k">Backup before wipe</span>
                  <Badge :tone="profile.pre_wipe_config.backup_before_wipe ? 'online' : 'neutral'">
                    {{ profile.pre_wipe_config.backup_before_wipe ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div class="detail-kv">
                  <span class="detail-k">Kick players</span>
                  <Badge :tone="profile.pre_wipe_config.kick_players_before_wipe ? 'online' : 'neutral'">
                    {{ profile.pre_wipe_config.kick_players_before_wipe ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div class="detail-kv">
                  <span class="detail-k">Final save</span>
                  <Badge :tone="profile.pre_wipe_config.run_final_save ? 'online' : 'neutral'">
                    {{ profile.pre_wipe_config.run_final_save ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div class="detail-kv">
                  <span class="detail-k">Discord announce</span>
                  <Badge :tone="profile.pre_wipe_config.discord_pre_announce ? 'online' : 'neutral'">
                    {{ profile.pre_wipe_config.discord_pre_announce ? 'Yes' : 'No' }}
                  </Badge>
                </div>
              </div>
            </div>

            <!-- Post-wipe -->
            <div>
              <div class="t-eyebrow detail-eyebrow">Post-wipe</div>
              <div class="detail-rows">
                <div class="detail-kv">
                  <span class="detail-k">Verify server started</span>
                  <Badge :tone="profile.post_wipe_config.verify_server_started ? 'online' : 'neutral'">
                    {{ profile.post_wipe_config.verify_server_started ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div v-if="gameProfile.mods === 'umod'" class="detail-kv">
                  <span class="detail-k">Verify plugins loaded</span>
                  <Badge :tone="profile.post_wipe_config.verify_plugins_loaded ? 'online' : 'neutral'">
                    {{ profile.post_wipe_config.verify_plugins_loaded ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div class="detail-kv">
                  <span class="detail-k">Rollback on failure</span>
                  <Badge :tone="profile.post_wipe_config.rollback_on_failure ? 'accent' : 'neutral'">
                    {{ profile.post_wipe_config.rollback_on_failure ? 'Yes' : 'No' }}
                  </Badge>
                </div>
                <div class="detail-kv">
                  <span class="detail-k">Max restart attempts</span>
                  <span class="detail-v-mono">{{ profile.post_wipe_config.max_restart_attempts }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Panel>
    </div>
  </div>

  <!-- Create / Edit Modal -->
  <Teleport to="body">
    <div
      v-if="showModal"
      class="modal-backdrop"
      @click.self="closeModal"
    >
      <div class="modal">
        <!-- Modal header -->
        <div class="modal__head">
          <h2 class="modal__title">{{ editingProfile ? 'Edit profile' : 'New profile' }}</h2>
          <IconButton icon="x" label="Close" @click="closeModal" />
        </div>

        <div class="modal__body">
          <!-- Basic info -->
          <div class="form-section">
            <div class="t-eyebrow form-section__eyebrow">Basic information</div>
            <Input
              v-model="form.profile_name"
              label="Profile name"
              placeholder="Default wipe profile"
              :required="true"
            />
            <div class="cc-field">
              <span class="cc-field__label">Description (optional)</span>
              <textarea
                v-model="form.description"
                rows="2"
                placeholder="Standard wipe configuration for monthly force wipes"
                class="cc-textarea"
              />
            </div>
          </div>

          <!-- Pre-wipe config -->
          <div class="form-section">
            <div class="form-section__row">
              <div class="t-eyebrow">Pre-wipe</div>
              <Checkbox
                v-model="form.pre_wipe_config.enabled"
                label="Enabled"
              />
            </div>
            <div class="check-grid">
              <Checkbox
                v-model="form.pre_wipe_config.backup_before_wipe"
                label="Backup before wipe"
              />
              <Checkbox
                v-model="form.pre_wipe_config.run_final_save"
                label="Run final save"
              />
              <Checkbox
                v-model="form.pre_wipe_config.kick_players_before_wipe"
                label="Kick players before wipe"
              />
              <Checkbox
                v-model="form.pre_wipe_config.discord_pre_announce"
                label="Discord pre-announce"
              />
              <Checkbox
                v-model="form.pre_wipe_config.pushbullet_notify"
                label="Pushbullet notify"
              />
            </div>
            <Input
              v-if="form.pre_wipe_config.kick_players_before_wipe"
              v-model="form.pre_wipe_config.kick_message"
              label="Kick message"
              placeholder="Server is wiping, back soon!"
            />
          </div>

          <!-- Post-wipe config -->
          <div class="form-section">
            <div class="form-section__row">
              <div class="t-eyebrow">Post-wipe</div>
              <Checkbox
                v-model="form.post_wipe_config.enabled"
                label="Enabled"
              />
            </div>
            <div class="check-grid">
              <Checkbox
                v-model="form.post_wipe_config.verify_server_started"
                label="Verify server started"
              />
              <Checkbox
                v-model="form.post_wipe_config.verify_correct_map"
                label="Verify correct map"
              />
              <Checkbox
                v-if="gameProfile.mods === 'umod'"
                v-model="form.post_wipe_config.verify_plugins_loaded"
                label="Verify plugins loaded"
              />
              <Checkbox
                v-model="form.post_wipe_config.verify_player_slots_open"
                label="Verify player slots open"
              />
              <Checkbox
                v-model="form.post_wipe_config.rollback_on_failure"
                label="Rollback on failure"
              />
              <Checkbox
                v-model="form.post_wipe_config.discord_post_announce"
                label="Discord post-announce"
              />
            </div>
            <div class="number-grid">
              <div class="cc-field">
                <span class="cc-field__label">Max restart attempts</span>
                <span class="cc-input cc-input--mono">
                  <input
                    v-model.number="form.post_wipe_config.max_restart_attempts"
                    type="number"
                    min="1"
                    max="10"
                  />
                </span>
              </div>
              <div class="cc-field">
                <span class="cc-field__label">Health check timeout (s)</span>
                <span class="cc-input cc-input--mono">
                  <input
                    v-model.number="form.post_wipe_config.health_check_timeout_seconds"
                    type="number"
                    min="30"
                    max="600"
                  />
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- Modal footer -->
        <div class="modal__foot">
          <Button variant="secondary" @click="closeModal">Cancel</Button>
          <Button
            :loading="isSaving"
            @click="saveProfile"
          >
            {{ editingProfile ? 'Save changes' : 'Create profile' }}
          </Button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.profiles {
  max-width: 900px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}

/* Page head */
.page__head {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}
.page__title {
  font-size: var(--text-3xl);
  font-weight: 700;
  letter-spacing: -0.02em;
  color: var(--text-primary);
  margin-top: 4px;
}

/* Profile list */
.profile-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* Profile row inside panel */
.profile-row {
  display: flex;
  align-items: center;
}
.profile-toggle {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px;
  background: transparent;
  border: 0;
  cursor: pointer;
  text-align: left;
  gap: 12px;
  transition: var(--transition-colors);
}
.profile-toggle:hover { background: var(--surface-hover); }
.profile-meta { display: flex; flex-direction: column; gap: 2px; }
.profile-name {
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
}
.profile-desc {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}
.profile-chev {
  color: var(--text-tertiary);
  transition: transform var(--dur-base) var(--ease-standard);
  display: flex;
}
.profile-chev--open { transform: rotate(180deg); }
.profile-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  padding-right: 12px;
}

/* Expanded detail */
.profile-detail {
  border-top: 1px solid var(--border-subtle);
  padding: 16px;
}
.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}
.detail-eyebrow { margin-bottom: 10px; }
.detail-rows {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.detail-kv {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}
.detail-k {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}
.detail-v-mono {
  font-family: var(--font-mono);
  font-size: var(--text-xs);
  font-variant-numeric: tabular-nums;
  color: var(--text-secondary);
}

/* Modal */
.modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 50;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
  padding: 16px;
}
.modal {
  background: var(--surface-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-xl, 0 24px 60px rgba(0,0,0,.45));
  width: 100%;
  max-width: 660px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.modal__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-subtle);
  flex: none;
}
.modal__title {
  font-size: var(--text-lg);
  font-weight: 700;
  color: var(--text-primary);
}
.modal__body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.modal__foot {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  padding: 14px 20px;
  border-top: 1px solid var(--border-subtle);
  flex: none;
}

/* Form sections */
.form-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.form-section__eyebrow { margin-bottom: 4px; }
.form-section__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.check-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}
.number-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

/* Textarea token-based */
.cc-textarea {
  width: 100%;
  padding: 9px 11px;
  background: var(--surface-inset);
  border: 0;
  border-radius: var(--radius-md);
  box-shadow: var(--ring-default);
  color: var(--text-primary);
  font-family: var(--font-sans);
  font-size: var(--text-sm);
  line-height: 1.5;
  resize: vertical;
  outline: 0;
  transition: var(--transition-colors);
  box-sizing: border-box;
}
.cc-textarea::placeholder { color: var(--text-muted); }
.cc-textarea:focus { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }

@media (max-width: 640px) {
  .detail-grid { grid-template-columns: 1fr; }
  .check-grid { grid-template-columns: 1fr; }
  .number-grid { grid-template-columns: 1fr; }
}
</style>
