import {
  useEffect,
  useState,
  useRef
} from "react";

// material-ui
import {
  Button,
  Stack,
  Typography,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  FormLabel,
  Autocomplete,
  TextField,
  Grid,
} from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton';

import * as ComboData from "utils/ComboData";
import { useFormik, FormikProvider } from 'formik';
import * as yup from 'yup';

const StatusChangeDialog = (props) => {
  const [content, setContent] = useState();
  const [dialogTitle, setDialogTitle] = useState("Confirm");
  const [prositiveBtnText, setPrositiveBtnText] = useState("Confirm");
  const [remarks, setRemarks] = useState("");
  const [helperText, setHelperText] = useState("");
  const [comboInputValue, setComboInputValue] = useState({});
  const [positiveSubmitting, setPositiveSubmitting] = useState(false);
  const positiveOnceRef = useRef(false);
  const groupTitleComboList = ComboData.groupTitle;

  const confirmLoading = Boolean(props.confirmLoading) || positiveSubmitting;
  const gazetteGroupMissing =
    props.getStatus === "genGazetteCode" &&
    Object.keys(props.selectedGazetteGroup ?? {}).length === 0;

  useEffect(() => {
    setComboInputValue({});
    if (props.getStatus == "genGazetteCode") {
      setDialogTitle("Gen Gazette Code");
      setPrositiveBtnText("Submit");
      return getGazetteCodeContent()
    } else if (props.getStatus == "notAccepted") {
      setDialogTitle("Not Accept Reason");
      setPrositiveBtnText("Mark Not Accept");
      return getNotAcceptedContent();
    }if (props.getStatus == "resubmit") {
      setDialogTitle("Re-Submit Reason");
      setPrositiveBtnText("Mark Re-Submit");
      return getNotAcceptedContent();
    }if (props.getStatus == "paid") {
      setDialogTitle("Action Confirm");
      setPrositiveBtnText("Confirm");
      return getConfirmContent("Are you sure to mark this application as paid?");
    } else {
      setDialogTitle("Action Confirm");
      setPrositiveBtnText("Confirm");
      let str = "Do you want to set the application status to '" + props.getStatus + "'?"
      return getConfirmContent(str);
    }
  }, [props.getStatus]);

  useEffect(() => {
    if (!props.open) {
      positiveOnceRef.current = false;
      setPositiveSubmitting(false);
    }
  }, [props.open]);

  const wasConfirmLoadingRef = useRef(false);
  useEffect(() => {
    if (wasConfirmLoadingRef.current && !props.confirmLoading) {
      positiveOnceRef.current = false;
      setPositiveSubmitting(false);
    }
    wasConfirmLoadingRef.current = Boolean(props.confirmLoading);
  }, [props.confirmLoading]);

  const acceptedHandle = () => () => {
    if (confirmLoading) return;
    if (positiveOnceRef.current) return;

    const statusKey = props.getStatus;

    if (statusKey === "notAccepted" || statusKey === "resubmit") {
      if (!remarks || remarks === "") {
        setHelperText("Please enter reason");
        return;
      }
      setHelperText("");
      props.setReason({ "reason": remarks });
    }

    positiveOnceRef.current = true;
    setPositiveSubmitting(true);
    props.setStatusWindowAccepted(true);
  };


  const formik = useFormik({
    initialValues: ({
      username: '',
    }),
    validationSchema: yup.object().shape({
    }),
  });


  const getConfirmContent = (text) => {
    setContent(<Grid container direction="row" justifyContent="center" alignItems="center">
      <FormLabel sx={{ fontSize: "20px", color: "#000000", textAlign: "center" }}>
        <Typography variant="h5">{text}</Typography>
      </FormLabel>
    </Grid>);
  }

  const getNotAcceptedContent = () => {
    setContent(<Grid container direction="row" justifyContent="center" alignItems="center">
      <Grid item xs={12} md={12} lg={12}>

        <TextField
          multiline
          fullWidth
          rows={6}
          placeholder="Please enter reason"
          helperText={helperText}
          onChange={(newValues) => {
            setRemarks(newValues.target.value);
            setHelperText("");
          }}
          variant="outlined"
          InputProps={
            {
              style: { minHeight: '42.5px', maxHeight: '50vh', height: 'auto' },
            }
          }
        />
      </Grid>
    </Grid>
    );
  }

  const getGazetteCodeContent = () => {
    setContent(<Grid container direction="row" justifyContent="center" alignItems="center">
      <Grid item xs={12} md={8} lg={8} sx={{ mb: 1, }}>
        <Grid container alignItems={"center"}>
          <Grid item xs={12} md={2} lg={3}
            sx={{ display: 'flex', alignItems: 'center' }}>
            <Typography variant="h5">Target Issue:</Typography>
          </Grid>
          <Grid item xs={12} md={9} lg={9}>
            <FormLabel>
              <Typography variant="h5">{props.gazetteIssue + ", "}{props.issueNum + ", "}{props.issueDate}</Typography>
            </FormLabel>
          </Grid>
        </Grid>
      </Grid>
      <Grid item xs={12} md={8} lg={8} sx={{ mb: 1, height: "180px" }}>
        <Grid container alignItems={"center"}>
          <Grid item xs={12} md={3} lg={3}
            sx={{ display: 'flex', alignItems: 'center' }}>
            <Typography variant="h5">Gazette Group:</Typography>
          </Grid>
          <Grid item xs={12} md={9} lg={9}>
            <Autocomplete
              disablePortal
              id="gazetteGroup"
              options={groupTitleComboList}
              filterOptions={(options) => options}
              getOptionLabel={(option) => {
                if (option == null) return "";
                if (typeof option === "string") return option;
                return option.label != null ? String(option.label) : "";
              }}
              inputValue={comboInputValue.label}
              onChange={(event, newValue) => {
                if (newValue != null && newValue != {}) {
                  // console.log(comboInputValue)
                  props.setSelectedGazetteGroupInputType(newValue.label);
                  setComboInputValue(newValue);
                  props.setSelectedGazetteGroup(newValue);
                  formik.setFieldValue("", "")
                } else {
                  props.setSelectedGazetteGroupInputType("");
                }
              }}
              sx={{
                  '& .MuiInputBase-root': { alignItems: 'center' },
                  '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                  '& .MuiOutlinedInput-root': { height: 40 }
              }}
              renderInput={(params) => <TextField {...params} placeholder="" />}
            />
          </Grid>
        </Grid>
      </Grid>
    </Grid>
    );
  }

  return (
    <Dialog
      open={props.open}
      onClose={() => {
        if (confirmLoading) return;
        props.handleClose();
      }}
      fullWidth={true}
      maxWidth={'md'}
    >
      <DialogTitle >
        <Grid container>
          <Grid item>
            <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
              <Typography variant="h4">
                {dialogTitle}
              </Typography>
            </Stack>
          </Grid>
        </Grid>
      </DialogTitle>
      <FormikProvider value={formik}>
        <form>
          <DialogContent>
            <DialogContentText component="div">
              {content}
            </DialogContentText>
          </DialogContent>
        </form>
      </FormikProvider>
      <Stack direction="row" justifyContent="space-around">
        <DialogActions>
          <Button variant="contained" onClick={props.handleClose} autoFocus disabled={confirmLoading}>
            <Typography variant="h5">
              Cancel
            </Typography>
          </Button>
        </DialogActions>
        <DialogActions>
          <LoadingButton
            variant="contained"
            color="success"
            onClick={acceptedHandle()}
            loading={confirmLoading}
            disabled={gazetteGroupMissing}
          >
            <Typography variant="h5" component="span">
              {prositiveBtnText}
            </Typography>
          </LoadingButton>
        </DialogActions>
      </Stack>
    </Dialog>
  );
};

export default StatusChangeDialog;
