"use client"

import React, { useRef, useState } from "react"
import { Button } from "@/shared/components/ui/button"
import { Download, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { ImportResultsDialog } from "@/shared/components/import-results-dialog"
import type { ImportDataResponse } from "@garage/api"

type ImportDataButtonProps = {
    onImport: (file: File) => Promise<ImportDataResponse>
    onSuccess?: () => void
    accept?: string
    label?: string
    entityLabel?: string
}

export function ImportDataButton({
    onImport,
    onSuccess,
    accept = ".xlsx,.xls,.csv",
    label = "Import",
    entityLabel,
}: ImportDataButtonProps) {
    const inputRef = useRef<HTMLInputElement>(null)
    const [isPending, setIsPending] = useState(false)
    const [result, setResult] = useState<ImportDataResponse["data"] | null>(null)
    const [resultOpen, setResultOpen] = useState(false)

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]
        if (!file) return

        setIsPending(true)
        try {
            const response = await onImport(file)
            const data = response.data ?? { imported_count: 0, failed_count: 0, failed_rows: [] }
            setResult(data)
            setResultOpen(true)

            if (data.failed_count === 0) {
                onSuccess?.()
            } else if (data.imported_count > 0) {
                onSuccess?.()
            }
        } catch (err: any) {
            toast.error(err?.message ?? "Failed to import data")
        } finally {
            setIsPending(false)
            if (inputRef.current) inputRef.current.value = ""
        }
    }

    return (
        <>
            <input
                ref={inputRef}
                type="file"
                accept={accept}
                className="hidden"
                onChange={handleFileChange}
            />
            <Button
                size="sm"
                variant="outline"
                disabled={isPending}
                onClick={() => inputRef.current?.click()}
            >
                {isPending ? <Loader2 className="animate-spin" /> : <Download />}
                {label}
            </Button>
            {result && (
                <ImportResultsDialog
                    open={resultOpen}
                    onOpenChange={setResultOpen}
                    importedCount={result.imported_count}
                    failedCount={result.failed_count}
                    failedRows={result.failed_rows}
                    entityLabel={entityLabel}
                />
            )}
        </>
    )
}
