<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import {
  fetchBausteine,
  createBaustein,
  deleteBaustein,
  reworkBaustein,
  sortBausteine,
  fetchSortStatus,
  fetchSuggestions,
  generateSuggestions,
  fetchSuggestionsStatus,
  addSuggestion,
  ignoreSuggestion,
} from '../api.js'

const props = defineProps({
  topic: { type: String, required: true },
  refreshKey: { type: Number, default: 0 },
})

const bausteine = ref([])
const suggestions = ref([])
const suggestionsLoading = ref(false)
const newTitle = ref('')
const newInfo = ref('')
const sortInfo = ref('')
const sortingActive = ref(false)
let sortPollTimer = null
const reworkInputs = ref({})
const reworkingIds = ref(new Set())
const reworkingSnapshots = new Map()
let pollTimer = null
let bausteinPollTimer = null

const pendingSuggestions = computed(() => suggestions.value.filter((s) => s.status === 'pending'))
const ignoredSuggestions = computed(() => suggestions.value.filter((s) => s.status === 'ignored'))

function parseExamples(example) {
  if (!example) return []
  try {
    const parsed = JSON.parse(example)
    if (Array.isArray(parsed)) return parsed
  } catch {}
  return [{ label: '', code: example }]
}

async function loadData() {
  const [b, s] = await Promise.all([fetchBausteine(props.topic), fetchSuggestions(props.topic)])
  bausteine.value = b
  suggestions.value = s
}

async function checkAndGenerate() {
  const status = await fetchSuggestionsStatus(props.topic)
  if (status.generating) {
    suggestionsLoading.value = true
    startPolling()
  }
}

async function handleAdd() {
  const title = newTitle.value.trim()
  if (!title) return
  const info = newInfo.value.trim()
  newTitle.value = ''
  newInfo.value = ''
  const created = await createBaustein(props.topic, title, info)
  bausteine.value.push(created)
  reworkingSnapshots.set(created.id, created.updated_at)
  reworkingIds.value = new Set([...reworkingIds.value, created.id])
  startBausteinPolling()
}

async function handleDelete(id) {
  await deleteBaustein(id)
  bausteine.value = bausteine.value.filter((b) => b.id !== id)
}

async function handleAccept(s) {
  const created = await addSuggestion(s.id)
  suggestions.value = suggestions.value.filter((x) => x.id !== s.id)
  bausteine.value.push(created)
}

async function handleIgnore(s) {
  await ignoreSuggestion(s.id)
  const idx = suggestions.value.findIndex((x) => x.id === s.id)
  if (idx !== -1) suggestions.value[idx].status = 'ignored'
}

async function handleRestore(s) {
  const created = await addSuggestion(s.id)
  suggestions.value = suggestions.value.filter((x) => x.id !== s.id)
  bausteine.value.push(created)
}

async function handleRegenerate() {
  suggestionsLoading.value = true
  await generateSuggestions(props.topic)
  startPolling()
}

async function handleSort() {
  sortingActive.value = true
  const info = sortInfo.value.trim()
  await sortBausteine(props.topic, info)
  startSortPolling()
}

function startSortPolling() {
  if (sortPollTimer) return
  sortPollTimer = setInterval(async () => {
    const status = await fetchSortStatus(props.topic)
    if (!status.sorting) {
      sortingActive.value = false
      clearInterval(sortPollTimer)
      sortPollTimer = null
      bausteine.value = await fetchBausteine(props.topic)
    }
  }, 3000)
}

async function handleRework(b) {
  const instructions = (reworkInputs.value[b.id] || '').trim()
  if (!instructions) return
  reworkingSnapshots.set(b.id, b.updated_at)
  reworkingIds.value = new Set([...reworkingIds.value, b.id])
  reworkInputs.value[b.id] = ''
  await reworkBaustein(b.id, instructions)
  startBausteinPolling()
}

function startBausteinPolling() {
  if (bausteinPollTimer) return
  bausteinPollTimer = setInterval(async () => {
    const fresh = await fetchBausteine(props.topic)
    bausteine.value = fresh
    const remaining = new Set(reworkingIds.value)
    for (const id of reworkingIds.value) {
      const b = fresh.find((x) => x.id === id)
      if (!b || b.updated_at !== reworkingSnapshots.get(id)) {
        remaining.delete(id)
        reworkingSnapshots.delete(id)
      }
    }
    reworkingIds.value = remaining
    if (remaining.size === 0) {
      clearInterval(bausteinPollTimer)
      bausteinPollTimer = null
    }
  }, 3000)
}

function startPolling() {
  stopPolling()
  pollTimer = setInterval(async () => {
    const status = await fetchSuggestionsStatus(props.topic)
    if (!status.generating) {
      suggestionsLoading.value = false
      stopPolling()
      await loadData()
    }
  }, 3000)
}

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
  if (bausteinPollTimer) {
    clearInterval(bausteinPollTimer)
    bausteinPollTimer = null
  }
  if (sortPollTimer) {
    clearInterval(sortPollTimer)
    sortPollTimer = null
  }
}

async function init() {
  await loadData()
  await checkAndGenerate()
}

watch(
  () => props.topic,
  () => {
    stopPolling()
    suggestionsLoading.value = false
    init()
  },
)

watch(
  () => props.refreshKey,
  async (newVal) => {
    if (!newVal) return
    await loadData()
    let added = false
    for (const b of bausteine.value) {
      if (!b.description && !b.purpose && !reworkingIds.value.has(b.id)) {
        reworkingSnapshots.set(b.id, b.updated_at)
        reworkingIds.value = new Set([...reworkingIds.value, b.id])
        added = true
      }
    }
    if (added) startBausteinPolling()
  },
)

onMounted(init)
onUnmounted(stopPolling)
</script>

<template>
  <div class="bausteine-view">
    <div class="bausteine-grid">
      <div class="card new-card">
        <h3>Neuer Baustein</h3>
        <input
          v-model="newTitle"
          placeholder="Thema…"
          @keyup.enter="handleAdd"
        />
        <input
          v-model="newInfo"
          placeholder="Zusätzliche Infos (optional)…"
          @keyup.enter="handleAdd"
        />
        <button class="new-btn" @click="handleAdd" :disabled="!newTitle.trim()">Generieren</button>

        <h3 class="new-card-section">Ordnen</h3>
        <input
          v-model="sortInfo"
          placeholder="Zusätzliche Infos (optional)…"
          @keyup.enter="handleSort"
        />
        <button class="new-btn" @click="handleSort" :disabled="sortingActive || !bausteine.length">
          {{ sortingActive ? 'Ordne…' : 'Ordnen' }}
        </button>
      </div>

      <div v-for="b in bausteine" :key="b.id" class="card">
        <div class="card-header">
          <h3>{{ b.title }}</h3>
          <button class="card-delete" @click="handleDelete(b.id)">&times;</button>
        </div>
        <p v-if="b.description" class="desc">{{ b.description }}</p>
        <p v-if="b.purpose" class="purpose">{{ b.purpose }}</p>
        <div v-if="b.example" class="examples">
          <div v-for="(ex, i) in parseExamples(b.example)" :key="i" class="code-block">
            <span v-if="ex.label" class="code-label">{{ ex.label }}</span>
            <pre v-html="ex.code"></pre>
          </div>
        </div>
        <p v-if="!b.description && !b.purpose" class="loading-text">Wird generiert…</p>
        <p v-else-if="reworkingIds.has(b.id)" class="loading-text">Wird überarbeitet…</p>
        <div class="rework-row">
          <input
            v-model="reworkInputs[b.id]"
            placeholder="Anpassen…"
            :disabled="reworkingIds.has(b.id)"
            @keyup.enter="handleRework(b)"
          />
          <button
            class="rework-btn"
            :disabled="!reworkInputs[b.id]?.trim() || reworkingIds.has(b.id)"
            @click="handleRework(b)"
            title="Überarbeiten"
          >↻</button>
        </div>
      </div>
    </div>

    <hr class="divider" />

    <div class="suggestions-section">
      <div class="section-header">
        <h3>Vorschläge</h3>
        <button class="regenerate-btn" @click="handleRegenerate" :disabled="suggestionsLoading">
          {{ suggestionsLoading ? 'Generiere…' : 'Generieren' }}
        </button>
      </div>
      <div v-if="suggestionsLoading" class="loading-indicator">Generiere Vorschläge…</div>
      <div v-if="pendingSuggestions.length" class="suggestions-grid">
        <div v-for="s in pendingSuggestions" :key="s.id" class="card suggestion-card">
          <h3>{{ s.title }}</h3>
          <p v-if="s.description" class="desc">{{ s.description }}</p>
          <p v-if="s.purpose" class="purpose">{{ s.purpose }}</p>
          <div v-if="s.example" class="examples">
            <div v-for="(ex, i) in parseExamples(s.example)" :key="i" class="code-block">
              <span v-if="ex.label" class="code-label">{{ ex.label }}</span>
              <pre v-html="ex.code"></pre>
            </div>
          </div>
          <div class="suggestion-actions">
            <button class="btn-add" @click="handleAccept(s)">Hinzufügen</button>
            <button class="btn-ignore" @click="handleIgnore(s)">Ignorieren</button>
          </div>
        </div>
      </div>
    </div>

    <hr v-if="ignoredSuggestions.length" class="divider" />

    <div v-if="ignoredSuggestions.length" class="ignored-section">
      <h3>Ignoriert</h3>
      <div v-for="s in ignoredSuggestions" :key="s.id" class="ignored-item">
        <span>{{ s.title }}</span>
        <button class="btn-restore" @click="handleRestore(s)">Hinzufügen</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.bausteine-view {
  flex: 1;
  height: 100vh;
  overflow-y: auto;
  padding: 1.5rem;
}

.bausteine-grid,
.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
}

.card {
  background: #fff;
  border: 1px solid #e2e5e9;
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  max-height: 400px;
  overflow-y: auto;
  overscroll-behavior: contain;
}

.new-card {
  background: #f8f9fb;
  border-style: dashed;
}

.new-card h3 {
  font-size: 0.95rem;
  color: #1a1a1a;
  margin: 0;
}

.new-card-section {
  margin-top: 0.75rem;
  padding-top: 0.75rem;
  border-top: 1px solid #e2e5e9;
}

.new-card input {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #d8dde3;
  border-radius: 6px;
  font-size: 0.85rem;
  font-family: inherit;
  outline: none;
}

.new-card input:focus {
  border-color: #6366f1;
}

.new-btn {
  padding: 8px 12px;
  border: none;
  background: #6366f1;
  color: white;
  border-radius: 6px;
  font-size: 0.85rem;
  font-weight: 600;
  cursor: pointer;
}

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

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-header h3 {
  font-size: 0.95rem;
  color: #1a1a1a;
  margin: 0;
}

.card-delete {
  background: none;
  border: none;
  color: #991b1b;
  font-size: 1.2rem;
  cursor: pointer;
  line-height: 1;
  opacity: 0;
  transition: opacity 0.15s;
}

.card:hover .card-delete {
  opacity: 1;
}

.desc {
  font-size: 0.85rem;
  color: #4b5563;
}

.purpose {
  font-size: 0.8rem;
  color: #6b7280;
  font-style: italic;
}

.examples {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
}

.code-block {
  background: #1e2a3a;
  color: #e6e6e6;
  font-family: "SF Mono", Consolas, monospace;
  font-size: 12px;
  line-height: 1.5;
  padding: 12px 14px;
  border-radius: 6px;
}

.code-block pre {
  margin: 0;
  white-space: pre-wrap;
  font: inherit;
  color: inherit;
}

.code-label {
  font-family: -apple-system, sans-serif;
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 1px;
  color: #8be9fd;
  margin-bottom: 4px;
  display: block;
}

.code-block :deep(.k) { color: #ff79c6; }
.code-block :deep(.v) { color: #ffb86c; }
.code-block :deep(.s) { color: #f1c40f; }
.code-block :deep(.f) { color: #50fa7b; }
.code-block :deep(.t) { color: #8be9fd; }
.code-block :deep(.c) { color: #6b8aae; font-style: italic; }
.code-block :deep(.n) { color: #ffb86c; }
.code-block :deep(.p) { color: #e6e6e6; }

.loading-text {
  font-size: 0.8rem;
  color: #9ca3af;
  font-style: italic;
}

.rework-row {
  display: flex;
  gap: 6px;
  margin-top: auto;
  padding-top: 8px;
}

.rework-row input {
  flex: 1;
  padding: 5px 8px;
  border: 1px solid #d8dde3;
  border-radius: 4px;
  font-size: 0.8rem;
  outline: none;
}

.rework-row input:focus {
  border-color: #6366f1;
}

.rework-row input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.rework-btn {
  width: 28px;
  height: 28px;
  border: 1px solid #d8dde3;
  border-radius: 4px;
  background: #fff;
  color: #4b5563;
  font-size: 0.9rem;
  cursor: pointer;
}

.rework-btn:hover:not(:disabled) {
  border-color: #6366f1;
  color: #6366f1;
}

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

.divider {
  border: none;
  border-top: 1px solid #e2e5e9;
  margin: 1.5rem 0;
}

.loading-indicator {
  font-size: 0.85rem;
  color: #92400e;
  background: #fef3c7;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  margin-bottom: 1rem;
  animation: pulse 1.5s ease-in-out infinite;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h3 {
  font-size: 0.9rem;
  color: #4b5563;
  margin: 0;
}

.regenerate-btn {
  padding: 4px 10px;
  border: 1px solid #d8dde3;
  border-radius: 4px;
  background: #fff;
  font-size: 0.8rem;
  cursor: pointer;
  color: #4b5563;
}

.regenerate-btn:hover {
  border-color: #6366f1;
  color: #6366f1;
}

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

.suggestion-card {
  border-color: #c7d2fe;
  background: #fafafe;
}

.suggestion-actions {
  display: flex;
  gap: 0.5rem;
  margin-top: auto;
  padding-top: 0.5rem;
}

.btn-add {
  padding: 4px 10px;
  border: 1px solid #34d399;
  border-radius: 4px;
  background: #d1fae5;
  color: #065f46;
  font-size: 0.8rem;
  cursor: pointer;
}

.btn-add:hover {
  background: #a7f3d0;
}

.btn-ignore {
  padding: 4px 10px;
  border: 1px solid #d8dde3;
  border-radius: 4px;
  background: #fff;
  color: #6b7280;
  font-size: 0.8rem;
  cursor: pointer;
}

.btn-ignore:hover {
  background: #f3f4f6;
}

.ignored-section h3 {
  font-size: 0.85rem;
  color: #9ca3af;
  margin-bottom: 0.5rem;
}

.ignored-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.4rem 0;
  font-size: 0.85rem;
  color: #9ca3af;
}

.btn-restore {
  padding: 2px 8px;
  border: 1px solid #d8dde3;
  border-radius: 4px;
  background: #fff;
  color: #6b7280;
  font-size: 0.75rem;
  cursor: pointer;
}

.btn-restore:hover {
  border-color: #34d399;
  color: #065f46;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.65; }
}
</style>
