import { useState } from 'react'
import { Card, CardHeader } from '@/components/ui/Card'

interface ExportButtonsProps {
  period: string
}

export function ExportButtons({ period }: ExportButtonsProps) {
  const [exporting, setExporting] = useState<string | null>(null)

  const handleExport = async (format: string) => {
    setExporting(format)
    try {
      const response = await fetch(`/api/v1/finance/export?period=${period}&format=${format}`)
      if (!response.ok) throw new Error('Export failed')
      
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `ledger-${period}.${format.toLowerCase()}`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (err) {
      console.error('Export error:', err)
      alert(`Failed to export ${format}`)
    } finally {
      setExporting(null)
    }
  }

  return (
    <Card>
      <CardHeader title="Export Reports" subtitle="Download ledger data in various formats" />
      <div className="p-6 flex gap-4">
        <button
          onClick={() => handleExport('SIE4')}
          disabled={exporting === 'SIE4'}
          className="px-4 py-2 bg-primary text-white rounded hover:bg-primary-dark disabled:opacity-50"
        >
          {exporting === 'SIE4' ? 'Exporting...' : 'Export SIE4'}
        </button>
        <button
          onClick={() => handleExport('PDF')}
          disabled={exporting === 'PDF'}
          className="px-4 py-2 bg-danger text-white rounded hover:bg-danger-dark disabled:opacity-50"
        >
          {exporting === 'PDF' ? 'Exporting...' : 'Export PDF'}
        </button>
        <button
          onClick={() => handleExport('CSV')}
          disabled={exporting === 'CSV'}
          className="px-4 py-2 bg-success text-white rounded hover:bg-success-dark disabled:opacity-50"
        >
          {exporting === 'CSV' ? 'Exporting...' : 'Export CSV'}
        </button>
      </div>
    </Card>
  )
}