<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { DocumentReasoning } from '@/types'
import Button from '@/components/common/Button.vue'

const props = defineProps<{
  documentId: string
  reasoning: DocumentReasoning | null
  editable?: boolean
}>()

const emit = defineEmits<{
  'update': [reasoning: DocumentReasoning]
  'add-step': [thought: string, conclusion: string | null]
  'delete-step': [step: number]
}>()

const reasoningTypes = [
  { value: 'chain', label: 'Chain' },
  { value: 'idea', label: 'Idea' },
  { value: 'context', label: 'Context' },
  { value: 'reflection', label: 'Reflection' },
] as const

const localReasoning = ref<DocumentReasoning | null>(null)
const showAddStep = ref(false)
const newStepThought = ref('')
const newStepConclusion = ref('')

watch(() => props.reasoning, (newVal) => {
  localReasoning.value = newVal ? JSON.parse(JSON.stringify(newVal)) : null
}, { immediate: true, deep: true })

const hasReasoning = computed(() => !!localReasoning.value && localReasoning.value.reasoning_type !== null)

function updateReasoningType(type: string) {
  if (!localReasoning.value) return
  localReasoning.value.reasoning_type = type as DocumentReasoning['reasoning_type']
  emitUpdate()
}

function updateConfidence(value: string) {
  if (!localReasoning.value) return
  const num = parseFloat(value)
  if (!isNaN(num) && num >= 0 && num <= 1) {
    localReasoning.value.confidence = num
    emitUpdate()
  }
}

function updateStep(index: number, field: 'thought' | 'conclusion', value: string) {
  if (!localReasoning.value) return
  if (field === 'conclusion') {
    localReasoning.value.reasoning_steps[index].conclusion = value || null
  } else {
    localReasoning.value.reasoning_steps[index].thought = value
  }
  emitUpdate()
}

function emitUpdate() {
  if (!localReasoning.value) return
  emit('update', { ...localReasoning.value })
}

function openAddStep() {
  newStepThought.value = ''
  newStepConclusion.value = ''
  showAddStep.value = true
}

function submitAddStep() {
  if (!newStepThought.value.trim()) return
  emit('add-step', newStepThought.value.trim(), newStepConclusion.value.trim() || null)
  showAddStep.value = false
}

function removeStep(step: number) {
  emit('delete-step', step)
}

function getConfidenceColor(confidence: number | null): string {
  if (confidence === null) return 'var(--text-secondary)'
  if (confidence >= 0.8) return '#22c55e'
  if (confidence >= 0.5) return '#eab308'
  return '#ef4444'
}
</script>

<template>
  <aside class="reasoning-panel">
    <div class="reasoning-panel__header">
      <h3 class="reasoning-panel__title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 2a8 8 0 0 1 8 8c0 3.5-2 6-4 8l-2 2-2-2c-2-2-4-4.5-4-8a8 8 0 0 1 8-8z"/>
          <circle cx="12" cy="10" r="3"/>
        </svg>
        Reasoning
      </h3>
    </div>

    <div v-if="!hasReasoning" class="reasoning-panel__empty">
      <p>No reasoning data for this document.</p>
      <Button variant="secondary" size="sm" @click="openAddStep">
        Add Reasoning
      </Button>
    </div>

    <div v-else class="reasoning-panel__content">
      <!-- Reasoning Type -->
      <div class="reasoning-panel__field">
        <label class="reasoning-panel__label">Type</label>
        <select
          v-if="editable"
          :value="localReasoning?.reasoning_type"
          class="reasoning-panel__select"
          @change="updateReasoningType(($event.target as HTMLSelectElement).value)"
        >
          <option v-for="rt in reasoningTypes" :key="rt.value" :value="rt.value">
            {{ rt.label }}
          </option>
        </select>
        <span v-else class="reasoning-panel__value">
          {{ reasoningTypes.find(r => r.value === localReasoning?.reasoning_type)?.label }}
        </span>
      </div>

      <!-- Confidence -->
      <div class="reasoning-panel__field">
        <label class="reasoning-panel__label">Confidence</label>
        <div class="reasoning-panel__confidence">
          <input
            v-if="editable"
            type="number"
            min="0"
            max="1"
            step="0.01"
            :value="localReasoning?.confidence"
            class="reasoning-panel__input"
            @change="updateConfidence(($event.target as HTMLInputElement).value)"
          />
          <span
            v-else
            class="reasoning-panel__value"
            :style="{ color: getConfidenceColor(localReasoning?.confidence ?? null) }"
          >
            {{ localReasoning?.confidence !== null ? (localReasoning!.confidence * 100).toFixed(0) + '%' : 'N/A' }}
          </span>
          <div
            v-if="localReasoning?.confidence !== null"
            class="reasoning-panel__confidence-bar"
          >
            <div
              class="reasoning-panel__confidence-fill"
              :style="{
                width: ((localReasoning?.confidence ?? 0) * 100) + '%',
                backgroundColor: getConfidenceColor(localReasoning?.confidence ?? null)
              }"
            ></div>
          </div>
        </div>
      </div>

      <!-- Model Source -->
      <div v-if="localReasoning?.model_source" class="reasoning-panel__field">
        <label class="reasoning-panel__label">Model</label>
        <span class="reasoning-panel__value">{{ localReasoning.model_source }}</span>
      </div>

      <!-- Reasoning Steps -->
      <div class="reasoning-panel__steps">
        <div class="reasoning-panel__steps-header">
          <label class="reasoning-panel__label">Steps</label>
          <Button v-if="editable" variant="secondary" size="sm" @click="openAddStep">
            + Add
          </Button>
        </div>

        <div
          v-for="(step, index) in localReasoning?.reasoning_steps"
          :key="step.step"
          class="reasoning-panel__step"
        >
          <div class="reasoning-panel__step-header">
            <span class="reasoning-panel__step-number">Step {{ step.step }}</span>
            <button
              v-if="editable"
              class="reasoning-panel__step-delete"
              @click="removeStep(step.step)"
              title="Delete step"
            >
              ×
            </button>
          </div>
          <div class="reasoning-panel__step-body">
            <textarea
              v-if="editable"
              :value="step.thought"
              class="reasoning-panel__textarea"
              placeholder="Thought..."
              rows="2"
              @input="updateStep(index, 'thought', ($event.target as HTMLTextAreaElement).value)"
            ></textarea>
            <p v-else class="reasoning-panel__step-text">{{ step.thought }}</p>

            <div v-if="step.conclusion !== undefined" class="reasoning-panel__step-conclusion">
              <label class="reasoning-panel__sublabel">Conclusion</label>
              <textarea
                v-if="editable"
                :value="step.conclusion ?? ''"
                class="reasoning-panel__textarea"
                placeholder="Conclusion (optional)..."
                rows="2"
                @input="updateStep(index, 'conclusion', ($event.target as HTMLTextAreaElement).value)"
              ></textarea>
              <p v-else-if="step.conclusion" class="reasoning-panel__step-text reasoning-panel__step-text--conclusion">
                {{ step.conclusion }}
              </p>
            </div>
          </div>
        </div>

        <p v-if="!localReasoning?.reasoning_steps?.length" class="reasoning-panel__no-steps">
          No steps yet.
        </p>
      </div>
    </div>

    <!-- Add Step Modal -->
    <div v-if="showAddStep" class="reasoning-panel__modal-overlay" @click.self="showAddStep = false">
      <div class="reasoning-panel__modal">
        <h4 class="reasoning-panel__modal-title">Add Reasoning Step</h4>
        <div class="reasoning-panel__field">
          <label class="reasoning-panel__label">Thought</label>
          <textarea
            v-model="newStepThought"
            class="reasoning-panel__textarea"
            placeholder="Describe the reasoning thought..."
            rows="3"
            autofocus
          ></textarea>
        </div>
        <div class="reasoning-panel__field">
          <label class="reasoning-panel__label">Conclusion (optional)</label>
          <textarea
            v-model="newStepConclusion"
            class="reasoning-panel__textarea"
            placeholder="Optional conclusion reached..."
            rows="2"
          ></textarea>
        </div>
        <div class="reasoning-panel__modal-actions">
          <Button variant="secondary" size="sm" @click="showAddStep = false">Cancel</Button>
          <Button variant="primary" size="sm" @click="submitAddStep">Add Step</Button>
        </div>
      </div>
    </div>
  </aside>
</template>

<style scoped>
.reasoning-panel {
  width: 320px;
  min-width: 320px;
  height: 100%;
  background: var(--bg-secondary);
  border-left: 1px solid var(--border);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.reasoning-panel__header {
  padding: 1rem;
  border-bottom: 1px solid var(--border);
}

.reasoning-panel__title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9375rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.reasoning-panel__empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 2rem;
  color: var(--text-secondary);
  text-align: center;
}

.reasoning-panel__content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.reasoning-panel__field {
  margin-bottom: 1rem;
}

.reasoning-panel__label {
  display: block;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-secondary);
  margin-bottom: 0.375rem;
}

.reasoning-panel__sublabel {
  display: block;
  font-size: 0.6875rem;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
}

.reasoning-panel__value {
  font-size: 0.875rem;
  color: var(--text-primary);
}

.reasoning-panel__select {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.875rem;
  color: var(--text-primary);
  cursor: pointer;
  outline: none;
}

.reasoning-panel__select:focus {
  border-color: var(--accent);
}

.reasoning-panel__input {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.875rem;
  color: var(--text-primary);
  outline: none;
}

.reasoning-panel__input:focus {
  border-color: var(--accent);
}

.reasoning-panel__confidence {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.reasoning-panel__confidence-bar {
  height: 4px;
  background: var(--border);
  border-radius: 2px;
  overflow: hidden;
}

.reasoning-panel__confidence-fill {
  height: 100%;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.reasoning-panel__steps {
  margin-top: 1.5rem;
}

.reasoning-panel__steps-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.75rem;
}

.reasoning-panel__step {
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 8px;
  margin-bottom: 0.75rem;
  overflow: hidden;
}

.reasoning-panel__step-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
}

.reasoning-panel__step-number {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.reasoning-panel__step-delete {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  padding: 0;
  background: none;
  border: none;
  border-radius: 4px;
  font-size: 1.25rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.reasoning-panel__step-delete:hover {
  background: #ef444420;
  color: #ef4444;
}

.reasoning-panel__step-body {
  padding: 0.75rem;
}

.reasoning-panel__textarea {
  width: 100%;
  padding: 0.5rem 0.625rem;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.8125rem;
  font-family: inherit;
  color: var(--text-primary);
  resize: vertical;
  outline: none;
  box-sizing: border-box;
}

.reasoning-panel__textarea:focus {
  border-color: var(--accent);
}

.reasoning-panel__step-text {
  font-size: 0.8125rem;
  line-height: 1.5;
  color: var(--text-primary);
  margin: 0;
}

.reasoning-panel__step-text--conclusion {
  color: var(--text-secondary);
  font-style: italic;
}

.reasoning-panel__step-conclusion {
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px dashed var(--border);
}

.reasoning-panel__no-steps {
  font-size: 0.8125rem;
  color: var(--text-secondary);
  text-align: center;
  padding: 1rem;
}

/* Modal */
.reasoning-panel__modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.reasoning-panel__modal {
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 1.25rem;
  width: 90%;
  max-width: 400px;
}

.reasoning-panel__modal-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 1rem 0;
}

.reasoning-panel__modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1rem;
}
</style>
