import React, {FC, useContext, useState} from 'react';
import {StoreContext} from '../store';
import {FileSystem} from '../types';
import {handlePathOpen} from '../fsOperations';
import DevActions from './DevActions';
import Publishing from './Publishing';

const TabButton: FC<{active: boolean; onClick: () => void; label: string;}> = function TabButton({active, onClick, label}) {
  const classes = active ?  "border border-t-blue-500 border-b-none text-sm text-stone-800" : "text-sm";
  return (
    <button 
      className={classes}
      onClick={onClick}
    >
      {label}
    </button>
  );
}


const CurrentApp: FC = function CurrentApp() {
  const [tab, setTab] = useState<"publishing"|"devactions">("devactions");
  const store = useContext(StoreContext);
  let repoData: FileSystem.Repo|null = null;
  if (store && store.currentAppRepoOffset > -1) {
    const workspace = store.workspaceData.payload[0];
    repoData = workspace?.repos[store.currentAppRepoOffset]
  }

  let renderedTab = null;
  if (store) {
    if (repoData && tab === "devactions") {
      renderedTab = <DevActions 
        repoData={repoData} 
        appData={store.appData} 
        devicesData={store.devicesData}
      />;
    } else if (!repoData && tab === "devactions") {
      renderedTab = <div>There is no current app open. Try opening one in the workspace!</div>
    } else if (repoData && tab === "publishing") {
      renderedTab = <Publishing repoData={repoData} appData={store.appData} />
    } else if (!repoData && tab === "publishing") {
      renderedTab = <div>There is no current app open. Try opening one in the workspace!</div>
    }  else {
      renderedTab = <div>This is unreachable codepath</div>
    }
  } else {
    renderedTab = <div>Store is not initialized! Retry</div>
  }

  let header = null;
  if (repoData) {
    header = (<div className="flex flex-row justify-between items-center w-full p-1">
      <div className="text-orange-500">{repoData.name}</div>
      <button onClick={() => repoData && handlePathOpen(repoData.fullPath, 'code')}>
        <img 
          alt="open in vscode"
          src={require('../assets/code.png')}
          className="w-8"
        />
      </button>
    </div>);
  }

  return (
    <div className="w-80">
      {header}
      <div className="flex flex-row gap-2">
        <TabButton 
          label="Dev Actions"
          active={tab === "devactions"}
          onClick={() => setTab("devactions")}
        />
        <TabButton 
          label="Publishing"
          active={tab === "publishing"}
          onClick={() => setTab("publishing")}
        />
      </div>
      {renderedTab}
    </div>
  );
}

export default CurrentApp;
