import { useState, useEffect } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { useLanguage } from './LanguageContext';
import { translations } from '../constants/translations';

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

const JsonEditorDialog = ({ open, onClose, jsonText, onSave }: JsonEditorDialogProps) => {
  const [editedJson, setEditedJson] = useState(jsonText);
  const [isValid, setIsValid] = useState(true);
  const { targetLanguage } = useLanguage();
  const t = translations[targetLanguage];

  useEffect(() => {
    setEditedJson(jsonText);
  }, [jsonText]);

  const handleJsonChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditedJson(e.target.value);

    try {
      JSON.parse(e.target.value);
      setIsValid(true);
    } catch {
      setIsValid(false);
    }
  };

  const handleSave = () => {
    if (isValid) {
      onSave(editedJson);
    } else {
      alert(t.invalid);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="md">
      <DialogTitle>{t.edit}</DialogTitle>
      <DialogContent>
        <TextField
          autoFocus
          multiline
          rows={20}
          fullWidth
          variant="outlined"
          value={editedJson}
          onChange={handleJsonChange}
          helperText={!isValid ? t.invalid : t.editm}
          error={!isValid}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="primary">
          {t.cancel}
        </Button>
        <Button onClick={handleSave} color="primary" disabled={!isValid}>
          {t.save}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default JsonEditorDialog;
