import React, { useContext, useEffect } from "react";
import Button from "../components/Button";
import { StoreContext } from "../store";
import { FileSystem } from "../types";

export interface IWebBundle {
  id: number;
  partner: string;
  staging: boolean;
  cdnLink: string;
  s3Link: string;
  comment: any;
  createdAt: string;
  updatedAt: string;
  deletedAt: any;
};

export interface IWebLiveBundle {
  artifactId: number;
  partner: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: any;
};

const WebSDK: React.FC<{}> = () => {
  const [fileName, setFileName] = React.useState<string>("");
  const [partners, setPartners] = React.useState<Array<string>>([]);
  const [selectedPartner, setSelectedPartner] = React.useState<string>("");
  const store = useContext(StoreContext);
  const [availableBundles, setAvailableBundles] = React.useState<
    Array<IWebBundle>
  >([]);
  let repoData: FileSystem.Repo | null = null;
  if (store && store.currentAppRepoOffset > -1) {
    const workspace = store.workspaceData.payload[0];
    repoData = workspace?.repos[store.currentAppRepoOffset];
  }

  const pluginServerBaseURL = `${process.env.REACT_APP_SERVER_URL}/plugin-server/webSDK/${repoData?.appId}`;
  const pluginServerBaseURLWithoutAppId = `${process.env.REACT_APP_SERVER_URL}/plugin-server/webSDK/`;

  const [liveBundle, setLiveBundle] = React.useState<IWebLiveBundle | null>(
    null
  );
  const [readyToUpload, setReadyToUpload] = React.useState<boolean>(false);
  const [currentUploaded, setCurrentUploaded] = React.useState<IWebBundle | null>(null);
  const [activeTab, setActiveTab] = React.useState<string>("newBundle");
  async function storeFileName(e: React.ChangeEvent<HTMLInputElement>) {
    setFileName(e.target.value);
  }

  const compileUMDBundle = async () => {
    try {
      await fetch(
        `${pluginServerBaseURLWithoutAppId}/compile?sourceFolder=${fileName}`
      );
      setReadyToUpload(true);
    } catch (err) {
      console.error("Error during compilation: ", err);
    }
  }

  // const serveCompiledBundleDirectly = async () => {
  //   try {
  //     await fetch(
  //       `${pluginServerBaseURL}/compile?sourceFolder=${fileName}`
  //     );
  //     setReadyToUpload(true);
  //   } catch (err) {
  //     console.error("Error during compilation: ", err);
  //   }
  // }

  const getAvailablePartners = async () => {
    try {
      const response = await fetch(
        `${pluginServerBaseURL}/partners`
      );
      const responseData = await response.json();
      setPartners(responseData);
    } catch (err) {
      console.error("Error during bundle fetching: ", err);
    }
  }

  const uploadToS3 = async () => {
    try {
      const uploadedBundle = await fetch(
        `${pluginServerBaseURL}/upload/${selectedPartner}`,
      );
      setCurrentUploaded(await uploadedBundle.json());
      setReadyToUpload(false);
    } catch (err) {
      console.error("Error during upload: ", err);
    }
  }

  const getAvailableBundle = async () => {
    try {
      const response = await fetch(
        `${pluginServerBaseURL}/bundles/${selectedPartner}`
      );
      const responseData = await response.json();
      setAvailableBundles(responseData);
    } catch (err) {
      console.error("Error during bundle fetching: ", err);
    }
  }

  const makeCurrentBundleLive = async (bundleId: string) => {
    try {
      await fetch(
        `${pluginServerBaseURL}/live/${bundleId}`,
        {
          method: "POST",
        }
      );
      getCurrentLiveBundle();
    } catch (err) {
      console.error("Error during making bundle live: ", err);
    }
  };

  const makeCurrentBundleLocalLive = async (artifactId: string) => {
    try {
      window.parent.postMessage({type: "setWebSdkArtifactId", artifactId}, "*");
    } catch (err) {
      console.error("Error during making bundle local live: ", err);
    }
  };

  const getCurrentLiveBundle = async () => {
    try {
      const response = await fetch(
        `${pluginServerBaseURL}/live/${selectedPartner}`
      );
      const responseData = await response.json();
      setLiveBundle(responseData);
    } catch (err) {
      console.error("Error during bundle fetching: ", err);
    }
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${day}/${month}/${year}, ${hours}:${minutes}`;
  };

  useEffect(() => {
    getAvailableBundle();
    getCurrentLiveBundle();
    getAvailablePartners();
    // eslint-disable-next-line
  }, [selectedPartner]);

  return (
    <div
      className="flex flex-col items-left justify-center border rounded border-gray-500 p-4 ml-10 "
      style={{ width: 400 }}
    >
      <h1 className="mb-2">Web bundle manager</h1>
      <div className="mb-2">
        <label className="mb-2 text-xs">Select Partner:</label>
        <select
          className=" text-xs shadow appearance-none border rounded w-1/2 py-1 px-2 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          defaultValue={selectedPartner}
          onChange={(e) => {
            setSelectedPartner(e.target.value);
            setLiveBundle(null);
            setAvailableBundles([]);
          }}
        >
          <option value="">Select a partner</option>
          {partners.map((partner, index) => (
            <option key={index} value={partner}>
              {partner}
            </option>
          ))}
        </select>
      </div>
      {liveBundle && (
        <div className="mb-2">
          <p className="text-green-50 text-xs">Current live bundle</p>
          <p className="text-xs">
            {JSON.stringify({
              id: liveBundle.artifactId,
              partner: liveBundle.partner,
            })}
          </p>
        </div>
      )}
      <div className="flex">
        <Button
          onClick={() => {
            setActiveTab("newBundle");
            setReadyToUpload(false);
          }}
          className={
            activeTab === "newBundle"
              ? "bg-blue-500 text-white text-xs"
              : "text-xs"
          }
          label="New Bundle"
        />
        <Button
          onClick={() => {
            setActiveTab("liveBundle");
            getAvailableBundle();
            getCurrentLiveBundle();
            setCurrentUploaded(null);
          }}
          className={
            activeTab === "liveBundle"
              ? "bg-blue-500 text-white text-xs"
              : "text-xs"
          }
          label="Bundle manager"
        />
      </div>
      <div className="mt-4 overflow-y-auto" style={{ height: 400 }}>
        {activeTab === "newBundle" && (
          <div>
            <div className="mb-2">
              <label className="mb-2 text-xs">Entry file path:</label>
              <input
                type="text"
                className=" text-xs shadow appearance-none border rounded w-full py-1 px-2 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                onChange={storeFileName}
              />
            </div>
            <Button
              className="text-xs"
              onClick={compileUMDBundle}
              label="Compile UMD bundle"
            />
            <Button
              disabled={!readyToUpload || !selectedPartner}
              className="text-xs"
              onClick={uploadToS3}
              label="Upload to S3"
            />
            {currentUploaded && (
              <p className="text-green-500">
                Upload success! with ID: {currentUploaded?.id}
              </p>
            )}
          </div>
        )}
        {activeTab === "liveBundle" && (
          <div className="flex flex-col ">
            <h2 className="mb-2">Available bundles</h2>
            <ul className="mb-2">
              {availableBundles.length > 0 ? (
                availableBundles.map((bundle: IWebBundle, index: number) => (
                  <li key={index} className="mb-2 border p-2 text-xs">
                    {JSON.stringify({
                      id: bundle.id,
                      createdAt: formatDate(bundle.createdAt),
                      updatedAt: formatDate(bundle.updatedAt),
                      comment: bundle.comment,
                      partner: bundle.partner,
                    })}
                    <Button
                      onClick={() => {
                        makeCurrentBundleLocalLive(bundle.id.toString());
                      }}
                      label="Local live"
                    />
                    <Button
                      onClick={() => {
                        makeCurrentBundleLive(bundle.id.toString());
                      }}
                      className={
                        liveBundle?.artifactId === bundle.id
                          ? "bg-green-500 text-white"
                          : ""
                      }
                      label={
                        liveBundle?.artifactId === bundle.id
                          ? "Live"
                          : "Global live"
                      }
                    />
                  </li>
                ))
              ) : (
                <li>No bundles available</li>
              )}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
};

export default WebSDK;
