import { ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'

export interface InvoiceTemplateColors {
  primary: string
  secondary: string
  background: string
  headerBg: string
  headerText: string
  bodyText: string
  tableHeaderBg: string
  tableHeaderText: string
  tableRowAlt: string
  tableBorder: string
  totalHighlight: string
}

export interface InvoiceTemplateConfig {
  id: string
  name: string
  layout: string
  category: string
  description: string
  colors: InvoiceTemplateColors
}

export const TEMPLATE_CATEGORIES = [
  { id: 'essential', label: 'Professional Essentials' },
  { id: 'creative', label: 'Creative & Modern' },
  { id: 'warm', label: 'Warm & Distinctive' },
  { id: 'premium', label: 'Premium & Specialized' },
] as const

const templates = ref<InvoiceTemplateConfig[]>([])
let loaded = false

export async function loadTemplates(): Promise<InvoiceTemplateConfig[]> {
  if (loaded && templates.value.length > 0) return templates.value
  try {
    templates.value = await invoke<InvoiceTemplateConfig[]>('get_invoice_templates')
    loaded = true
  } catch (e) {
    console.error('Failed to load invoice templates:', e)
  }
  return templates.value
}

export function getLoadedTemplates(): InvoiceTemplateConfig[] {
  return templates.value
}

export function getTemplateById(id: string): InvoiceTemplateConfig {
  return templates.value.find(t => t.id === id) || templates.value[0] || {
    id: 'clean', name: 'Clean', layout: 'clean', category: 'essential',
    description: 'Default', colors: {
      primary: '#1e293b', secondary: '#3b82f6', background: '#ffffff',
      headerBg: '#ffffff', headerText: '#1e293b', bodyText: '#374151',
      tableHeaderBg: '#f8fafc', tableHeaderText: '#374151',
      tableRowAlt: '#f8fafc', tableBorder: '#e5e7eb', totalHighlight: '#3b82f6',
    },
  }
}

export function getTemplatesByCategory(category: string): InvoiceTemplateConfig[] {
  return templates.value.filter(t => t.category === category)
}
