<script setup lang="ts">
import { ref } from 'vue'
import { useAgentsStore, HOOK_EVENT_TYPES } from '../../stores/agents'
import type { HookEntry, HookCommand } from '../../stores/agents'

const store = useAgentsStore()
const editingHook = ref<{ eventType: string; index: number } | null>(null)
const editMatcher = ref('')
const editCommand = ref('')
const editTimeout = ref(5000)

function hookCount(eventType: string): number {
  return store.hooksConfig[eventType]?.length || 0
}

function totalHookCount(): number {
  return Object.values(store.hooksConfig).reduce((sum, arr) => sum + (arr?.length || 0), 0)
}

function startEdit(eventType: string, index: number) {
  const entry = store.hooksConfig[eventType]?.[index]
  if (!entry) return
  editingHook.value = { eventType, index }
  editMatcher.value = entry.matcher || ''
  editCommand.value = entry.hooks?.[0]?.command || ''
  editTimeout.value = entry.hooks?.[0]?.timeout || 5000
}

function saveEdit() {
  if (!editingHook.value) return
  const { eventType, index } = editingHook.value

  const entry: HookEntry = {
    matcher: editMatcher.value.trim() || null,
    hooks: [{
      type: 'command',
      command: editCommand.value.trim(),
      timeout: editTimeout.value
    }]
  }

  store.updateHook(eventType, index, entry)
  editingHook.value = null
}

function cancelEdit() {
  editingHook.value = null
}

function truncateCommand(cmd: string, max = 60): string {
  return cmd.length > max ? cmd.slice(0, max) + '...' : cmd
}

const eventTypeLabels: Record<string, string> = {
  'UserPromptSubmit': 'User Prompt Submit',
  'PreToolUse': 'Pre Tool Use',
  'PostToolUse': 'Post Tool Use',
  'SessionStart': 'Session Start',
  'Stop': 'Stop',
  'Notification': 'Notification',
  'PermissionRequest': 'Permission Request'
}

const eventTypeColors: Record<string, string> = {
  'UserPromptSubmit': '#3b82f6',
  'PreToolUse': '#f59e0b',
  'PostToolUse': '#22c55e',
  'SessionStart': '#6366f1',
  'Stop': '#ef4444',
  'Notification': '#8b5cf6',
  'PermissionRequest': '#06b6d4'
}
</script>

<template>
  <div class="hooks-manager">
    <!-- Header -->
    <div class="hooks-header">
      <div class="hooks-header-left">
        <h3>Hooks</h3>
        <span class="hooks-count">{{ totalHookCount() }} hooks</span>
        <span v-if="store.configFile" class="hooks-path">{{ store.configFile }}</span>
      </div>
      <div class="hooks-header-right">
        <button
          class="btn btn-primary"
          :disabled="store.saving"
          @click="store.saveHooks()"
        >{{ store.saving ? 'Saving...' : 'Save Hooks' }}</button>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="store.hooksLoading" class="hooks-loading">Loading hooks...</div>

    <!-- Error -->
    <div v-if="store.error" class="hooks-error">{{ store.error }}</div>

    <!-- Hook sections by event type -->
    <div v-if="!store.hooksLoading" class="hooks-scroll">
      <div v-for="eventType in HOOK_EVENT_TYPES" :key="eventType" class="hook-section">
        <button
          class="hook-section-header"
          @click="store.toggleHookType(eventType)"
        >
          <span class="hook-dot" :style="{ background: eventTypeColors[eventType] }"></span>
          <span class="hook-type-label">{{ eventTypeLabels[eventType] || eventType }}</span>
          <span
            v-if="hookCount(eventType)"
            class="hook-type-count"
            :style="{ background: eventTypeColors[eventType] + '18', color: eventTypeColors[eventType] }"
          >{{ hookCount(eventType) }}</span>
          <svg
            class="hook-chevron"
            :class="{ expanded: store.expandedHookTypes.has(eventType) }"
            xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"
            fill="none" stroke="currentColor" stroke-width="2"
          >
            <polyline points="6 9 12 15 18 9"/>
          </svg>
        </button>

        <div v-if="store.expandedHookTypes.has(eventType)" class="hook-section-body">
          <!-- Hook entries -->
          <div
            v-for="(entry, idx) in (store.hooksConfig[eventType] || [])"
            :key="idx"
            class="hook-entry"
          >
            <!-- View mode -->
            <template v-if="!editingHook || editingHook.eventType !== eventType || editingHook.index !== idx">
              <div class="hook-entry-info">
                <div v-if="entry.matcher" class="hook-matcher">
                  <span class="entry-label">Matcher</span>
                  <code>{{ entry.matcher }}</code>
                </div>
                <div v-for="(hook, hIdx) in entry.hooks" :key="hIdx" class="hook-command-row">
                  <span class="entry-label">Command</span>
                  <code :title="hook.command">{{ truncateCommand(hook.command) }}</code>
                  <span v-if="hook.timeout" class="hook-timeout">{{ hook.timeout }}ms</span>
                </div>
              </div>
              <div class="hook-entry-actions">
                <button class="btn-link" @click="startEdit(eventType, idx)">Edit</button>
                <button class="btn-link danger" @click="store.removeHook(eventType, idx)">Remove</button>
              </div>
            </template>

            <!-- Edit mode -->
            <template v-else>
              <div class="hook-edit-form">
                <div class="form-row">
                  <label>Matcher</label>
                  <input type="text" v-model="editMatcher" placeholder=".*  (regex or empty)" />
                </div>
                <div class="form-row">
                  <label>Command</label>
                  <textarea v-model="editCommand" rows="2" placeholder="bash script.sh"></textarea>
                </div>
                <div class="form-row">
                  <label>Timeout (ms)</label>
                  <input type="number" v-model.number="editTimeout" />
                </div>
                <div class="form-row-actions">
                  <button class="btn btn-secondary btn-xs" @click="cancelEdit">Cancel</button>
                  <button class="btn btn-primary btn-xs" @click="saveEdit">Save</button>
                </div>
              </div>
            </template>
          </div>

          <!-- Empty state for this type -->
          <div v-if="!hookCount(eventType)" class="hook-empty">No hooks configured</div>

          <!-- Add button -->
          <button class="hook-add-btn" @click="store.addHook(eventType)">
            + Add hook
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.hooks-manager {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.hooks-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1.25rem;
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-secondary);
  gap: 1rem;
  flex-shrink: 0;
}

.hooks-header-left {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.hooks-header-left h3 {
  margin: 0;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

.hooks-count {
  font-size: 0.6875rem;
  color: var(--text-muted);
  padding: 0.125rem 0.5rem;
  background: var(--bg-hover);
  border-radius: 999px;
}

.hooks-path {
  font-size: 0.6875rem;
  color: var(--text-muted);
  font-family: 'Consolas', monospace;
}

.hooks-header-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.hooks-loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
  font-size: 0.8125rem;
}

.hooks-error {
  padding: 0.625rem 1.25rem;
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  font-size: 0.8125rem;
  border-bottom: 1px solid rgba(239, 68, 68, 0.2);
}

.hooks-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 0.75rem 1.25rem;
}

/* Hook sections */
.hook-section {
  margin-bottom: 4px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
}

.hook-section-header {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 0.75rem;
  background: var(--bg-secondary);
  border: none;
  color: var(--text-primary);
  font-size: 0.8125rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.15s;
}

.hook-section-header:hover {
  background: var(--bg-hover);
}

.hook-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.hook-type-label {
  flex: 1;
  text-align: left;
}

.hook-type-count {
  font-size: 0.625rem;
  font-weight: 600;
  padding: 0.0625rem 0.4375rem;
  border-radius: 999px;
}

.hook-chevron {
  color: var(--text-muted);
  transition: transform 0.2s;
  flex-shrink: 0;
  transform: rotate(-90deg);
}

.hook-chevron.expanded {
  transform: rotate(0deg);
}

.hook-section-body {
  border-top: 1px solid var(--border-color);
  padding: 0.5rem 0.75rem;
  background: var(--bg-primary);
}

/* Hook entries */
.hook-entry {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 0.5rem 0;
  gap: 0.5rem;
}

.hook-entry + .hook-entry {
  border-top: 1px solid var(--border-color);
}

.hook-entry-info {
  flex: 1;
  min-width: 0;
}

.hook-matcher,
.hook-command-row {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  padding: 0.125rem 0;
}

.entry-label {
  font-size: 0.5625rem;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  min-width: 55px;
  flex-shrink: 0;
}

.hook-entry code {
  font-size: 0.6875rem;
  color: var(--text-secondary);
  font-family: 'Consolas', monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hook-timeout {
  font-size: 0.625rem;
  color: var(--text-muted);
  flex-shrink: 0;
}

.hook-entry-actions {
  display: flex;
  gap: 0.5rem;
  flex-shrink: 0;
  padding-top: 0.125rem;
}

.btn-link {
  background: none;
  border: none;
  color: #6366f1;
  font-size: 0.6875rem;
  font-weight: 500;
  cursor: pointer;
  padding: 0;
}

.btn-link:hover {
  text-decoration: underline;
}

.btn-link.danger {
  color: #ef4444;
}

/* Edit form */
.hook-edit-form {
  width: 100%;
  padding: 0.5rem 0;
}

.form-row {
  margin-bottom: 0.5rem;
}

.form-row label {
  display: block;
  font-size: 0.625rem;
  font-weight: 600;
  color: var(--text-muted);
  margin-bottom: 0.1875rem;
  text-transform: uppercase;
}

.form-row input,
.form-row textarea {
  width: 100%;
  padding: 0.3125rem 0.5rem;
  font-size: 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  outline: none;
  font-family: 'Consolas', monospace;
  box-sizing: border-box;
}

.form-row input:focus,
.form-row textarea:focus {
  border-color: #6366f1;
}

.form-row-actions {
  display: flex;
  gap: 0.375rem;
  justify-content: flex-end;
}

.hook-empty {
  padding: 0.5rem 0;
  font-size: 0.6875rem;
  color: var(--text-muted);
  text-align: center;
}

.hook-add-btn {
  background: none;
  border: none;
  color: #6366f1;
  font-size: 0.6875rem;
  cursor: pointer;
  padding: 0.375rem 0;
  width: 100%;
  text-align: center;
}

.hook-add-btn:hover {
  text-decoration: underline;
}

/* Buttons */
.btn {
  padding: 0.3125rem 0.75rem;
  font-size: 0.75rem;
  font-weight: 500;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.15s;
}

.btn-xs {
  padding: 0.1875rem 0.5rem;
  font-size: 0.6875rem;
}

.btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--bg-secondary);
  color: var(--text-secondary);
}

.btn-secondary:hover:not(:disabled) {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.btn-primary {
  background: #6366f1;
  color: white;
  border-color: #6366f1;
}

.btn-primary:hover:not(:disabled) {
  background: #4f46e5;
  border-color: #4f46e5;
}
</style>
