import { useState } from 'react'
import type { BackupExportResult, BackupImportResult } from '@shared/ipc'
import { useSettings } from '../../store/settings'
import { useTemplates } from '../../store/templates'

export interface BackupCardController {
  exporting: boolean
  exportResult: BackupExportResult | null
  importing: boolean
  importResult: BackupImportResult | null
  exportBackup: () => Promise<void>
  importBackup: () => Promise<void>
}

/**
 * View-model for the Backup & restore card (L93/CC13): owns the export/import
 * orchestration — including reloading the settings/templates stores after a
 * restore changes both underneath — so the card stays presentational.
 */
export function useBackupCard(): BackupCardController {
  const [exporting, setExporting] = useState(false)
  const [exportResult, setExportResult] = useState<BackupExportResult | null>(null)
  const [importing, setImporting] = useState(false)
  const [importResult, setImportResult] = useState<BackupImportResult | null>(null)

  async function exportBackup(): Promise<void> {
    setExporting(true)
    setExportResult(null)
    try {
      setExportResult(await window.api.exportBackup())
    } catch (e) {
      setExportResult({ ok: false, error: e instanceof Error ? e.message : String(e) })
    } finally {
      setExporting(false)
    }
  }

  async function importBackup(): Promise<void> {
    setImporting(true)
    setImportResult(null)
    try {
      const result = await window.api.importBackup()
      setImportResult(result)
      if (result.ok) {
        // Settings + templates changed underneath the stores -- reload both.
        useSettings.getState().reload()
        useTemplates.getState().reload()
      }
    } catch (e) {
      setImportResult({ ok: false, error: e instanceof Error ? e.message : String(e) })
    } finally {
      setImporting(false)
    }
  }

  return { exporting, exportResult, importing, importResult, exportBackup, importBackup }
}
