import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useFeedbackStore = defineStore('feedback', () => {
  const entries = ref(JSON.parse(localStorage.getItem('vigilcare-feedback') || '[]'))

  const stats = computed(() => {
    const total = entries.value.length
    if (total === 0) return { total: 0, useful: 0, falsePositive: 0, usefulPct: 0, fpPct: 0 }

    const useful = entries.value.filter(e => e.rating === 'useful' || e.rating === 'would-act').length
    const fp = entries.value.filter(e => e.rating === 'false-positive').length

    return {
      total,
      useful,
      falsePositive: fp,
      usefulPct: Math.round((useful / total) * 100),
      fpPct: Math.round((fp / total) * 100),
    }
  })

  const byAlertType = computed(() => {
    const map = {}
    for (const entry of entries.value) {
      if (!map[entry.alertType]) map[entry.alertType] = []
      map[entry.alertType].push(entry)
    }
    return map
  })

  function addFeedback(alertId, alertType, severity, rating, notes = '') {
    const existing = entries.value.findIndex(e => e.alertId === alertId)
    const entry = {
      alertId,
      alertType,
      severity,
      rating,
      notes: notes.trim(),
      timestamp: new Date().toISOString(),
    }

    if (existing >= 0) {
      entries.value[existing] = entry
    } else {
      entries.value.push(entry)
    }

    persist()
  }

  function getFeedback(alertId) {
    return entries.value.find(e => e.alertId === alertId) ?? null
  }

  function persist() {
    localStorage.setItem('vigilcare-feedback', JSON.stringify(entries.value))
  }

  function exportAsJson() {
    const blob = new Blob([JSON.stringify(entries.value, null, 2)], { type: 'application/json' })
    downloadBlob(blob, 'vigilcare-feedback.json')
  }

  function exportAsCsv() {
    const headers = ['alertId', 'alertType', 'severity', 'rating', 'notes', 'timestamp']
    const rows = entries.value.map(e => headers.map(h => `"${(e[h] ?? '').toString().replace(/"/g, '""')}"`).join(','))
    const csv = [headers.join(','), ...rows].join('\n')
    const blob = new Blob([csv], { type: 'text/csv' })
    downloadBlob(blob, 'vigilcare-feedback.csv')
  }

  function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    a.click()
    URL.revokeObjectURL(url)
  }

  function clearAll() {
    entries.value = []
    persist()
  }

  return { entries, stats, byAlertType, addFeedback, getFeedback, exportAsJson, exportAsCsv, clearAll }
})