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 bg-black/60 flex items-center justify-center z-[2000]">
      <div className="bg-az-panel border border-az-border rounded-lg p-4 w-[700px] max-h-[80vh] shadow-xl flex flex-col">
        <h3 className="text-white font-semibold mb-2">{t('flights.planner.editAsJson')}</h3>
        <textarea
          value={edited}
          onChange={e => handleChange(e.target.value)}
          rows={20}
          className={`flex-1 w-full bg-az-bg border rounded px-3 py-2 text-az-text text-xs font-mono outline-none resize-none ${
            valid ? 'border-az-border focus:border-az-orange' : 'border-az-red'
          }`}
        />
        <p className={`text-xs mt-1 ${valid ? 'text-az-muted' : 'text-az-red'}`}>
          {valid ? t('flights.planner.editJsonHint') : t('flights.planner.invalidJson')}
        </p>
        <div className="flex justify-end gap-2 mt-3">
          <button onClick={onClose}
            className="px-3 py-1 text-sm border border-az-border rounded hover:bg-az-bg text-az-text">
            {t('flights.planner.cancel')}
          </button>
          <button onClick={() => valid && onSave(edited)} disabled={!valid}
            className="px-3 py-1 text-sm bg-az-orange rounded hover:bg-orange-600 text-white disabled:opacity-40">
            {t('flights.planner.save')}
          </button>
        </div>
      </div>
    </div>
  )
}
