import React, {FC, useContext, useEffect, useRef} from 'react';
import Button from '../components/Button';
import AsyncButton from '../components/AsyncButton';
import {FileSystem} from '../types';
import {StoreDispatchContext, fetchWorkspaceData, StoreState, fetchDevicesData} from '../store';

type DevActionsProps = {
  repoData: FileSystem.Repo, 
  appData: StoreState['appData'], 
  devicesData: StoreState['devicesData']
};
const DevActions: FC<DevActionsProps> = function DevActions({repoData, appData, devicesData}) {
  const dispatch = useContext(StoreDispatchContext);
  useEffect(() => {
    fetchDevicesData(dispatch, false, false);
  }, [dispatch]);
  const androidDevice = useRef<HTMLSelectElement>(null);
  const iosDevice = useRef<HTMLSelectElement>(null);
  const appId = repoData.appId;

  const killMetro = () => {
    fetch(`http://localhost:3100/plugin-server/home/killMetro`, {method: 'DELETE'});
  };

  const runIOS = () => {
    const el = iosDevice.current;
    if (el) {
      fetch(`http://localhost:3100/plugin-server/home/${appId}/runIOS/${el.value || 'none'}`, {method: 'POST'})
    } else {
      console.error("No ios device select item found");
    }
    // fetch(`http://localhost:3100/plugin-server/home/${appId}/build/ios/debug`, {method: 'POST'});
  }

  const releaseBuildIOS = () => {
    const el = iosDevice.current;
    if (el) {
      let query = `?deviceId=${el.value}`
      fetch(`http://localhost:3100/plugin-server/home/${appId}/build/ios/release${query}`, {method: 'POST'});
    } else {
      console.error("No ios device select item found");
    }
  }

  const bundleIOS = async () => {
    await fetch(`http://localhost:3100/plugin-server/home/${appId}/bundleJsIOS`, {method: 'POST'})
    return fetchWorkspaceData(dispatch, false, false);
  }

  const runAndroid = () => {
    const el = androidDevice.current;
    if (el) {
      fetch(`http://localhost:3100/plugin-server/home/${appId}/runAndroid/${el.value || 'none'}`, {method: 'POST'})
    } else {
      console.error("No android device select item found");
    }
  }

  const buildAndroid = () => {
    const el = androidDevice.current;
    let queryParam = '';
    if (el) {
      queryParam = `?deviceId=${el.value}`;
    } else {
      console.error("No android device select item found");
    }
    fetch(`http://localhost:3100/plugin-server/home/${appId}/build/android/release${queryParam}`, {method: 'POST'})
  }

  const doNpmInstall = async () => {
    await fetch(`http://localhost:3100/plugin-server/cli/app/${appId}/npmInstall`, {method: 'POST'});
  }

  const doPodInstall = async () => {
    await fetch(`http://localhost:3100/plugin-server/cli/app/${appId}/podInstall`, {method: 'POST'});
  }

  const bundleAndroid = async () => {
    await fetch(`http://localhost:3100/plugin-server/home/${appId}/bundleJSAndroid`, {method: 'POST'})
    return fetchWorkspaceData(dispatch, false, false);
  }

  const rebuildWebAll = async () => {
    await fetch(`http://localhost:3100/plugin-server/plugins/${appId}/compileall`, {
      method: 'POST'
    });
  }

  const refreshIntegrations = async () => {
    if (appData.loadingInfo.status === 'success') {
      await fetch(`http://localhost:3100/plugin-server/home/${appId}/refreshIntegrations`, 
       {
         method: 'POST',
         body: JSON.stringify({integrations: appData.payload.appIntegrations}),
         headers: {
           "Content-Type": "application/json"
         }
       }
      );
    } else {
      console.error("appData has not loaded properly yet");
    }
  }

  let result = (
    <div className="flex flex-col gap-2">
      <div className="border p-1 rounded">
        <div>Repo management</div>
        <div className="flex flex-row flex-wrap w-full p-2 gap-1">
          <AsyncButton 
            label="Codegen Integrations" 
            onClick={refreshIntegrations}
          />
          <AsyncButton label="NPM Install" onClick={doNpmInstall}/>
          <AsyncButton label="Pod install" onClick={doPodInstall}/>
          <Button 
            label="Kill Metro" 
            onClick={killMetro}
          />
        </div>
      </div>
      <div className="border p-1 rounded">
        <div>Android</div>
        <div className="p-2">
          <select ref={androidDevice} className="text-xs w-full">
            {
              devicesData.payload.android.map(it => (
                <option key={it.id} value={it.id}>
                  {it.name}
                </option>
              ))
            }
          </select>
        </div>
        <div className="flex flex-row gap-1 text-sm p-2">
          <Button label="Debug" onClick={runAndroid}/>
          <Button label="Build" onClick={buildAndroid}/>
          <AsyncButton 
            label="Bundle Codepush" 
            onClick={bundleAndroid}
          />
        </div>
      </div>
      <div className="border p-1 rounded">
        <div>iOS</div>
        <div className="p-2">
          <select ref={iosDevice} className="text-xs w-full">
          {
            devicesData.payload.ios.map(it => (
              <option key={it.id} value={it.id}>
                {it.name} 
              </option>
            ))
          }
          </select>
        </div>
        <div className="flex flex-row gap-1 text-sm p-2">
          <Button label="Debug" onClick={runIOS}/>
          <Button label="Build" onClick={releaseBuildIOS}/>
          <AsyncButton 
            label="Bundle Codepush" 
            onClick={bundleIOS}
          />
        </div>
      </div>
      <div className="border p-1 rounded">
        <div>Web</div>
        <AsyncButton 
          label="Rebuild All" 
          onClick={rebuildWebAll}
        />
      </div>
    </div>
  );

  return result;
}

export default DevActions;
