import React, {FC, useContext, useRef} from 'react';
import Button from '../components/Button';
import {StoreContext} from '../store';


const RepoCloneButton: FC<{workspaceId: number}> = function({workspaceId}) {
  const dialog = useRef<HTMLDialogElement>(null);
  const store = useContext(StoreContext);
  const showDialog = async () => {
    if (dialog.current) {
      dialog.current.showModal();
    }
  }

  const hideDialog = () => {
    if (dialog.current) {
      dialog.current.close();
    }
  }

  const clone = async () => {
    if (store) {
      await fetch(`http://localhost:3100/plugin-server/cli/workspaces/${workspaceId}/cloneApp`, {
        method: 'POST',
        body: JSON.stringify({
          appIntegrations: store.appData.payload.appIntegrations,
          manifest: store.appData.payload.manifest,
          apptileConfig: store.appData.payload.apptileConfig
        }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      hideDialog();
    } else {
      console.error("Store is not defined. Cannot perform clone");
    }
  }

  let contents = null;
  if (store) {
    switch (store.appData.loadingInfo.status) {
    case 'notstarted':
      contents = <div>Data loading has not started. Wait</div>
      break;
    case 'inprogress':
      contents = <div>Loading...</div>;
      break;
    case 'error':
      contents = (<div>
          Error happened {store.appData.loadingInfo.errorMessage}
          <Button label="Retry" onClick={() => {}}></Button>
        </div>);
      break;
    case 'success':
      const {manifest, appIntegrations, apptileConfig} = store.appData.payload;
      contents = (<div>
        <div>name: {manifest.name}</div>
        <div>appId: {manifest.uuid}</div>
        <div>repo: {manifest.gitRepo}</div>
        <div>Integrations</div>
        {appIntegrations.map((it) => {
          return (<div key={it.integrationCode}>{it.integrationCode}:{it.packageLocation}</div>)
        })}
        <div>apptileServer: {apptileConfig.apptileServer}</div>
        <div>appconfigServer: {apptileConfig.appconfigServer}</div>
      </div>)
      break;
    default:
      contents = (<div>Invalid loading state!</div>);
    }
  } else {
    contents = <div>Store is not initialized yet! Wait</div>
  }

  return (<>
    <dialog ref={dialog}>
      {contents}
      
      <Button 
        label="Clone"
        showLoader={store?.appData?.loadingInfo?.status !== 'success'}
        onClick={clone}
      />
      <button
        className="bg-blue-500 p-2 rounded text-white"
        onClick={hideDialog}
      >
        Cancel
      </button>
    </dialog>
    <button 
      className="border border-solid border-green-500 rounded w-14 h-14 mt-1"
      onClick={showDialog}
    >
      +
    </button>
  </>);
}

export default RepoCloneButton;
