<script setup lang="ts">
import { ref } from 'vue'
import SubscriptionForm from './SubscriptionForm.vue'
import SubscriptionList from './SubscriptionList.vue'
import NotificationHistory from './NotificationHistory.vue'
import SmtpSettings from './SmtpSettings.vue'
import StatusTimeline from './StatusTimeline.vue'
import StageManager from './StageManager.vue'
import SyncEventsView from './SyncEventsView.vue'
import { configApi } from '../../services/configApi'
import { useUiStore } from '../../stores/ui'

const ui = useUiStore()
const activeTab = ref<'subscriptions' | 'stages' | 'events' | 'history' | 'settings'>('subscriptions')
const listRef = ref<InstanceType<typeof SubscriptionList>>()

// Track which doc_number is selected to show timeline
const selectedDoc = ref('')
const chainStatus = ref<any>(null)
const loadingStatus = ref(false)

async function onSubscriptionCreated(docNumber: string) {
  listRef.value?.load()
  // Immediately show chain status for the subscribed document
  selectedDoc.value = docNumber
  await loadChainStatus(docNumber)
}

async function loadChainStatus(docNumber: string) {
  loadingStatus.value = true
  try {
    const { data } = await configApi.getChainStatus(docNumber)
    chainStatus.value = data
  } catch {
    chainStatus.value = null
  } finally {
    loadingStatus.value = false
  }
}

function selectDoc(docNumber: string) {
  if (selectedDoc.value === docNumber) {
    selectedDoc.value = ''
    chainStatus.value = null
  } else {
    selectedDoc.value = docNumber
    loadChainStatus(docNumber)
  }
}

async function triggerProcess() {
  try {
    const { data } = await configApi.triggerNotificationProcessing()
    ui.showToast(`Processed: ${data.events_processed} events, ${data.emails_sent} emails sent`, 'success')
  } catch {
    ui.showToast('Processing failed', 'error')
  }
}
</script>

<template>
  <div class="h-full flex flex-col p-4 overflow-y-auto">
    <div class="max-w-5xl mx-auto w-full">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-semibold">Notifications</h2>
          <p class="text-dark-400 text-sm">Subscribe to document status changes and receive email notifications.</p>
        </div>
        <button @click="triggerProcess" class="btn-secondary text-xs">Process Now</button>
      </div>

      <!-- Tabs -->
      <div class="flex gap-1 mb-4">
        <button
          @click="activeTab = 'subscriptions'"
          :class="['px-3 py-1.5 text-sm rounded-md transition-colors', activeTab === 'subscriptions' ? 'bg-dark-700 text-white' : 'text-dark-400 hover:text-dark-200']"
        >Subscriptions</button>
        <button
          @click="activeTab = 'stages'"
          :class="['px-3 py-1.5 text-sm rounded-md transition-colors', activeTab === 'stages' ? 'bg-dark-700 text-white' : 'text-dark-400 hover:text-dark-200']"
        >Stages</button>
        <button
          @click="activeTab = 'history'"
          :class="['px-3 py-1.5 text-sm rounded-md transition-colors', activeTab === 'history' ? 'bg-dark-700 text-white' : 'text-dark-400 hover:text-dark-200']"
        >History</button>
        <button
          @click="activeTab = 'events'"
          :class="['px-3 py-1.5 text-sm rounded-md transition-colors', activeTab === 'events' ? 'bg-dark-700 text-white' : 'text-dark-400 hover:text-dark-200']"
        >Events</button>
        <button
          @click="activeTab = 'settings'"
          :class="['px-3 py-1.5 text-sm rounded-md transition-colors', activeTab === 'settings' ? 'bg-dark-700 text-white' : 'text-dark-400 hover:text-dark-200']"
        >Settings</button>
      </div>

      <!-- Subscriptions tab -->
      <template v-if="activeTab === 'subscriptions'">
        <div class="space-y-4">
          <SubscriptionForm @created="onSubscriptionCreated" />

          <!-- Chain status shown immediately after subscribing -->
          <div v-if="selectedDoc" class="card">
            <div class="flex items-center justify-between mb-3">
              <h3 class="font-semibold text-sm">Chain Status: {{ selectedDoc }}</h3>
              <button @click="selectedDoc = ''; chainStatus = null" class="text-xs text-dark-500 hover:text-dark-300">Close</button>
            </div>

            <div v-if="loadingStatus" class="text-dark-500 text-sm text-center py-4">Loading chain status...</div>

            <template v-else-if="chainStatus">
              <!-- Status timeline -->
              <StatusTimeline :doc-number="selectedDoc" />

              <!-- Linked chain documents -->
              <div v-if="chainStatus.chain_documents?.length" class="mt-4">
                <h4 class="text-xs font-semibold text-dark-400 mb-2">Linked Documents</h4>
                <div v-for="doc in chainStatus.chain_documents" :key="doc.id" class="p-2 bg-dark-900 rounded mb-2 flex items-center justify-between">
                  <div>
                    <span class="text-xs font-medium text-primary-400 uppercase">{{ doc.source_system }}</span>
                    <span class="text-sm ml-2">{{ doc.doc_type }} #{{ doc.doc_number }}</span>
                  </div>
                  <span v-if="doc.status" class="text-xs text-dark-400">{{ doc.status }}</span>
                </div>
              </div>

              <!-- Recent events -->
              <div v-if="chainStatus.events?.length" class="mt-4">
                <h4 class="text-xs font-semibold text-dark-400 mb-2">Recent Changes</h4>
                <div v-for="evt in chainStatus.events.slice(0, 5)" :key="evt.id" class="text-xs py-1 flex items-center gap-2 border-b border-dark-800">
                  <span :class="evt.change_type === 'changed' ? 'text-blue-400' : evt.change_type === 'added' ? 'text-green-400' : 'text-red-400'" class="font-medium">
                    {{ evt.change_type }}
                  </span>
                  <span class="text-dark-300">{{ evt.column_name }}</span>
                  <span v-if="evt.old_value" class="text-dark-500 line-through">{{ evt.old_value }}</span>
                  <span v-if="evt.new_value" class="text-green-400">{{ evt.new_value }}</span>
                </div>
              </div>

              <!-- Notification history for this doc -->
              <div v-if="chainStatus.history?.length" class="mt-4">
                <h4 class="text-xs font-semibold text-dark-400 mb-2">Notification History</h4>
                <div v-for="n in chainStatus.history.slice(0, 5)" :key="n.id" class="text-xs py-1 flex items-center justify-between border-b border-dark-800">
                  <span class="text-dark-300 truncate">{{ n.subject }}</span>
                  <span :class="n.status === 'sent' ? 'text-green-400' : n.status === 'failed' ? 'text-red-400' : 'text-yellow-400'" class="ml-2 font-medium shrink-0">
                    {{ n.status }}
                  </span>
                </div>
              </div>

              <p v-if="!chainStatus.events?.length && !chainStatus.chain_documents?.length" class="text-dark-500 text-sm text-center py-2">
                No events detected yet. Status updates will appear here after the next sync.
              </p>
            </template>
          </div>

          <SubscriptionList ref="listRef" @select="selectDoc" />
        </div>
      </template>

      <!-- Stages tab -->
      <StageManager v-if="activeTab === 'stages'" />

      <!-- History tab -->
      <NotificationHistory v-if="activeTab === 'history'" />

      <!-- Events tab -->
      <SyncEventsView v-if="activeTab === 'events'" />

      <!-- Settings tab -->
      <SmtpSettings v-if="activeTab === 'settings'" />
    </div>
  </div>
</template>
