'use client'

import * as React from 'react'
import { importExcel, getSingleTableCount } 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 {
      const res = await importExcel(tableName, file)
      if (res?.success) {
        // UPSERT 모드와 기존 INSERT 모드 모두 지원
        const processedCount = (res as any).processed ?? res.inserted ?? 0
        
        // UPSERT 모드인 경우 상세 정보 표시
        if ((res as any).upsertMode) {
          const inserted = (res as any).inserted ?? 0
          const updated = (res as any).updated ?? 0
          
          // 실제 DB에서 현재 카운트를 다시 가져옴
          try {
            const actualCount = await getSingleTableCount(tableName)
            setCurrentCount(actualCount)
          } catch (err) {
            console.error(`[SAP Import] DB 카운트 조회 실패:`, err)
          }
          
          if (inserted > 0 && updated > 0) {
            setStatusMsg(`신규 ${inserted}건, 업데이트 ${updated}건`)
          } else if (inserted > 0) {
            setStatusMsg(`${inserted}건 신규 추가`)
          } else if (updated > 0) {
            setStatusMsg(`${updated}건 업데이트`)
          } else {
            setStatusMsg(`변경사항 없음`)
          }
        } else {
          // INSERT 모드에서는 기존 방식대로 카운트 증가
          setCurrentCount((c) => c + processedCount)
          setStatusMsg(`${processedCount}건`)
        }
      } else {
        console.error(`[SAP Import] 실패: ${tableName}, 사유: ${res?.message ?? '임포트 실패'}`)
        setStatusMsg(`데이터 저장에 실패하였습니다.`)
      }
    } catch (err: any) {
      console.error(`[SAP Import] 예외 발생: ${tableName}, 에러: ${err?.message ?? err}`)
      setStatusMsg(`데이터 저장에 실패하였습니다.`)
    } finally {
      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>
  )
}


