'use client'

import * as React from 'react'
import { importExcel } from '@/lib/s-erp-import/actions'
import { RPAInfo } from './rpa-info'

export function ImportButton({ tableName, count }: { tableName: string; count: number }) {
  const [pending, setPending] = React.useState(false)
  const [currentCount, setCurrentCount] = React.useState(count)
  const [statusMsg, setStatusMsg] = React.useState<string | null>(null)
  const fileInputRef = React.useRef<HTMLInputElement>(null)

  const onClickImport = () => fileInputRef.current?.click()

  const onFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    setPending(true)
    try {
      console.log(`[SAP Import] 시작: ${tableName}, 파일: ${file.name}, 크기: ${file.size} bytes`)
      const res = await importExcel(tableName, file)
      if (res?.success) {
        setCurrentCount((c) => c + (res.inserted ?? 0))
        console.log(`[SAP Import] 성공: ${tableName}, 입력 건수: ${res.inserted ?? 0}`)
        setStatusMsg(`${res.inserted ?? 0}건`)
      } else {
        console.error(`[SAP Import] 실패: ${tableName}, 사유: ${res?.message ?? '임포트 실패'}`)
        if ((res as any)?.unknownHeaders) {
          console.error(`[SAP Import] 매핑 실패 헤더:`, (res as any).unknownHeaders)
        }
        if ((res as any)?.errors) {
          console.error(`[SAP Import] 유효성 오류 상세:`, (res as any).errors)
        }
        setStatusMsg(`데이터 저장에 실패하였습니다.`)
      }
    } catch (err: any) {
      console.error(`[SAP Import] 예외 발생: ${tableName}, 에러: ${err?.message ?? err}`)
      setStatusMsg(`데이터 저장에 실패하였습니다.`)
    } finally {
      console.log(`[SAP Import] 종료: ${tableName}`)
      setPending(false)
      e.target.value = ''
    }
  }

  return (
    <div 
      className="border rounded p-4"
      data-testid={`import-controls-${tableName}`}
      data-table-name={tableName}
      data-current-count={currentCount}
    >
      <div className="flex items-center gap-6">
        <button 
          onClick={onClickImport} 
          disabled={pending} 
          className="w-[300px] py-2 border rounded hover:bg-gray-100 transition-colors duration-200"
          data-testid={`upload-button-${tableName}`}
          data-table-name={tableName}
          data-action="upload"
          data-status={pending ? 'uploading' : 'idle'}
          data-button-text={tableName}
        >
          {tableName}
        </button>
        {statusMsg && (
          <span 
            className="text-base"
            data-testid={`status-message-${tableName}`}
            data-table-name={tableName}
            data-message={statusMsg}
          >
            {statusMsg}
          </span>
        )}
        <input 
          ref={fileInputRef} 
          type="file" 
          accept=".xlsx,.xls" 
          className="hidden" 
          onChange={onFileChange}
          data-testid={`file-input-${tableName}`}
          data-table-name={tableName}
          data-file-types=".xlsx,.xls"
        />
      </div>
      <RPAInfo tableName={tableName} count={currentCount} />
    </div>
  )
}


