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

function computeStepsAndNotes(stepsStr) {
  if (!stepsStr || !stepsStr.trim()) return { steps: 0, totalNotes: 0 }
  const tokens = stepsStr.trim().split(',')
  const bellSet = new Set()
  for (const token of tokens) {
    for (const part of token.split('+')) {
      const n = parseInt(part.trim(), 10)
      if (!isNaN(n) && n >= 1 && n <= 16) bellSet.add(n)
    }
  }
  return { steps: tokens.length, totalNotes: bellSet.size || 1 }
}

export default function SelectArchetypeModal({ open, onClose, melodyId, currentMelody, currentBuiltMelody, onAssigned }) {
  const [archetypes, setArchetypes] = useState([])
  const [loading, setLoading] = useState(false)
  const [assigning, setAssigning] = useState(null)
  const [error, setError] = useState('')

  useEffect(() => {
    if (open) loadArchetypes()
  }, [open])

  const loadArchetypes = async () => {
    setLoading(true)
    setError('')
    try {
      const data = await api.get('/builder/melodies')
      setArchetypes((data.melodies || []).filter((m) => m.binary_path))
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  const handleSelect = async (archetype) => {
    setAssigning(archetype.id)
    setError('')
    try {
      // Unassign from previously assigned archetype first
      if (currentBuiltMelody?.id && currentBuiltMelody.id !== archetype.id) {
        try {
          await api.post(`/builder/melodies/${currentBuiltMelody.id}/unassign?firestore_melody_id=${melodyId}`)
        } catch { /* best-effort */ }
      }

      const token = localStorage.getItem('access_token')
      const res = await fetch(`/api${archetype.binary_url}`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      if (!res.ok) throw new Error(`Failed to download binary: ${res.statusText}`)
      const blob = await res.blob()
      const file = new File([blob], `${archetype.pid || archetype.name}.bsm`, { type: 'application/octet-stream' })

      await api.upload(`/melodies/${melodyId}/upload/binary`, file)
      await api.post(`/builder/melodies/${archetype.id}/assign?firestore_melody_id=${melodyId}`)

      const csv = archetype.steps || ''
      const { steps, totalNotes } = computeStepsAndNotes(csv)
      if (currentMelody && csv) {
        const existingInfo = currentMelody.information || {}
        const body = {
          information: { ...existingInfo, archetype_csv: csv, steps, totalNotes, outdated_archetype: false },
          default_settings: currentMelody.default_settings,
          type: currentMelody.type,
          uid: currentMelody.uid,
          pid: currentMelody.pid,
        }
        if (currentMelody.url) body.url = currentMelody.url
        await api.put(`/melodies/${melodyId}`, body)
      }

      onAssigned?.({ name: archetype.name, pid: archetype.pid, steps, totalNotes, archetype_csv: csv, id: archetype.id })
      onClose()
    } catch (err) {
      setError(err.message)
    } finally {
      setAssigning(null)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Select Archetype"
      size="md"
      footer={
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
      }
    >
      {error && (
        <div style={{
          padding: 'var(--space-3) var(--space-4)',
          backgroundColor: 'var(--color-danger-bg)',
          border: '1px solid var(--color-danger)',
          borderRadius: 'var(--radius-md)',
          color: 'var(--color-danger)',
          fontSize: 'var(--font-size-sm)',
          marginBottom: 'var(--space-4)',
        }}>
          {error}
        </div>
      )}

      {loading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-10)' }}>
          <Spinner size="md" />
        </div>
      ) : archetypes.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 'var(--space-10)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)' }}>
          No built binaries found. Go to <strong>Archetype Builder</strong> to create one first.
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', maxHeight: 420, overflowY: 'auto' }}>
          {archetypes.map((m) => (
            <div
              key={m.id}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: 'var(--space-3) var(--space-4)',
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-md)',
                backgroundColor: 'var(--color-bg-elevated)',
              }}
            >
              <div>
                <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
                  {m.name}
                </p>
                <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)', marginTop: 2 }}>
                  PID: {m.pid || '—'} &nbsp;·&nbsp; {m.steps?.split(',').length || 0} steps
                </p>
              </div>
              <Button
                variant="primary"
                size="sm"
                disabled={Boolean(assigning)}
                loading={assigning === m.id}
                onClick={() => handleSelect(m)}
              >
                {assigning === m.id ? 'Uploading…' : 'Select & Upload'}
              </Button>
            </div>
          ))}
        </div>
      )}
    </Modal>
  )
}
