import { useState, useEffect } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import { getLanguageName, parseLocalizedString, serializeLocalizedString } from '@/lib/melodyUtils'

export default function TranslationModal({ open, onClose, field, fieldKey, value, languages, primaryLanguage, onChange, multiline }) {
  const [draft, setDraft] = useState({})

  useEffect(() => {
    if (open) setDraft(parseLocalizedString(value))
  }, [open, value])

  const updateDraft = (lang, text) => setDraft((prev) => ({ ...prev, [lang]: text }))

  const handleSave = () => {
    onChange(fieldKey, serializeLocalizedString(draft))
    onClose()
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={`Translations — ${field}`}
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" onClick={handleSave}>Save Translations</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        {(languages || ['en']).map((lang) => (
          <div key={lang}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 'var(--space-2)', marginBottom: 'var(--space-1)' }}>
              <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)' }}>
                {getLanguageName(lang)}
              </span>
              {lang === primaryLanguage && (
                <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>primary</span>
              )}
              <span style={{ fontSize: 'var(--font-size-xs)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', textTransform: 'uppercase' }}>
                {lang}
              </span>
            </div>
            <FormField
              label=""
              name={`trans-${lang}`}
              type={multiline ? 'textarea' : 'text'}
              rows={2}
              value={draft[lang] || ''}
              onChange={(e) => updateDraft(lang, e.target.value)}
            />
          </div>
        ))}
      </div>
    </Modal>
  )
}
