import * as React from "react";
import Box from "@mui/material/Box";
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import { inputProps } from "../interface/inputfieldProps";
import {
  JsonFormsDispatch,
  useJsonForms,
  withJsonFormsControlProps,
} from "@jsonforms/react";
import { useContext } from "react";
import { DataContext } from "../context/Context";
import RadioButtonCheckedIcon from "@mui/icons-material/RadioButtonChecked";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import PendingIcon from "@mui/icons-material/Pending";
import _ from "lodash";
import { StepContent, Tooltip } from "@mui/material";
import ComponentWrapper from "../common/ComponentWrapper";
import { getComponentProps } from "../common/getComponentProps";
import { getFieldName } from "../permissions/getFieldName";
const ImpaktAppsStepper = React.memo(function (props: inputProps) {
  const {
    data,
    enabled,
    uischema,
    path,
    schema,
    rootSchema,
    renderers,
    cells,
  } = props;
  const uischemaData = uischema?.config?.main;
  const [labels, setLabels] = React.useState(data?.steps || uischemaData.steps);
  const [activeStep, setActiveStep] = React.useState(0);
  const [allowedStep, setallowedStep] = React.useState([]);
  React.useEffect(() => {
    if (data) {
      setActiveStep(data.active);
      setLabels(data.steps);
    }
  }, [data]);
  const handleNext = () => {
    setActiveStep((pre) => pre + 1);
  };
  const handleBack = () => {
    setActiveStep((pre) => pre - 1);
  };
  const handleReset = () => {
    setActiveStep(0);
  };
  const ctx = useJsonForms();
  const { theme, pageName, permissions, serviceProvider, setFormdata } =
    useContext(DataContext);

  const stepperHandler = (buttonType: string) => {
    serviceProvider(
      ctx,
      {
        ...uischemaData,
        [buttonType]: buttonType,
        onClick: buttonType,
      },
      {
        event: { _reactName: buttonType },
        path,
        ...uischemaData.additionalData,
        paramValue: {
          buttonType,
          handleNext,
          handleBack,
          handleReset,
        },
      }
    );
  };
  function ColorlibStepIcon(props) {
    const { active, completed } = props;
    const icons = {
      1: (
        <Tooltip title="Task Successfully Done">
          <CheckCircleIcon sx={{ fontSize: 32 }} color="success" />
        </Tooltip>
      ),
      2: (
        <Tooltip title="Current Task">
          <RadioButtonCheckedIcon sx={{ fontSize: 32 }} color="info" />
        </Tooltip>
      ),
      3: (
        <Tooltip title="Task Pending">
          <PendingIcon sx={{ fontSize: 32 }} color="error" />
        </Tooltip>
      ),
    };
    return (
      <>
        {active && icons[2]}
        {completed && icons[1]}
        {!active && !completed && icons[3]}
      </>
    );
  }
  const stepContentWithDispatch: React.FC = () => {
    const scopeArray: string[] =
      uischema.elements[allowedStep[activeStep]]?.scope?.split("/");
    const actualElemPath: string =
      scopeArray?.[scopeArray?.length - 1] || undefined;
    const widget = _.cloneDeep(uischema.elements[allowedStep[activeStep]]);
    if (activeStep !== labels.length) {
      widget.config.main.additionalData = {
        ...widget?.config?.main?.additionalData,
        tableButtonPath: actualElemPath,
      };
    }
    return (
      <div>
        <JsonFormsDispatch
          schema={schema}
          uischema={{ ...widget }}
          path={actualElemPath}
          key={actualElemPath}
          renderers={renderers}
          enabled={enabled}
          cells={cells}
        />
        <Box sx={{ mb: 2 }}>
          {uischemaData.defaultButtonAvailable && (
            <div>
              <Button
                color="inherit"
                disabled={activeStep === 0}
                onClick={() => stepperHandler(uischemaData?.onBack || "onBack")}
                sx={{ mr: 1 }}
              >
                Back
              </Button>
              <Button
                onClick={() => stepperHandler(uischemaData?.onNext || "onNext")}
                color="inherit"
              >
                {activeStep === labels.length - 1 ? "Finish" : "Next"}
              </Button>
            </div>
          )}
        </Box>
      </div>
    );
  };
  const RenderCompletionContent = () => (
    <Box component={"div"}>
      {uischemaData?.completeText ? (
        <Typography sx={{ mt: 2, mb: 1 }}>
          {uischemaData.completeText}
        </Typography>
      ) : (
        <Typography sx={{ mt: 2, mb: 1 }}>
          All steps completed - you are finished
        </Typography>
      )}
      {uischemaData?.resetButton && (
        <Button
          color="inherit"
          onClick={() => stepperHandler(uischemaData?.onReset || "onReset")}
        >
          {uischemaData?.resetText ? uischemaData.resetText : "Reset"}
        </Button>
      )}
    </Box>
  );
  const fieldName = getFieldName(path);
  return (
    <ComponentWrapper
      {...getComponentProps(
        `${pageName}:${fieldName}`,
        permissions,
        schema,
        rootSchema
      )}
    >
      <Box sx={{ width: "100%" }}>
        <Stepper
          activeStep={activeStep}
          orientation={uischemaData?.orientation || "horizontal"}
        >
          {labels.map((item, index) => {
            const labelId = item?.id || index;
            allowedStep[index] = labelId;
            const label = item.label;
            const stepProps: { completed?: boolean } = {};
            return (
              <Step key={label} {...stepProps}>
                <StepLabel StepIconComponent={ColorlibStepIcon}>
                  {label}
                </StepLabel>
                {uischemaData.orientation === "vertical" && (
                  <StepContent>{stepContentWithDispatch(0)}</StepContent>
                )}
              </Step>
            );
          })}
        </Stepper>
        {activeStep === labels.length ? (
          <RenderCompletionContent />
        ) : (
          <>
            {uischemaData.orientation !== "vertical" && (
              <React.Fragment>{stepContentWithDispatch(0)}</React.Fragment>
            )}
          </>
        )}
      </Box>
    </ComponentWrapper>
  );
});
export default withJsonFormsControlProps(ImpaktAppsStepper);
