// frontend/src/modals/manufacturing/UploadAssetModal.jsx
import { useState, useRef } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'

function formatBytes(bytes) {
  if (!bytes) return '—'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
}

export default function UploadAssetModal({ open, hwType, assetName, onClose, onSaved }) {
  const [file, setFile]         = useState(null)
  const [uploading, setUploading] = useState(false)
  const [error, setError]       = useState('')
  const [dragging, setDragging] = useState(false)
  const fileInputRef            = useRef(null)

  const handleClose = () => { setFile(null); setError(''); onClose() }

  const handleFile = (f) => {
    if (!f) return
    if (!f.name.endsWith('.bin')) { setError('Only .bin files are accepted.'); return }
    setFile(f); setError('')
  }

  const handleUpload = async () => {
    if (!file) return
    setError(''); setUploading(true)
    try {
      const formData = new FormData()
      formData.append('file', file)
      const token = localStorage.getItem('access_token')
      const res = await fetch(`/api/manufacturing/flash-assets/${hwType}/${assetName}`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.detail || 'Upload failed')
      }
      onSaved()
      handleClose()
    } catch (err) {
      setError(err.message)
    } finally {
      setUploading(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title={`Upload ${assetName}`}
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={handleClose}>Cancel</Button>
          <Button variant="primary" onClick={handleUpload} loading={uploading} disabled={!file}>
            Upload
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          Board:{' '}
          <span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-secondary)' }}>{hwType}</span>
          {' '}— overwrites any existing file.
        </p>

        {error && (
          <div style={{ padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>
            {error}
          </div>
        )}

        {/* Drop zone */}
        <div
          role="button"
          tabIndex={0}
          aria-label="Upload file drop zone"
          onClick={() => fileInputRef.current?.click()}
          onDragOver={(e) => { e.preventDefault(); setDragging(true) }}
          onDragLeave={() => setDragging(false)}
          onDrop={(e) => {
            e.preventDefault(); setDragging(false)
            handleFile(e.dataTransfer.files[0])
          }}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') fileInputRef.current?.click() }}
          style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 'var(--space-2)',
            padding: 'var(--space-8) var(--space-4)',
            border: `2px dashed ${file ? 'var(--color-primary)' : dragging ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
            borderRadius: 'var(--radius-lg)',
            backgroundColor: file ? 'var(--color-primary-subtle)' : dragging ? 'var(--color-primary-subtle)' : 'var(--color-bg-abyss)',
            cursor: 'pointer',
            transition: 'all 0.15s ease',
          }}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".bin"
            onChange={(e) => handleFile(e.target.files[0])}
            style={{ display: 'none' }}
          />

          {file ? (
            <>
              <Icon name="check" size={20} color="var(--color-primary)" />
              <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-primary)', textAlign: 'center', wordBreak: 'break-all' }}>{file.name}</span>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{formatBytes(file.size)}</span>
            </>
          ) : (
            <>
              <Icon name="upload" size={20} color="var(--color-text-muted)" />
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', textAlign: 'center' }}>
                Click or drop a <span style={{ fontFamily: 'var(--font-family-mono)' }}>.bin</span> file
              </span>
            </>
          )}
        </div>
      </div>
    </Modal>
  )
}
