import { Download, Upload } from 'lucide-react'

import { type ExcelSortState, useExcelIo } from '@hooks/use-excel-io'
import { Button } from '@postxl/ui-components'

export type ExcelIoActionsProps = Readonly<{
  model?: string
  filters?: Record<string, unknown>
  sort?: ExcelSortState
  onImportSuccess?: () => void
}>

export function ExcelIoActions({ model, filters, sort, onImportSuccess }: ExcelIoActionsProps) {
  const { isExportingExcel, isImportingExcel, importInputRef, handleExportExcel, handleImportExcel, openImportDialog } =
    useExcelIo({
      model,
      filters,
      sort,
      onImportSuccess,
    })

  if (!model) {
    return null
  }

  return (
    <>
      <Button
        type="button"
        variant="outline"
        size="icon"
        className="h-8 w-8"
        onClick={() => {
          void handleExportExcel()
        }}
        disabled={isExportingExcel}
        title="Export filtered and sorted rows to Excel"
      >
        <Download className="h-4 w-4" />
      </Button>
      <input
        ref={importInputRef}
        type="file"
        accept=".xlsx,.xls"
        className="hidden"
        onChange={(event) => {
          const file = event.target.files?.[0] ?? null
          void handleImportExcel(file)
        }}
      />
      <Button
        type="button"
        variant="outline"
        size="icon"
        className="h-8 w-8"
        onClick={openImportDialog}
        disabled={isImportingExcel}
        title="Import Excel file"
      >
        <Upload className="h-4 w-4" />
      </Button>
    </>
  )
}
