import { Button, Card, Subtitle2, Caption1 } from '@fluentui/react-components'
import { DocumentArrowDownRegular, DocumentArrowUpRegular } from '@fluentui/react-icons'
import { useErrorTextStyles } from '../../components/ui/errorText'
import { useSettingsStyles } from './settingsStyles'
import { useBackupCard } from './useBackupCard'

export function BackupCard(): React.JSX.Element {
  const styles = useSettingsStyles()
  const errText = useErrorTextStyles()

  // View-model hook owns the export/import state + IPC (L93/CC13).
  const { exporting, exportResult, importing, importResult, exportBackup, importBackup } =
    useBackupCard()

  return (
    <Card className={styles.card}>
      <div className={styles.sectionHeader}>
        <DocumentArrowDownRegular className={styles.sectionIcon} />
        <Subtitle2 as="h3">Backup &amp; restore</Subtitle2>
      </div>
      <Caption1 className={styles.hint}>
        Save your settings and custom-command templates to a JSON file, or restore them on another
        machine. Does not include download history or credentials (proxy, API tokens -- re-enter
        those after import).
      </Caption1>

      <div className={styles.folderRow}>
        <Button icon={<DocumentArrowDownRegular />} onClick={exportBackup} disabled={exporting}>
          {exporting ? 'Exporting…' : 'Export backup…'}
        </Button>
        <Button icon={<DocumentArrowUpRegular />} onClick={importBackup} disabled={importing}>
          {importing ? 'Importing…' : 'Import backup…'}
        </Button>
      </div>
      {exportResult?.ok && exportResult.path && (
        <Caption1 className={styles.hint}>Saved to {exportResult.path}</Caption1>
      )}
      {exportResult && !exportResult.ok && exportResult.error && (
        <Caption1 className={errText.error}>{exportResult.error}</Caption1>
      )}
      {importResult?.ok && (
        <Caption1 className={styles.hint}>Settings and templates restored.</Caption1>
      )}
      {importResult && !importResult.ok && importResult.error && (
        <Caption1 className={errText.error}>{importResult.error}</Caption1>
      )}
    </Card>
  )
}
