import React, {useState} from 'react';
import * as ReactDOM from 'react-dom/client';

function Publish(props = {}) {
  const [state, setState] = useState({loading: false});
  const updateState = (update) => setState(Object.assign({}, state, update));

  if (window.devTool.publicUrl) {
    return;
  }

  return <div>
    {state.loading &&
      <div className="overlay overlay--loading">Loading, Please wait...</div>
    }
    <button onClick={submit} disabled={state.loading} className="btn btn--primary">Publish</button>
  </div>;

  async function submit() {
    const ready = confirm('Are you ready to submit the code?');
    if (!ready) {
      return;
    }

    updateState({loading: true});

    try {
      const response = await fetch(`/publish`);
      const data = await response.json();
      if (data.success) {
        alert('Your code is successfully sent to project manager! Thank you!');
      } else {
        alert('Can\'t send your code, please try again or contact project manager.');
      }
    } catch (error) {
      alert('Something went wrong, please try again or contact project manager.');
    }

    updateState({loading: false});
  }
}

export function setupPublish(rootAttributes) {
  // INIT
  const wrapper = document.createElement('div');
  wrapper.setAttribute('id', 'publish-btn');
  document.querySelector('.page_toolbar__right').append(wrapper)

  const root = ReactDOM.createRoot(wrapper);
  const html = (<Publish rootAttributes={rootAttributes}/>);
  root.render(html);
}
