import { createEditorInstance, editor } from '@kevisual/codemirror/dist/editor.json';
import { useEffect, useRef, useLayoutEffect, useState, useCallback } from 'react';
import { useLocation } from 'react-router';
import { useCodeEditorStore, ParseData } from '../store';
import { Button, message, Tooltip } from 'antd';
import { LeftOutlined, MessageOutlined, SaveOutlined } from '@ant-design/icons';
import { useAiStore } from '@/pages/ai-chat';
import { useShallow } from 'zustand/react/shallow';
import { useNewNavigate } from '@/modules';
export const App = () => {
  const ref = useRef<HTMLDivElement>(null);
  const editorRef = useRef<typeof editor>(null);
  const location = useLocation();
  const store = useCodeEditorStore();
  const [mounted, setMounted] = useState(false);
  const navigator = useNewNavigate();
  const aiStore = useAiStore(
    useShallow((state) => {
      return {
        setOpen: state.setOpen,
        setKey: state.setKey,
      };
    }),
  );
  useEffect(() => {
    initEditor();
    const state = location.state as ParseData;
    if (state && state.data) {
      store.init(state);
    }
    setMounted(true);
    return () => {
      setMounted(false);
    };
  }, []);
  useLayoutEffect(() => {
    if (!mounted) return;
    if (editorRef.current) {
      setNewValue(store.code);
    } else {
      setNewValue('');
    }
  }, [store.code, mounted]);
  const initEditor = () => {
    const _editor = createEditorInstance(ref.current!);
    editorRef.current = _editor;
  };
  const setNewValue = (value: string) => {
    const editor = editorRef.current;
    if (editor) {
      editor.dispatch({
        changes: [{ from: 0, to: editor.state.doc.length, insert: value }],
      });
    }
  };
  const getValue = () => {
    const editor = editorRef.current;
    if (editor) {
      return editor.state.doc.toString();
    }
    return '';
  };
  const onSave = useCallback(async () => {
    const value = getValue();
    // store.onUpdate(value);
    if (store.dataType === 'object') {
      try {
        JSON.parse(value);
      } catch (error) {
        console.error(error);
        message.error('JSON format error');
        return;
      }
    }
    store.onUpdate(value);
  }, [store.dataType]);

  return (
    <div className='w-full h-full bg-gray-400 flex flex-col'>
      <div className='p-4 flex-grow overflow-hidden'>
        <div className='h-full w-full overflow-hidden'>
          <Button.Group className='mb-2'>
            <Tooltip title='Go Back' placement='bottom'>
              <Button
                className=''
                icon={<LeftOutlined />}
                onClick={() => {
                  navigator(-1);
                }}></Button>
            </Tooltip>
            <Tooltip title='Ai Chat'>
              <Button
                className=''
                onClick={() => {
                  aiStore.setOpen(true);
                  aiStore.setKey(location.pathname);
                }}
                icon={<MessageOutlined />}></Button>
            </Tooltip>
            <Tooltip title='Save' placement='bottom'>
              <Button className='' onClick={onSave} icon={<SaveOutlined />}></Button>
            </Tooltip>
          </Button.Group>
          <div className='w-full p-4 rounded-md bg-white overflow-hidden relative' style={{ height: 'calc(100% - 130px)' }}>
            <div className='w-full h-full scrollbar'>
              <div className='w-full h-full' ref={ref}></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
