import { useEffect, useLayoutEffect, useState } from 'react';
import { getHistoryState, setHistoryState } from '@kevisual/store/web-page.js';
import { Draw } from './pages/Draw';
import { App as Manager, ProviderManagerName, useManagerStore } from '../mark/manager/Manager';
import { ToastProvider } from '@/modules/toast/Provider';

import './index.css';
import { useShallow } from 'zustand/shallow';
import { toast } from 'react-toastify';

// @ts-ignore
window.EXCALIDRAW_ASSET_PATH = 'https://esm.sh/@excalidraw/excalidraw@0.18.0/dist/prod/';

export const App = () => {
  return (
    <ToastProvider>
      <DrawApp />
    </ToastProvider>
  );
};
export const getUrlId = () => {
  const url = new URL(window.location.href);
  return url.searchParams.get('id') || '';
};
export const DrawApp = () => {
  const [id, setId] = useState('');
  const urlId = getUrlId();

  useLayoutEffect(() => {
    const state = getHistoryState();
    if (state?.id) {
      setId(state.id);
      return;
    }
    if (urlId) {
      setId(urlId);
    }
  }, []);

  return (
    <div className='bg-white w-full h-full flex'>
      <Manager
        showSearch={true}
        showAdd={true}
        markType={'excalidraw'}
        openMenu={!urlId}
        onClick={(data) => {
          if (data.id !== id) {
            setId('');
            const url = new URL(location.href);
            url.searchParams.set('id', data.id);
            console.log('set url', url.toString());
            setHistoryState({}, url.toString());
            setTimeout(() => {
              setId(data.id);
            }, 200);
            const _store = useManagerStore.getState(ProviderManagerName);
            if (_store.markData) {
              _store.setCurrentMarkId('');
              // _store.setOpen(false);
              _store.setMarkData(undefined);
            }
          } else if (data.id === id) {
            toast.success('已选择当前画布');
          }
          console.log('onClick', data, id);
        }}>
        <div className='h-full grow'>
          <DrawWrapper id={id} setId={setId} />
        </div>
      </Manager>
    </div>
  );
};

export const DrawWrapper = (props: { id?: string; setId: (id: string) => void }) => {
  const { id, setId } = props;
  const store = useManagerStore(
    useShallow((state) => {
      return {
        currentMarkId: state.currentMarkId,
      };
    }),
  );
  console.log('DrawApp store', store);
  return (
    <>
      {id ? (
        <Draw
          id={id}
          onClose={() => {
            setId('');
            setHistoryState({
              id: '',
            });
          }}
        />
      ) : (
        <div className='flex items-center justify-center h-full text-gray-500'> {store.currentMarkId ? '' : '请先选择一个画布'} </div>
      )}
    </>
  );
};
