import * as React from "react";
import { useState, useEffect } from "@theia/core/shared/react";
import { createUseStyles } from "react-jss";
import Modal from "react-modal";
import { useCommonStyles } from "../StorjWidget/StorjWidget.style";
import { LocalStorageKey, RCloneEndPoints } from "../../constants";
import { IRCloneFile } from "../StorjWidget/StorjWidget.interface";
import fetchRClone from "../../helpers/fetchRClone";
import BackButton from "../BackButton";

const useStyles = createUseStyles({
  contentContainer: {
    position: "relative",
    height: "100%",
    display: "flex",
    flexDirection: "column",
  },
  confirmButton: {
    backgroundColor: "#F57C00 !important",
    color: "#fff !important",
  },
  actionsContainer: {
    alignSelf: "flex-end",
    marginTop: "auto",
  },
  commonButton: {
    borderRadius: 2,
    textTransform: "uppercase",
    height: 32,
  },
  innerContent: {
    display: "flex",
    maxHeight: 300,
    overflow: (props: any) => (props.fileListLoading ? "hidden" : "auto"),
    background: "var(--theia-input-background)",
    color: "var(--theia-input-foreground)",
    padding: 16,
    borderRadius: 6,
  },
  header: {
    display: "flex",
    flexDirection: "column",
    width: "100%",
  },
  selectedPathContainer: {
    display: "flex",
    marginTop: 16,
    alignItems: "center",
  },
  selectedPath: {
    flex: 1,
    marginLeft: 16,
    background: "var(--theia-input-background)",
    color: "var(--theia-input-foreground)",
    height: 24,
    borderRadius: 12,
    padding: "4px 24px",
    display: "flex",
    alignItems: "center",
    fontSize: 12,
  },
  predefinedPath: {
    opacity: "40%",
  },
  fileRow: {
    cursor: "pointer",
    lineHeight: "32px",
    "&:hover": {
      textDecoration: "underline",
    },
  },
  fileRowSelected: {
    composes: "$fileRow",
    background: "var(--theia-selection-background)",
  },
  loadingContainer: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  fileActionsContainer: {
    marginBottom: 16,
    display: "flex",
  },
  homeButton: {
    marginLeft: 16,
    "&:hover": {
      textDecoration: "underline",
    },
    cursor: "pointer",
  },
});
type Props = {
  isOpen: boolean;
  onClose: Function;
  onClickConfirm: (selectedPath: string, selectedFile: string) => void;
  canSelectFiles: boolean;
};
const RemotePathSelectorModal = (props: Props) => {
  const { isOpen: isOpenProp, onClose, onClickConfirm, canSelectFiles } = props;
  const selectedRemoteName = localStorage.getItem(
    LocalStorageKey.SELECTED_REMOTE
  );
  const selectedBucket = localStorage.getItem(LocalStorageKey.SELECTED_BUCKET);
  const [isOpen, setIsOpen] = useState(isOpenProp);
  const predefinedPath = `${selectedRemoteName}:${selectedBucket}`;
  const [selectedPath, setSelectedPath] = useState("");
  const [fileListLoading, setFileListLoading] = useState(false);
  const [selectedFile, setSelectedFile] = useState<string>("");
  const [fileList, setFileList] = useState<IRCloneFile[]>([]);
  const classes = useStyles({ fileListLoading });
  const commonClasses = useCommonStyles();

  useEffect(() => {
    setIsOpen(isOpenProp);
  }, [isOpenProp]);
  useEffect(() => {
    if (isOpen && !selectedFile) {
      getFileList();
    }
  }, [selectedPath, isOpen, selectedFile]);
  function closeModal() {
    setIsOpen(false);
    onClose();
  }
  function handleClickConfirm() {
    onClickConfirm(`${predefinedPath}/${selectedPath}`, selectedFile);
    closeModal();
  }
  const getFileList = async () => {
    setFileListLoading(true);
    try {
      const options: RequestInit = {
        body: JSON.stringify({ fs: predefinedPath, remote: selectedPath }),
      };
      const res = await fetchRClone(RCloneEndPoints.getFilesList, options);
      const json = await res.json();
      setFileList(json.list);
    } catch (error) {
      console.error(error);
    } finally {
      setFileListLoading(false);
    }
  };
  const handleClickPath = (file: IRCloneFile) => {
    if (!file.IsDir && !canSelectFiles) {
      return;
    }
    setSelectedPath(file.Path);
    if (!file.IsDir) {
      setSelectedFile(file.Name);
    } else {
      setSelectedFile("");
    }
  };
  const handleClickHome = () => {
    setSelectedPath("");
    setSelectedFile("");
  };
  const handleClickBack = () => {
    if (!selectedPath) {
      return;
    }
    const pathArr = selectedPath.split("/");
    pathArr.pop();
    if (selectedFile) {
      pathArr.pop();
    }
    setSelectedPath(pathArr.join("/"));
    setSelectedFile("");
  };
  return (
    <Modal
      isOpen={isOpen}
      onRequestClose={closeModal}
      className={commonClasses.modal}
      overlayClassName={commonClasses.overlay}
    >
      <div className={classes.contentContainer}>
        <div className={classes.header}>
          <h3>SELECT A DIRECTORY TO SYNC</h3>
          <div className={classes.selectedPathContainer}>
            <h4>Current Path</h4>
            <div className={classes.selectedPath}>
              <span
                className={classes.predefinedPath}
              >{`${predefinedPath}/`}</span>
              <span>{selectedPath}</span>
            </div>
          </div>
        </div>
        <div className={classes.fileActionsContainer}>
          <BackButton
            onClick={handleClickBack}
            disabled={!selectedPath}
            hideHomeIcon
          />
          <i
            onClick={handleClickHome}
            className={`fa fa-home ${classes.homeButton}`}
          />
        </div>

        <div className={classes.innerContent}>
          <table className={commonClasses.table}>
            <tr>
              <th>Name</th>
              <th>Modified</th>
            </tr>
            {fileListLoading ? (
              <div className={classes.loadingContainer}>
                <i className="fa fa-spinner fa-spin fa-2x" />
              </div>
            ) : fileList.length === 0 ? (
              <div className={classes.loadingContainer}>
                <p>This directory is empty.</p>
              </div>
            ) : (
              fileList.map((file, index) => {
                return (
                  <tr
                    key={index}
                    className={
                      file.Name === selectedFile
                        ? classes.fileRowSelected
                        : classes.fileRow
                    }
                    onClick={() => handleClickPath(file)}
                  >
                    <td>
                      <i
                        className={file.IsDir ? "fa fa-folder" : "fa fa-file"}
                      />
                      {file.Name}
                    </td>
                    <td>
                      {new Intl.DateTimeFormat("en").format(
                        new Date(file.ModTime)
                      )}
                    </td>
                  </tr>
                );
              })
            )}
          </table>
        </div>
        <div className={classes.actionsContainer}>
          <button
            type="button"
            onClick={closeModal}
            style={{ marginRight: 16 }}
            className={`theia-button secondary ${commonClasses.button}`}
          >
            CANCEL
          </button>
          <button
            type="button"
            onClick={handleClickConfirm}
            className={`theia-button primary ${commonClasses.button}`}
          >
            CHOOSE PATH
          </button>
        </div>
      </div>
    </Modal>
  );
};

export default RemotePathSelectorModal;
