import { useEffect, useRef, useState } from 'react';
import { BaseEditor } from '@kevisual/codemirror/editor/editor.ts';
import { Box, Drawer } from '@mui/material';
import { useShallow } from 'zustand/shallow';
import { useContainerStore } from '../store';
import { Tooltip } from '@mui/material';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { LeftOutlined, SaveOutlined } from '@ant-design/icons';

export const DrawEdit = () => {
  const editorElRef = useRef<HTMLDivElement>(null);
  const editorRef = useRef<BaseEditor>(null);
  const containerStore = useContainerStore(
    useShallow((state) => {
      return {
        openDrawEdit: state.openDrawEdit,
        setOpenDrawEdit: state.setOpenDrawEdit,
        data: state.data,
        updateData: state.updateData,
      };
    }),
  );
  const { openDrawEdit, setOpenDrawEdit } = containerStore;
  const [mount, setMount] = useState(false);
  useEffect(() => {
    if (openDrawEdit && editorElRef.current && !mount) {
      editorRef.current = new BaseEditor();
      editorRef.current.createEditor(editorElRef.current);
      setMount(true);
    }

    return () => {
      if (editorRef.current) {
        editorRef.current.destroyEditor();
      }
    };
  }, [openDrawEdit]);

  useEffect(() => {
    if (openDrawEdit && containerStore.data?.id && mount) {
      const editor = editorRef.current;
      const formData = containerStore.data;
      const fileType = editor?.getFileType(formData.title);
      const language = editor?.language;
      if (fileType && fileType !== language) {
        editor?.setLanguage(fileType, editorElRef.current!);
      } else {
        editor?.resetEditor(editorElRef.current!);
      }
      editor?.setContent(formData.code || '');
    }
  }, [openDrawEdit, containerStore.data?.id, mount]);

  return (
    <Drawer
      open={openDrawEdit}
      ModalProps={{
        keepMounted: true, // 保持挂载
        hideBackdrop: true, // 移除mask
        disableEnforceFocus: true, // 允许操作背景内容
        disableAutoFocus: true, // 防止自动聚焦
      }}
      sx={{
        '& .MuiDrawer-paper': {
          width: '50%',
          height: '100%',
          overflow: 'hidden',
        },
      }}
      anchor='right'>
      <div className='bg-secondary w-full h-[48px]'>
        <div className='text-white flex p-2'>
          <div className='ml-2 flex gap-2'>
            <Tooltip title='返回'>
              <IconButton
                sx={{
                  '&:hover': {
                    color: 'primary.main',
                  },
                }}
                onClick={() => {
                  setOpenDrawEdit(false);
                }}>
                <LeftOutlined />
              </IconButton>
            </Tooltip>
            <Tooltip title='保存'>
              <IconButton
                sx={{
                  '&:hover': {
                    color: 'primary.main',
                  },
                }}
                onClick={() => {
                  const code = editorRef.current?.getContent();
                  containerStore.updateData({ id: containerStore.data.id, code }, { refresh: false });
                }}>
                <SaveOutlined />
              </IconButton>
            </Tooltip>
          </div>
          <div className='flex-1 ml-2 flex items-center'>{containerStore.data?.title}</div>
        </div>
      </div>
      <Box
        className='border-primary '
        style={{ height: 'calc(100% - 50px)' }}
        sx={{
          '& .cm-editor': {
            height: '100%',
          },
          '& .cm-scroller': {},
        }}>
        <div className='w-full h-full ' ref={editorElRef}></div>
      </Box>
    </Drawer>
  );
};

export default DrawEdit;
