// frontend/src/modals/melodies/UploadArchetypeModal.jsx

import { useState, useEffect } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import api from '@/lib/api'

// Decode a .bin/.bsm binary into a steps CSV string
async function decodeBinaryToStepsString(file) {
  const buf  = await file.arrayBuffer()
  const view = new DataView(buf)
  const values = []
  for (let i = 0; i + 1 < buf.byteLength; i += 2) {
    values.push(view.getUint16(i, false))
  }
  return values.map(stepValueToNotation).join(',')
}

function stepValueToNotation(stepValue) {
  const v = Number(stepValue || 0) & 0xffff
  if (!v) return '0'
  const bells = []
  for (let bit = 0; bit < 16; bit++) {
    if (v & (1 << bit)) bells.push(String(bit + 1))
  }
  return bells.join('+')
}

export default function UploadArchetypeModal({ open, existingArchetypes = [], onClose, onUploaded }) {
  const [file, setFile]           = useState(null)
  const [name, setName]           = useState('')
  const [pid, setPid]             = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError]         = useState('')

  useEffect(() => {
    if (!open) { setFile(null); setName(''); setPid(''); setSubmitting(false); setError('') }
  }, [open])

  const handleSubmit = async () => {
    setError('')
    if (!file)        { setError('Please choose a .bin or .bsm file.'); return }
    if (!name.trim()) { setError('Friendly name is required.'); return }
    if (!pid.trim())  { setError('PID is required.'); return }

    const dupName = existingArchetypes.find((a) => a.name?.toLowerCase() === name.trim().toLowerCase())
    if (dupName) { setError(`An archetype named "${name.trim()}" already exists.`); return }
    const dupPid  = existingArchetypes.find((a) => a.pid?.toLowerCase() === pid.trim().toLowerCase())
    if (dupPid)  { setError(`An archetype with PID "${pid.trim()}" already exists.`); return }

    setSubmitting(true)
    try {
      const steps = await decodeBinaryToStepsString(file)
      await api.post('/builder/melodies', { name: name.trim(), pid: pid.trim(), steps })
      onUploaded?.()
      onClose?.()
    } catch (err) {
      setError(err.message || 'Failed to upload archetype.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Upload Archetype"
      subtitle="Decode a .bin/.bsm binary and save as a selectable archetype"
      size="sm"
      persistent={submitting}
      footer={
        <>
          <Button variant="secondary" onClick={onClose} disabled={submitting}>Cancel</Button>
          <Button variant="primary" onClick={handleSubmit} loading={submitting}>Upload Archetype</Button>
        </>
      }
    >
      {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)',
          marginBottom: 'var(--space-4)',
        }}>
          {error}
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {/* File input — FormField doesn't support file type, use labelled wrapper */}
        <div>
          <label style={{
            display: 'block',
            fontSize: 'var(--font-size-sm)',
            fontWeight: 'var(--font-weight-medium)',
            color: 'var(--color-text-secondary)',
            marginBottom: 'var(--space-2)',
          }}>
            Binary File (.bin / .bsm) <span style={{ color: 'var(--color-danger)' }}>*</span>
          </label>
          <input
            type="file"
            accept=".bin,.bsm,application/octet-stream"
            disabled={submitting}
            onChange={(e) => setFile(e.target.files?.[0] || null)}
            style={{
              width: '100%',
              fontSize: 'var(--font-size-sm)',
              color: 'var(--color-text-secondary)',
              backgroundColor: 'var(--color-bg-abyss)',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-md)',
              padding: 'var(--space-2) var(--space-3)',
              cursor: 'pointer',
            }}
          />
          {file && (
            <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 'var(--space-1)' }}>
              {file.name}
            </p>
          )}
        </div>

        <FormField
          label="Friendly Name"
          name="name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="e.g. Doxology Festive"
          disabled={submitting}
          required
        />

        <FormField
          label="PID"
          name="pid"
          type="text"
          value={pid}
          onChange={(e) => setPid(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, ''))}
          placeholder="e.g. builtin_doxology"
          hint="Lowercase letters, numbers, and underscores only"
          disabled={submitting}
          required
        />
      </div>
    </Modal>
  )
}
