import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'

interface Props {
  open: boolean
  jsonText: string
  onClose: () => void
  onSave: (json: string) => void
}

export default function JsonEditorDialog({ open, jsonText, onClose, onSave }: Props) {
  const { t } = useTranslation()
  const [edited, setEdited] = useState(jsonText)
  const [valid, setValid] = useState(true)

  useEffect(() => { setEdited(jsonText) }, [jsonText])

  const handleChange = (value: string) => {
    setEdited(value)
    try { JSON.parse(value); setValid(true) } catch { setValid(false) }
  }

  if (!open) return null

  return (
    <div className="fixed inset-0 flex items-center justify-center z-[2000]" style={{ background: 'rgba(0,0,0,0.6)' }}>
      <div
        className="bracket panel shadow-xl flex flex-col"
        style={{ background: 'var(--surface-1)', padding: '20px', width: '700px', maxHeight: '80vh' }}
      >
        <h3 className="sect-head mb-3">{t('flights.planner.editAsJson')}</h3>
        <textarea
          value={edited}
          onChange={e => handleChange(e.target.value)}
          rows={20}
          className="inp inp-mono flex-1 resize-none"
          style={{
            maxHeight: '60vh',
            borderColor: valid ? undefined : 'var(--accent-red)',
            boxShadow: valid ? undefined : '0 0 0 1px var(--accent-red)',
          }}
        />
        <p className="text-[11px] mt-1.5" style={{ color: valid ? 'var(--text-secondary)' : 'var(--accent-red)' }}>
          {valid ? t('flights.planner.editJsonHint') : t('flights.planner.invalidJson')}
        </p>
        <div className="flex justify-end gap-2 mt-4">
          <button onClick={onClose} className="btn btn-ghost">
            {t('flights.planner.cancel')}
          </button>
          <button onClick={() => valid && onSave(edited)} disabled={!valid} className="btn btn-primary">
            {t('flights.planner.save')}
          </button>
        </div>

        <span className="br" />
      </div>
    </div>
  )
}
