import { useCallback, useRef } from 'react';
import { JsonEditor } from '@visual-json/react';
import type { JsonValue } from '@visual-json/core';
import { toast } from 'sonner';
import { useFilesAPI } from '../../../hooks/useFilesAPI';

type JsonEditorRendererProps = {
  content: string;
  filePath: string;
  root: string;
  onSave?: (content: string) => void;
};

export const JsonEditorRenderer = ({ content, filePath, root, onSave }: JsonEditorRendererProps) => {
  const { writeFile } = useFilesAPI(root);
  const valueRef = useRef<JsonValue>(JSON.parse(content));

  const handleChange = useCallback((value: JsonValue) => {
    valueRef.current = value;
  }, []);

  const handleSave = useCallback(async () => {
    const newContent = JSON.stringify(valueRef.current, null, 2);
    try {
      await writeFile(filePath, newContent);
      onSave?.(newContent);
      toast.success('File saved');
    } catch {
      toast.error('Failed to save file');
    }
  }, [filePath, writeFile, onSave]);

  return (
    <div
      className="h-full"
      onKeyDown={(ev) => {
        if ((ev.ctrlKey || ev.metaKey) && ev.key === 's') {
          ev.preventDefault();
          handleSave();
        }
      }}
    >
      <JsonEditor
        defaultValue={valueRef.current}
        onChange={handleChange}
        height="100%"
        width="100%"
      />
    </div>
  );
};
