import React, { useEffect, useState, useContext } from "react";
import {getTheme} from "../theme.jsx";
import { makeStyles } from "@mui/styles";
import { toast } from 'react-toastify';
import { Context } from "../context/ContextApi.jsx";
import {
  Tooltip,
  TextField,
  FormControl,
  InputLabel,
  OutlinedInput,
  Checkbox,
  Select,
  MenuItem,
  Button,
  ListItemText,
  Dialog,
  DialogActions,
  DialogContent,
  Divider,
  DialogTitle,
} from "@mui/material";

import AvatarEditor from "react-avatar-editor";


import {
  AddAPhotoOutlined as AddAPhotoOutlinedIcon,
  ZoomInOutlined as ZoomInOutlinedIcon,
  ZoomOutOutlined as ZoomOutOutlinedIcon,
  Loop as LoopIcon,
  AddPhotoAlternate as AddPhotoAlternateIcon,
} from "@mui/icons-material";

import {
  ExpandLess as ExpandLessIcon,
  ExpandMore as ExpandMoreIcon,
  Save as SaveIcon,
} from "@mui/icons-material";

const useStyles = makeStyles({
  notchedOutline: {
    borderColor: "#f85a3e !important",
  },
});

const defaultImage =
  "data:image/png;base64,[encoded data, 21916 characters]";

const OrgHeader = (props) => {
  const {
    userdata,
    selectedOrganization,
    setSelectedOrganization,
    globalUrl,
    isCloud,
    adminTab,
    handleEditOrg,
    isEditOrgTab,
    serverside,
  } = props;

  const classes = useStyles();

  var upload = "";
  const defaultBranch = "master";
  const [orgName, setOrgName] = React.useState(selectedOrganization.name);
  const [orgDescription, setOrgDescription] = React.useState(
    selectedOrganization.description
  );

  const { themeMode } = useContext(Context)
  const {theme} = getTheme(themeMode)

  const [file, setFile] = React.useState("");
  const [fileBase64, setFileBase64] = React.useState(
    selectedOrganization.image
  );
  useEffect(() => {
    if (selectedOrganization.image !== undefined && selectedOrganization.image !== null && selectedOrganization.image.length > 0) {
      setFileBase64(selectedOrganization.image);
      setFile(selectedOrganization.image);
    }
  }, [selectedOrganization]);

  const removeImage = () => {
    setFile("");
    setFileBase64("");
    setCroppedData(defaultImage);
    handleEditOrg(
      orgName,
      orgDescription,
      selectedOrganization.id,
      defaultImage,
      {
        app_download_repo: selectedOrganization?.defaults?.app_download_repo,
        app_download_branch: selectedOrganization?.defaults?.app_download_branch,
        workflow_download_repo: selectedOrganization?.defaults?.workflow_download_repo,
        workflow_download_branch: selectedOrganization?.defaults?.workflow_download_branch,
        notification_workflow: selectedOrganization?.defaults?.notification_workflow,
        documentation_reference: selectedOrganization?.defaults?.documentation_reference,
        workflow_upload_repo: selectedOrganization?.defaults?.workflow_upload_repo,
        workflow_upload_branch: selectedOrganization?.defaults?.workflow_upload_branch,
        workflow_upload_username: selectedOrganization?.defaults?.workflow_upload_username,
        workflow_upload_token: selectedOrganization?.defaults?.workflow_upload_token,
        newsletter: selectedOrganization?.defaults?.newsletter,
        weekly_recommendations: selectedOrganization?.defaults?.weekly_recommendations,
      },
      {
        sso_entrypoint: selectedOrganization?.sso_config?.sso_entrypoint,
        sso_certificate: selectedOrganization?.sso_config?.sso_certificate,
        client_id: selectedOrganization?.sso_config?.client_id,
        client_secret: selectedOrganization?.sso_config?.client_secret,
        openid_authorization: selectedOrganization?.sso_config?.openid_authorization,
        openid_token: selectedOrganization?.sso_config?.openid_token,
        SSORequired: selectedOrganization?.sso_config?.SSORequired,
        auto_provision: selectedOrganization?.sso_config?.auto_provision,
      },
      [],
    )
  };

  const surfaceColor = "#27292D";
  const inputColor = "#383B40";

  const bodyDivStyle = {
    margin: "auto",
    width: "900px",
  };

  const appIconStyle = {
    marginLeft: "5px",
  };

  const dividerStyle = {
    marginBottom: "10px",
    marginTop: "10px",
    height: "1px",
    width: "100%",
    backgroundColor: "grey",
  };

  if (file !== "") {
    const img = document.getElementById("logo");
    var canvas = document.createElement("canvas");
    canvas.width = 174;
    canvas.height = 174;
    var ctx = canvas.getContext("2d");

    img.onload = function () {
      // img, x, y, width, height
      //ctx.drawImage(img, 174, 174)
      //console.log("IMG natural: ", img.naturalWidth, img.naturalHeight)
      //ctx.drawImage(img, 0, 0, 174, 174)
      ctx.drawImage(
        img,
        0,
        0,
        img.width,
        img.height,
        0,
        0,
        canvas.width,
        canvas.height
      );

      const canvasUrl = canvas.toDataURL();
      if (canvasUrl !== fileBase64) {
        setFileBase64(canvasUrl);
        selectedOrganization.image = canvasUrl;
        setSelectedOrganization(selectedOrganization);
      }
    };
  }


  var image = "";
  const editHeaderImage = (event) => {
    const file = event.target.value;
    const actualFile = event.target.files[0];
    const fileObject = URL.createObjectURL(actualFile);
    setFile(fileObject);
  };

  //console.log("USER: ", userdata)
  const orgSaveButton = (
    <Tooltip title="Save any unsaved data" placement="bottom">
      <Button
        style={{ width: 150, height: 55, flex: 1 }}
        variant="outlined"
        color="primary"
        disabled={
          userdata === undefined || userdata === null || userdata.admin !== "true"
        }
        onClick={() =>
          handleEditOrg(
            orgName,
            orgDescription,
            selectedOrganization.id,
            selectedOrganization.image,
            {},
            {},
            [],
          )
        }
      >
        <SaveIcon />
      </Button>
    </Tooltip>
  );

  const [imageUploadError, setImageUploadError] = React.useState("");
  const [openImageModal, setOpenImageModal] = React.useState(false);
  const [scale, setScale] = React.useState(1);
  const [rotate, setRotation] = React.useState(0);
  const [disableImageUpload, setDisableImageUpload] = React.useState(true);
  const [croppedData, setCroppedData] = React.useState(defaultImage);
  const [imageData, setImageData] = useState(selectedOrganization?.image?.lenth > 0 ? selectedOrganization?.image : defaultImage)

  React.useEffect(() => {
    if (file.length > 0) {
      setCroppedData(file);
    } else if (fileBase64 !== undefined && fileBase64 !== null && fileBase64.length > 0) {
      setCroppedData(fileBase64);
    } else {
      setCroppedData(defaultImage);
    }

    if((imageData !== selectedOrganization?.image) && selectedOrganization?.image?.length > 0){
      setImageData(selectedOrganization?.image)
    }
  }, [selectedOrganization, file]);


  const alternateImg = (
    <AddPhotoAlternateIcon
      style={{
        maxWidth: 174,
        maxHeight: 174,
        minWidth: 174,
        minHeight: 174,
        flex: "1",
        display: "flex",
        flexDirection: "row",
        margin: "auto",
        marginTop: 30,
        marginLeft: 40,
      }}
      onClick={() => {
        upload.click();
      }}
    />
  );

  const zoomIn = () => {
    setScale(scale + 0.1);
  };

  const zoomOut = () => {
    setScale(scale - 0.1);
  };

  const rotation = () => {
    setRotation(rotate + 10);
  };

  const onPositionChange = () => {
    setDisableImageUpload(false);
  };

  const onCancelSaveAppIcon = () => {
    setOpenImageModal(false);
    setImageUploadError("");
  };

  let editor;
  const setEditorRef = (imgEditor) => {
    editor = imgEditor;
  };


  const onSaveAppIcon = () => {
        const canvas = editor.getImageScaledToCanvas();
        const newImageData = canvas.toDataURL();
        setCroppedData(newImageData);  // Update croppedData with the new image data
        setOpenImageModal(false);
        setDisableImageUpload(true);
        handleEditOrg(
          orgName,
          orgDescription,
          selectedOrganization.id,
          newImageData,
          {
            app_download_repo: selectedOrganization?.defaults?.app_download_repo,
            app_download_branch: selectedOrganization?.defaults?.app_download_branch,
            workflow_download_repo: selectedOrganization?.defaults?.workflow_download_repo,
            workflow_download_branch: selectedOrganization?.defaults?.workflow_download_branch,
            notification_workflow: selectedOrganization?.defaults?.notification_workflow,
            documentation_reference: selectedOrganization?.defaults?.documentation_reference,
            workflow_upload_repo: selectedOrganization?.defaults?.workflow_upload_repo,
            workflow_upload_branch: selectedOrganization?.defaults?.workflow_upload_branch,
            workflow_upload_username: selectedOrganization?.defaults?.workflow_upload_username,
            workflow_upload_token: selectedOrganization?.defaults?.workflow_upload_token,
            newsletter: selectedOrganization?.defaults?.newsletter,
            weekly_recommendations: selectedOrganization?.defaults?.weekly_recommendations,
          },
          {
            sso_entrypoint: selectedOrganization?.sso_config?.sso_entrypoint,
            sso_certificate: selectedOrganization?.sso_config?.sso_certificate,
            client_id: selectedOrganization?.sso_config?.client_id,
            client_secret: selectedOrganization?.sso_config?.client_secret,
            openid_authorization: selectedOrganization?.sso_config?.openid_authorization,
            openid_token: selectedOrganization?.sso_config?.openid_token,
            SSORequired: selectedOrganization?.sso_config?.SSORequired,
            auto_provision: selectedOrganization?.sso_config?.auto_provision,
          },
          [],
        )
  };

  const imageInfo = (
    <img
      src={imageData}
      alt="Click to upload an image (174x174)"
      id="logo"
      style={{
        maxWidth: 174,
        maxHeight: 174,
        minWidth: 174,
        minHeight: 174,
        objectFit: "contain",
        borderRadius: 16,
      }}
    />
  );

  const errorText = imageUploadError.length > 0 ? (
    <div style={{ marginTop: 10 }}>Error: {imageUploadError}</div>
  ) : null;


  const imageUploadModalView = openImageModal ? (
    <Dialog
      open={openImageModal}
      onClose={onCancelSaveAppIcon}
      PaperProps={{
        sx: {
            borderRadius: theme?.palette?.DialogStyle?.borderRadius,
            border: theme?.palette?.DialogStyle?.border,
            minWidth: "300px",
            minHeight: "300px",
            fontFamily: theme?.typography?.fontFamily,
            backgroundColor: theme?.palette?.DialogStyle?.backgroundColor,
            zIndex: 1000,
            '& .MuiDialogContent-root': {
              backgroundColor: theme?.palette?.DialogStyle?.backgroundColor,
            },
            '& .MuiDialogTitle-root': {
              backgroundColor: theme?.palette?.DialogStyle?.backgroundColor,
            },
            '& .MuiDialogActions-root': {
              backgroundColor: theme?.palette?.DialogStyle?.backgroundColor,
            },
        },
    }}
    >
      <FormControl>
        <DialogTitle>
          <div style={{ color: theme?.palette?.textColor}}>Upload Organization Image</div>
        </DialogTitle>
        {errorText}
        <DialogContent style={{ color: theme?.palette?.textColor }}>
          <AvatarEditor
            ref={setEditorRef}
            image={croppedData}
            width={174}
            height={174}
            border={50}
            color={[0, 0, 0, 0.6]} // RGBA
            scale={scale}
            rotate={rotate}
            onImageChange={onPositionChange}
            onLoadSuccess={() => setRotation(0)}
          />
          <Divider style={dividerStyle} />
          <div style={{ display: "flex", justifyContent: "space-between", margin: "10px 0" }}>
            <Tooltip title="New Icon">
              <Button
                variant="outlined"
                component="label"
                style={appIconStyle}
                onClick={() => { upload.click(); }}
              >
                <AddAPhotoOutlinedIcon style={{ color: theme?.palette?.textColor }} />
              </Button>
            </Tooltip>
            <Tooltip title="Zoom In">
              <Button
                variant="outlined"
                component="label"
                style={appIconStyle}
                onClick={zoomIn}
              >
                <ZoomInOutlinedIcon style={{ color: theme?.palette?.textColor }} />
              </Button>
            </Tooltip>
            <Tooltip title="Zoom Out">
              <Button
                variant="outlined"
                component="label"
                style={appIconStyle}
                onClick={zoomOut}
              >
                <ZoomOutOutlinedIcon style={{ color: theme?.palette?.textColor }} />
              </Button>
            </Tooltip>
            <Tooltip title="Rotate">
              <Button
                variant="outlined"
                component="label"
                style={appIconStyle}
                onClick={rotation}
              >
                <LoopIcon style={{ color: theme?.palette?.textColor }} />
              </Button>
            </Tooltip>
          </div>
          <Divider style={dividerStyle} />
        </DialogContent>
        <DialogActions>
          <Button
            style={{ borderRadius: "2px", fontSize: 16, textTransform: "none", color: theme?.palette?.textColor }}
            onClick={onCancelSaveAppIcon}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            style={{ borderRadius: "2px", fontSize: 16, color: "#1a1a1a", backgroundColor: disableImageUpload ? "" : "#ff8544", textTransform: 'none' }}
            disabled={disableImageUpload}
            onClick={onSaveAppIcon}
            color="primary"
          >
            Upload
          </Button>
        </DialogActions>
      </FormControl>
    </Dialog>
  ) : null;


  return (
    <div>
      <div
        style={{
          color: "white",
          flex: "1",
          display: "flex",
          flexDirection: "row",
          borderRadius: 16
        }}
      >
        <Tooltip title="Click to edit the organization's image (174x174)" placement="bottom">
          <div
            style={{
              margin: 10,
              cursor: "pointer",
              // backgroundColor: inputColor,
              maxWidth: 174,
              maxHeight: 174,
              borderRadius: 16,
            }}
            onClick={() => {
              setOpenImageModal(true);
            }}
          >
            <input
              hidden
              type="file"
              ref={(ref) => (upload = ref)}
              onChange={(e) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                  setCroppedData(event.target.result);
                };
                reader.readAsDataURL(e.target.files[0]);
              }}
            />
            {imageInfo}
          </div>
          {imageUploadModalView}
        </Tooltip>
        <div style={{ marginLeft: 16, alignContent: "center" }}>
          <div >
            <Button
              style={{ fontSize: 16, textTransform: 'capitalize',  boxShadow: "none", borderRadius: 4, width: 128, height: 40 }}
              variant="contained"
              color="primary"
              onClick={() => {
                setOpenImageModal(true);
              }}
            >
              {file === null ? "Upload" : "Update"}
            </Button>
          </div>
          <div>
            <Button
              variant="contained"
              color="secondary"
              style={{ fontSize: 16, textTransform: 'capitalize', boxShadow: "none", marginTop: 20, borderRadius: 4, width: 128, height: 40 }}
              onClick={() => removeImage()}
            >
              Remove
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default OrgHeader;
