import CloudUploadOutlined from '@ant-design/icons/CloudUploadOutlined';

import { BaseEditor } from '@kevisual/codemirror/editor/editor.ts';
import { IconButton } from '@kevisual/components/button/index.tsx';
import { Button, Tooltip } from 'antd';
import { UploadIcon } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useDropzone } from 'react-dropzone';
import { CacheWorkspace } from '@kevisual/cache';
import { useHomeStore } from './store/index.ts';
import { UploadModal } from './module/UploadModal.tsx';
import { useShallow } from 'zustand/shallow';
import { toast } from 'react-toastify';
import { SuccessModal } from './module/SuccessModal.tsx';

export const Home = () => {
  const editorElRef = useRef<HTMLDivElement>(null);
  const editorRef = useRef<BaseEditor>(null);
  const { initApp, setOpenUploadModal, setText, filename } = useHomeStore(
    useShallow((state) => ({ initApp: state.initApp, setOpenUploadModal: state.setOpenUploadModal, setText: state.setText, filename: state.filename })),
  );
  const onDrop = (acceptedFiles) => {
    console.log(acceptedFiles);
    const file = acceptedFiles[0];
    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target?.result as string;
      editorRef.current!.setContent(content);
    };
    reader.readAsText(file);
  };
  const { getRootProps, getInputProps } = useDropzone({ onDrop, accept: { 'text/html': ['.html'], 'text/javascript': ['.js'], 'text/css': ['.css'] } });

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

  const initEditor = async () => {
    if (!editorElRef.current) return;
    const cache = new CacheWorkspace();
    let cacheData = '';
    try {
      cacheData = (await cache.storage.get('html-editor')) || '';
    } catch (error) {
      console.error(error);
    }
    editorRef.current = new BaseEditor({
      filename: filename || 'index.html',
      onChange: (value) => {
        cache.storage.set('html-editor', value);
      },
    });
    editorRef.current.createEditor(editorElRef.current);
    setTimeout(() => {
      editorRef.current!.setContent(cacheData);
    }, 300);
  };

  return (
    <div className='flex flex-row w-full h-full'>
      <div className='flex flex-col text-primary border-r border-gray-200 px-2 pt-2'>
        <div>
          <Tooltip title='部署应用' placement='right'>
            <IconButton
              onClick={() => {
                const editorContent = editorRef.current?.getContent();
                if (editorContent) {
                  setOpenUploadModal(true);
                  setText(editorContent);
                } else {
                  toast.error('请先输入代码');
                }
              }}>
              <CloudUploadOutlined />
            </IconButton>
          </Tooltip>
        </div>
        <div className=' mt-2' {...getRootProps()}>
          <Tooltip title='点击上传html或者js文件  ' placement='right'>
            <IconButton>
              <UploadIcon size={16} />
            </IconButton>
            <input type='file' style={{ display: 'none' }} {...getInputProps()} />
          </Tooltip>
        </div>
      </div>
      <div className='h-full grow px-2'>
        <div className=' py-1'>
          <i className=' text-gray-500' style={{ fontSize: 10 }}>
            {'>'} 快速部署html小应用, 粘贴前端html代码。点击部署。(这个页面内容自动缓存到本地)
          </i>
        </div>
        <div className=' border rounded-md border-gray-200 scrollbar' style={{ height: 'calc(100% - 50px)' }}>
          <div className='w-full h-full ' ref={editorElRef}></div>
        </div>
      </div>
      <UploadModal />
      <SuccessModal />
    </div>
  );
};
