import React, { useRef, useState } from 'react'
import { Button } from './Button'

// ─── DropZone ─────────────────────────────────────────────────────────────────

export interface DropZoneProps {
  onFileSelect?: (files: FileList) => void
  accept?: string
  multiple?: boolean
  label?: string
  description?: string
  className?: string
  disabled?: boolean
  isLoading?: boolean
}

export const DropZone: React.FC<DropZoneProps> = ({
  onFileSelect,
  accept,
  multiple = false,
  label = '파일을 드래그하거나 클릭하여 업로드',
  description = 'CSV, XLSX (최대 10MB)',
  className = '',
  disabled = false,
  isLoading = false,
}) => {
  const [isDragging, setIsDragging] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const isDisabled = disabled || isLoading

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    if (isDisabled) return
    if (e.dataTransfer.files.length > 0) onFileSelect?.(e.dataTransfer.files)
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) onFileSelect?.(e.target.files)
  }

  return (
    <div
      onClick={() => !isDisabled && inputRef.current?.click()}
      onDragOver={(e) => { e.preventDefault(); if (!isDisabled) setIsDragging(true) }}
      onDragLeave={() => setIsDragging(false)}
      onDrop={handleDrop}
      className={`
        border-2 border-dashed rounded-[14px] p-8
        flex flex-col items-center justify-center text-center
        transition-all duration-150
        ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
        ${isDragging
          ? 'border-teal-400 bg-teal-50/30'
          : 'border-slate-200 hover:border-teal-300 hover:bg-teal-50/20'
        }
        ${className}
      `}
    >
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        className="hidden"
        onChange={handleChange}
        disabled={isDisabled}
      />
      {isLoading ? (
        <>
          <span className="material-symbols-outlined text-teal-400 text-h1 mb-3 animate-spin">
            progress_activity
          </span>
          <p className="text-body-sm font-bold text-slate-500">업로드 중...</p>
        </>
      ) : (
        <>
          <div className={`w-12 h-12 rounded-xl flex items-center justify-center mb-3 ${isDragging ? 'bg-teal-50' : 'bg-slate-50'}`}>
            <span className={`material-symbols-outlined text-h1 ${isDragging ? 'text-teal-500' : 'text-slate-400'}`}>
              {isDragging ? 'download' : 'upload_file'}
            </span>
          </div>
          {isDragging ? (
            <p className="text-body-sm font-bold text-teal-600">여기에 놓으세요</p>
          ) : (
            <>
              <p className="text-body-sm font-bold text-slate-700 mb-1">{label}</p>
              <p className="text-caption text-slate-400">{description}</p>
            </>
          )}
        </>
      )}
    </div>
  )
}

// ─── FileItem ─────────────────────────────────────────────────────────────────

export type FileItemStatus = 'uploading' | 'complete' | 'error'

export interface FileItemProps {
  name: string
  size?: string
  status?: FileItemStatus
  progress?: number
  onRemove?: () => void
}

export const FileItem: React.FC<FileItemProps> = ({
  name,
  size,
  status = 'complete',
  progress,
  onRemove,
}) => (
  <div className={`border-[1.5px] rounded-[14px] p-4 ${status === 'error' ? 'border-red-300 bg-red-50/20' : 'border-slate-200'}`}>
    <div className="flex items-center gap-3">
      <div className="w-10 h-10 rounded-[10px] bg-teal-50 flex items-center justify-center flex-shrink-0">
        <span className="material-symbols-outlined text-teal-500 text-h2">description</span>
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-body-sm font-bold text-slate-800 truncate">{name}</p>
        {size && <p className="text-caption text-slate-400">{size}</p>}
      </div>
      {status === 'complete' && (
        <span className="material-symbols-outlined text-green-500 text-h2 flex-shrink-0">check_circle</span>
      )}
      {status === 'error' && (
        <span className="material-symbols-outlined text-red-500 text-h2 flex-shrink-0">error</span>
      )}
      {onRemove && (
        <Button
          variant="ghost"
          size="sm"
          onClick={onRemove}
          aria-label="삭제"
          leftIcon="close"
          className="flex-shrink-0 hover:text-red-500"
        />
      )}
    </div>
    {status === 'uploading' && progress != null && (
      <div className="mt-2 h-1 bg-slate-100 rounded-full overflow-hidden">
        <div
          className="h-full bg-gradient-to-r from-teal-400 to-teal-500 rounded-full transition-all duration-300"
          style={{ width: `${progress}%` }}
        />
      </div>
    )}
  </div>
)
