import React, { memo, 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,
  Skeleton,
} 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, 25424 characters]"

  const defaultLandscapeImage = 
  "data:image/png;base64,[encoded data, 17844 characters]";

const PartnerHeader = (props) => {
  const {
    userdata,
    globalUrl,
    isPublishing,
    isCloud,
    partnerData,
    setPartnerData,
    loadingPartnerData
  } = props;

  const classes = useStyles();

  var upload = "";
  var landScapeUpload = "";

  const { themeMode } = useContext(Context)
  const {theme} = getTheme(themeMode)
  const [isDisabled, setIsDisabled] = useState(isCloud ? userdata?.active_org?.is_partner ? false : true : true);
  const [file, setFile] = React.useState("");
  const [landscapeFile, setLandscapeFile] = React.useState("");
  const [fileBase64, setFileBase64] = React.useState(
    partnerData.image_url
  );
  const [landscapeFileBase64, setLandscapeFileBase64] = React.useState(
    partnerData.landscape_image_url
  );

  useEffect(() => {
    setIsDisabled(isCloud ? userdata?.active_org?.is_partner ? false : true : true);
    if(userdata?.support){
      setIsDisabled(false);
    }
  }, [isCloud, userdata]);
  useEffect(() => {
    if (partnerData.image_url !== undefined && partnerData.image_url !== null && partnerData.image_url.length > 0) {
      setFileBase64(partnerData.image_url);
      setFile(partnerData.image_url);
    }
    if (partnerData.landscape_image_url !== undefined && partnerData.landscape_image_url !== null && partnerData.landscape_image_url.length > 0) {
      setLandscapeFileBase64(partnerData.landscape_image_url);
      setLandscapeFile(partnerData.landscape_image_url);
    }
  }, [partnerData]);

  useEffect(() => {
    if(partnerData?.image_url === undefined) {
      setPartnerData({
        ...partnerData,
        image_url: defaultImage,
      })
    } 
    if(partnerData?.landscape_image_url === undefined) {
      setPartnerData({
        ...partnerData,
        landscape_image_url: defaultLandscapeImage,
      })
    }
  }, []);

  const removeImage = () => {
    setFile("");
    setFileBase64("");
    setCroppedData(defaultImage);
    setPartnerData({
      ...partnerData,
      image_url: defaultImage,
    })
  };

  const removeLandscapeImage = () => {
    setLandscapeFile("");
    setLandscapeFileBase64("");
    setLandscapeCroppedData(defaultLandscapeImage);
    setPartnerData({
      ...partnerData,
      landscape_image_url: defaultLandscapeImage,
    })
  }

  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",
  };

  useEffect(() => {
    if (file !== "") {
      const img = document.getElementById("logo");
      if (img) {  // Add check to ensure img exists
        var canvas = document.createElement("canvas");
        canvas.width = 174;
        canvas.height = 174;
        var ctx = canvas.getContext("2d");

        img.onload = function () {
          ctx.drawImage(
            img,
            0,
            0,
            img.width,
            img.height,
            0,
            0,
            canvas.width,
            canvas.height
          );

          const canvasUrl = canvas.toDataURL();
          if (canvasUrl !== fileBase64) {
            setFileBase64(canvasUrl);
            setPartnerData(prevData => ({
              ...prevData,
              image_url: canvasUrl
            }));
          }
        };
      }
    }
  }, [file]); // Add file as dependency

  useEffect(() => {
    if (landscapeFile !== "") {
      const landscapeImg = document.getElementById("landscape_logo");
      if (landscapeImg) {  // Add check to ensure landscapeImg exists
        var landscapeCanvas = document.createElement("canvas");
        landscapeCanvas.width = 350;
        landscapeCanvas.height = 120;
        var landscapeCtx = landscapeCanvas.getContext("2d");
        
        landscapeImg.onload = function () {
          landscapeCtx.drawImage(
            landscapeImg,
            0,
            0,
            landscapeImg.width,
            landscapeImg.height,
            0,
            0,
            landscapeCanvas.width,
            landscapeCanvas.height
          );

          const landscapeCanvasUrl = landscapeCanvas.toDataURL();
          if (landscapeCanvasUrl !== landscapeFileBase64) {
            setLandscapeFileBase64(landscapeCanvasUrl);
            setPartnerData(prevData => ({
              ...prevData,
              landscape_image_url: landscapeCanvasUrl
            }));
          }
        };
      }
    }
  }, [landscapeFile]); // Add landscapeFile as dependency

  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={() =>
            console.log("save")
        }
      >
        <SaveIcon />
      </Button>
    </Tooltip>
  );

  const [imageUploadError, setImageUploadError] = React.useState("");
  const [openImageModal, setOpenImageModal] = React.useState(false);
  const [openLandscapeImageModal, setOpenLandscapeImageModal] = 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(
    partnerData?.image_url || defaultImage
  );
  const [landscapeCroppedData, setLandscapeCroppedData ] = React.useState(
    partnerData?.landscape_image_url || defaultLandscapeImage
  )


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

    if (landscapeFile.length > 0) {
      setLandscapeCroppedData(landscapeFile);
    } else if (landscapeFileBase64 !== undefined && landscapeFileBase64 !== null && landscapeFileBase64.length > 0) {
      setLandscapeCroppedData(landscapeFileBase64);
    } else {
      setLandscapeCroppedData(partnerData?.landscape_image_url || defaultLandscapeImage);
    }

  }, [partnerData, file, landscapeFile]);


  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);
    setOpenLandscapeImageModal(false);
    setImageUploadError("");
  };

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


  const onSaveAppIcon = () => {
        const canvas = editor.getImageScaledToCanvas();
        const newImageData = canvas.toDataURL();
        setCroppedData(newImageData);  // Update croppedData with the new image data
        setOpenImageModal(false);
        setDisableImageUpload(true);
        setPartnerData({
          ...partnerData,
          image_url: newImageData,
        })
  };

  const onSaveLandscapeImage = () => {
    const canvas = landscapeEditor.getImageScaledToCanvas();
    const newImageData = canvas.toDataURL();
    setLandscapeCroppedData(newImageData);
    setOpenLandscapeImageModal(false);
    setDisableImageUpload(true);
    setPartnerData({
      ...partnerData,
      landscape_image_url: newImageData,
    })
  }

  const imageInfo = (
    <img
      src={partnerData?.image_url || defaultImage}
      alt="Click to upload an image (174x174)"
      id="logo"
      disabled={isDisabled}
      style={{
        maxWidth: 174,
        maxHeight: 174,
        minWidth: 174,
        minHeight: 174,
        objectFit: "contain",
        borderRadius: 16,
        cursor: isDisabled ? "not-allowed" : "pointer",
      }}
    />
  );

    const landScapeImageInfo = (
    <img
      src={partnerData?.landscape_image_url || defaultLandscapeImage}
      alt="Click to upload an image (350x120)"
      id="landscape_logo"
      disabled={isDisabled}
      style={{
        maxWidth: 350,
        maxHeight: 120,
        minWidth: 350,
        minHeight: 120,
        objectFit: "contain",
        borderRadius: 16,
        cursor: isDisabled ? "not-allowed" : "pointer",
      }}
    />
  );

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


  const imageUploadModalView = openImageModal && !isDisabled ? (
    <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 Partner 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;

  const imageUploadModalViewLandscape = openLandscapeImageModal && !isDisabled ? (
    <Dialog
      open={openLandscapeImageModal}
      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 Partner Landscape Image</div>
        </DialogTitle>
        {errorText}
        <DialogContent style={{ color: theme?.palette?.textColor }}>
          <AvatarEditor
            ref={setLandscapeEditorRef}
            image={landscapeCroppedData}
            width={350}
            height={120}
            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={() => { 
                  landScapeUpload.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={onSaveLandscapeImage}
            color="primary"
          >
            Upload
          </Button>
        </DialogActions>
      </FormControl>
    </Dialog>
  ) : null;



  if (loadingPartnerData) {
    return (
      <div style={{
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
      }}>
        <div style={{
          backgroundColor: theme?.palette?.loaderColor,
          flex: "1",
          display: "flex",
          flexDirection: "row",
          borderRadius: 16
        }}>
          <div style={{ margin: 10 }}>
            <Skeleton 
              variant="rectangular" 
              width={174} 
              height={174} 
              style={{ borderRadius: 16 }}
              animation="wave"
            />
          </div>
          <div style={{ marginLeft: 16, alignContent: "center" }}>
            <div>
              <Skeleton variant="rectangular" width={128} height={40} style={{ borderRadius: 4 }} animation="wave" />
            </div>
            <div style={{ marginTop: 20 }}>
              <Skeleton variant="rectangular" width={128} height={40} style={{ borderRadius: 4 }} animation="wave" />
            </div>
          </div>
        </div>
        <div style={{
          backgroundColor: theme?.palette?.loaderColor,
          flex: "1",
          display: "flex",
          flexDirection: "row",
          borderRadius: 16
        }}>
          <div style={{ margin: 10 }}>
            <Skeleton 
              variant="rectangular" 
              width={350} 
              height={120} 
              style={{ borderRadius: 16 }}
              animation="wave"
            />
          </div>
          <div style={{ marginLeft: 16, alignContent: "center" }}>
            <div>
              <Skeleton variant="rectangular" width={128} height={40} style={{ borderRadius: 4 }} animation="wave" />
            </div>
            <div style={{ marginTop: 20 }}>
              <Skeleton variant="rectangular" width={128} height={40} style={{ borderRadius: 4 }} animation="wave" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
    style={{
      display: "flex",
      flexDirection: "row",
      alignItems: "center",
      justifyContent: "space-between",
      width: "90%",
    }}
    >
      <div
        style={{
          color: "white",
          display: "flex",
          flexDirection: "row",
          borderRadius: 16
        }}
        disabled={isDisabled}
      >
        <Tooltip title="Click to edit the partner's image (174x174)" placement="bottom">
          <div
            style={{
              margin: 10,
              cursor: "pointer",
              // backgroundColor: inputColor,
              maxWidth: 174,
              maxHeight: 174,
              borderRadius: 16,
            }}
            disabled={isDisabled}
            onClick={() => {
              setOpenImageModal(true);
            }}
          >
            <input
              hidden
              type="file"
              disabled={isDisabled}
              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="outlined"
              color="primary"
              disabled={isDisabled || isPublishing}
              onClick={() => {
                setOpenImageModal(true);
              }}
            >
              {partnerData?.image_url === 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 }}
              disabled={isDisabled || isPublishing}
              onClick={() => {
                removeImage();
                setOpenImageModal(false);
              }}
            >
              Remove
            </Button>
          </div>
        </div>
      </div>
      <div
        style={{
          color: "white",
          display: "flex",
          flexDirection: "row",
          borderRadius: 16
        }}
      >
        <Tooltip title="Click to edit the partner's landscape image (350x120)" placement="bottom">
          <div
            style={{
              margin: 10,
              cursor: "pointer",
              backgroundColor: inputColor,
              maxWidth: 350,
              maxHeight: 120,
              borderRadius: 16,
              display: "flex",
            }}
            disabled={isDisabled}
            onClick={() => {
              setOpenLandscapeImageModal(true);
            }}
          >
            <input
              hidden
              type="file"
              disabled={isDisabled}
              ref={(ref) => (landScapeUpload = ref)}
              onChange={(e) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                  setLandscapeCroppedData(event.target.result);
                };
                reader.readAsDataURL(e.target.files[0]);
              }}
            />
            {landScapeImageInfo}
          </div>
          {imageUploadModalViewLandscape}
        </Tooltip>
        <div style={{ marginLeft: 16, alignContent: "center" }}>
          <div >
            <Button
              style={{ fontSize: 16, textTransform: 'capitalize',  boxShadow: "none", borderRadius: 4, width: 128, height: 40 }}
              variant="outlined"
              color="primary"
              disabled={isDisabled || isPublishing}
              onClick={() => {
                setOpenLandscapeImageModal(true);
              }}
            >
              {partnerData?.landscape_image_url === 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 }}
              disabled={isDisabled || isPublishing}
              onClick={() => {
                removeLandscapeImage();
                setOpenLandscapeImageModal(false);
              }}
            >
              Remove
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PartnerHeader;
