// frontend/src/modals/melodies/DeployArchetypeModal.jsx
// Deploy or update a melody archetype from the Composer.

import { useState } 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'

export default function DeployArchetypeModal({
  open,
  onClose,
  onSuccess,
  mode = 'new',        // 'new' | 'update'
  archetype = null,    // existing archetype when mode === 'update'
  stepsStr = '',       // CSV notation string from composer
}) {
  const [name, setName] = useState(mode === 'update' ? (archetype?.name ?? '') : '')
  const [pid,  setPid]  = useState(mode === 'update' ? (archetype?.pid  ?? '') : '')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  // Reset fields whenever modal opens
  const handleClose = () => {
    if (loading) return
    setError('')
    onClose()
  }

  const handleSubmit = async () => {
    const trimName = name.trim()
    const trimPid  = pid.trim()
    if (!trimName) { setError('Name is required.'); return }
    if (!trimPid)  { setError('PID is required.');  return }

    setLoading(true)
    setError('')
    try {
      if (mode === 'update' && archetype?.id) {
        const updated = await api.put(`/builder/melodies/${archetype.id}`, {
          name: trimName,
          pid:  trimPid,
          steps: stepsStr,
        })
        onSuccess(updated, 'update')
      } else {
        // Duplicate checks
        const existing = await api.get('/builder/melodies')
        const list = existing.melodies || []
        const dupName = list.find((m) => m.name.toLowerCase() === trimName.toLowerCase())
        if (dupName) { setError(`An archetype named "${trimName}" already exists.`); return }
        const dupPid = list.find((m) => m.pid && m.pid.toLowerCase() === trimPid.toLowerCase())
        if (dupPid)  { setError(`An archetype with PID "${trimPid}" already exists.`); return }

        const created = await api.post('/builder/melodies', {
          name: trimName,
          pid:  trimPid,
          steps: stepsStr,
        })
        onSuccess(created, 'new')
      }
    } catch (err) {
      setError(err.message || 'Something went wrong.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title={mode === 'update' ? 'Update Archetype' : 'Deploy Archetype'}
      size="sm"
      persistent={loading}
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="secondary" onClick={handleClose} disabled={loading}>Cancel</Button>
          <Button variant="primary" onClick={handleSubmit} loading={loading}>
            {mode === 'update' ? 'Update' : 'Deploy'}
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 0 }}>
          {mode === 'update'
            ? 'Save the current composer pattern to this archetype.'
            : 'Create a new archetype from the current composer pattern.'}
        </p>

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

        <FormField
          label="Name"
          name="deploy-name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="e.g. Doksologia_3k"
          required
          disabled={loading}
        />
        <FormField
          label="PID"
          name="deploy-pid"
          type="text"
          value={pid}
          onChange={(e) => setPid(e.target.value)}
          placeholder="e.g. builtin_doksologia_3k"
          required
          disabled={loading}
        />
      </div>
    </Modal>
  )
}
