import type { FolderEntry } from '@/lib/client-types'
import { validateFolder } from '@/lib/validate-folder'

interface FolderDropzoneProps {
  isUploading: boolean
  onFolderSelected: (entry: FolderEntry) => void
  onError: (message: string) => void
}

export default function FolderDropzone({
  isUploading,
  onFolderSelected,
  onError,
}: FolderDropzoneProps) {
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files
    if (!selected || selected.length === 0) return

    const fileArray = Array.from(selected)
    const folderName = fileArray[0].webkitRelativePath?.split('/')[0] || 'folder'
    const validation = validateFolder(fileArray)

    if (validation.errors.length > 0) {
      onError(validation.errors.join(' | '))
      return
    }

    const entry: FolderEntry = {
      folderName,
      modelFile: validation.model!,
      textures: validation.textures,
      status: 'pending',
      progress: 0,
      warnings: validation.warnings,
      modelUrl: URL.createObjectURL(validation.model!),
      viewerOpen: true,
    }
    onFolderSelected(entry)
  }

  return (
    <>
      <input
        type="file"
        id="folder-input"
        {...({ webkitdirectory: '', directory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
        multiple
        className="hidden"
        onChange={handleChange}
      />

      <div
        onClick={() => document.getElementById('folder-input')?.click()}
        className={`
          relative border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-all duration-200 bg-black-800
          ${isUploading ? 'cursor-not-allowed opacity-60 border-white/20' : ''}
          ${!isUploading ? 'border-white/30 hover:border-white/50 hover:bg-black-700' : ''}
        `}
      >
        <div className="flex justify-center mb-3">
          <div className="w-12 h-12 rounded-full flex items-center justify-center bg-black-700">
            <svg
              className="w-6 h-6 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={1.5}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
              />
            </svg>
          </div>
        </div>
        <p className="text-sm font-medium text-gray-300">
          Deposez votre dossier ici
          <span className="text-gray-500 font-normal"> ou cliquez pour parcourir</span>
        </p>
        <p className="text-xs text-gray-500 mt-1">
          Contenu attendu : model.glb/gltf + textures (roughness, normal, metalness, color, displace)
          <br />Les originaux sont archives sur le Drive, les comprimes sont envoyes sur Git.
        </p>
      </div>
    </>
  )
}
