import './polyfills/index';
import React from 'react';
import {render as renderReact, unmountComponentAtNode} from 'react-dom';
import axios from 'axios';
import {match} from 'path-to-regexp';
import copy from 'copy-to-clipboard';
import {normalizeLink} from './utils/normalizeLink';
// import pkg from '../package.json'
import qs from 'qs';
import {
  toast,
  alert,
  confirm,
  defaultFetcher,
  ToastComponent,
  AlertComponent,
  render,
} from './index';

import './locale/zh-CN';

// 默认主题 用这个
export enum THEME_ENUM {
  PANDORA = 'pandora',
  GREEN = 'green',
  GRAY = 'gray',
  CLASSICS = 'classics',
  CHINARED = 'chinaRed',
  BLUE = 'blue',
}

export function embed(
  container: string | HTMLElement,
  schema: any,
  props: any = {theme: THEME_ENUM.PANDORA},
  env: any = {}
) {
  if(props.theme === void 0){
    props.theme = THEME_ENUM.PANDORA
  }
  
  if (typeof container === 'string') {
    container = document.querySelector(container) as HTMLElement;
  }
  if (!container) {
    console.error('选择器不对，页面上没有此元素');
    return;
  } else if (container.tagName === 'BODY') {
    let div = document.createElement('div');
    container.appendChild(div);
    container = div;
  }
  container.classList.add('pandora-scope');
  let scoped: any;

  

  const pandoraEnv = {
    getModalContainer: () =>
      env?.getModalContainer?.() || document.querySelector('.pandora-scope'),
    notify: (type: 'success' | 'error' | 'info' | 'warning', msg: string) =>
      toast[type]
        ? toast[type](msg, type === 'error' ? '系统错误' : '系统消息')
        : console.warn('[Notify]', type, msg),
    alert,
    confirm,
    updateLocation: (to: any, replace: boolean) => {
      if (to === 'goBack') {
        return window.history.back();
      }

      if (replace && window.history.replaceState) {
        window.history.replaceState('', document.title, to);
        return;
      }

      location.href = normalizeLink(to);
    },
    isCurrentUrl: (to: string, ctx?: any) => {
      const link = normalizeLink(to);
      const location = window.location;
      let pathname = link;
      let search = '';
      const idx = link.indexOf('?');
      if (~idx) {
        pathname = link.substring(0, idx);
        search = link.substring(idx);
      }

      if (search) {
        if (pathname !== location.pathname || !location.search) {
          return false;
        }

        const query = qs.parse(search.substring(1));
        const currentQuery = qs.parse(location.search.substring(1));

        return Object.keys(query).every(
          key => query[key] === currentQuery[key]
        );
      } else if (pathname === location.pathname) {
        return true;
      } else if (!~pathname.indexOf('http') && ~pathname.indexOf(':')) {
        return match(link, {
          decode: decodeURIComponent,
          strict: ctx?.strict ?? true
        })(location.pathname);
      }

      return false;
    },
    jumpTo: (to: string, action?: any) => {
      if (to === 'goBack') {
        return window.history.back();
      }

      to = normalizeLink(to);

      if (action && action.actionType === 'url') {
        action.blank === false ? (window.location.href = to) : window.open(to);
        return;
      }

      // 主要是支持 nav 中的跳转
      if (action && to && action.target) {
        window.open(to, action.target);
        return;
      }

      if (/^https?:\/\//.test(to)) {
        window.location.replace(to);
      } else {
        location.href = to;
      }
    },
    fetcher: defaultFetcher(env),
    isCancel: (value: any) => (axios as any).isCancel(value),
    copy: (contents: string, options: any = {}) => {
      const ret = copy(contents, options);
      ret && options.shutup !== true && toast.info('内容已拷贝到剪切板');
      return ret;
    },
    affixOffsetBottom: 0,
    ...env
  };

  let pandoraProps: any = {};
  function createElements(props: any): any {
    pandoraProps = {
      ...pandoraProps,
      ...props,
      scopeRef: (ref: any) => (scoped = ref)
    };

    return (
      <div className="pandora-root-wrapper">
        <ToastComponent
          position={(env && env.toastPosition) || 'top-right'}
          closeButton={false}
          timeout={5000}
          locale={props?.locale}
          theme={props?.theme}
        />
        <AlertComponent
          locale={props?.locale}
          theme={props?.theme}
          container={() => env?.getModalContainer?.() || container}
        />

        {render(schema, pandoraProps, pandoraEnv)}
      </div>
    );
  }

  renderReact(createElements(props), container);

  return {
    ...scoped,
    updateProps: (props: any, callback?: () => void) => {
      renderReact(createElements(props), container as HTMLElement, callback);
    },
    unmount: () => {
      unmountComponentAtNode(container as HTMLElement);
    }
  };
}

export * from './index'

// export const version = pkg.version