import {
  useEffect,
  useState
} from "react";
import * as React from "react";
import {getBowserType} from "auth/utils";

// material-ui
import {
  Button,
  FormLabel,
  Stack,
  Typography,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Grid,
  Box
} from '@mui/material';
import { useFormik, FormikProvider } from 'formik';
import * as yup from 'yup';
import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
import * as FormatUtils from "utils/FormatUtils";

import VisaIcon from "assets/images/icons/visacard.svg";
import MasterIcon from "assets/images/icons/mastercard.svg";
import JcbIcon from "assets/images/icons/jcb.svg";
import UnionPayIcon from "assets/images/icons/unionpay.svg";
import PpsIcon from "assets/images/icons/ppshk.svg";
import FpsIcon from "assets/images/icons/fps.svg";
import {FormattedMessage, useIntl} from "react-intl";
import { PRIMARY_CONTAINED_BUTTON_SX, PAY_CONTAINED_BUTTON_SX } from "themes/colorConst";
import * as HttpUtils from "utils/HttpUtils"
import * as UrlUtils from "utils/ApiPathConst"

const MultiPaymentWindow = (props) => {
  const intl = useIntl();
  const windowTitle = intl.formatMessage({id: 'selectPaymentMethod'});
  // const [content, setContent] = useState();
  const [loadtTransactionData, setLoadtTransactionData] = useState({});
  const [loadAvailableMethodData, setLoadAvailableMethodData] = useState([]);
  const [paymentMethod, setPaymentMethod] = useState("");
  const [isLimit, setIsLimit] = useState(false);
  const [isPPSLimit, setIsPPSLimit] = useState(false);
  const [transactionData, setTransactionData] = useState({});
  const [availableMethodData, setAvailableMethodData] = useState([]);
  const [fpsClass, setFpsClass] = useState("");
  const [visaClass, setVisaClass] = useState("");
  const [mastercardClass, setMastercardClass] = useState("");
  const [jCBClass, setJCBClass] = useState("");
  const [unionPayClass, setUnionPayClass] = useState("");
  const [pPSClass, setPPSlass] = useState("");
  const [filteredPaymentMethod, setFilteredPaymentMethod] = useState([]);
  const [onReady, setOnReady] = useState(false);
  
  const [paymentHoldedErrText, setPaymentHoldedErrText] = React.useState("");
  const [paymentHoldedErr, setPaymentHoldedErr] = React.useState(false);
  
  const mobileBrowser = "Mobile";

  useEffect(() => {
    // console.log(props.transactionData)
    if(Object.keys(props.transactionData).length > 0){
      setLoadtTransactionData(props.transactionData)
      // console.log(props.browserType)
    }
  }, [props.transactionData]);

  useEffect(() => {
    // console.log(props.availableMethods)
    if(props.availableMethods.length > 0){
      setLoadAvailableMethodData(props.availableMethods)
    }
  }, [props.availableMethods]);

  useEffect(() => {
    if(Object.keys(loadtTransactionData).length > 0){
        setTransactionData(loadtTransactionData)
    }
  }, [loadtTransactionData]);
  
  useEffect(() => {
    if(Object.keys(transactionData).length > 0&&props.availableMethods.length > 0){
      setLoadAvailableMethodData(props.availableMethods)
    }
  }, [transactionData]);

  useEffect(() => {
    if(loadAvailableMethodData.length > 0){
        setAvailableMethodData(loadAvailableMethodData)
    }
  }, [loadAvailableMethodData]);

  useEffect(() => {
    if(filteredPaymentMethod!= undefined && filteredPaymentMethod.length>0){
        setOnReady(true)
    } else if(filteredPaymentMethod!= undefined && Object.keys(filteredPaymentMethod).length > 0){
        setOnReady(true)
    }

  }, [filteredPaymentMethod]);

  useEffect(() => {
    const availableMethod = availableMethodData;

    if(props.availableMethods.length > 0){
      const filteringPaymentMethod = availableMethod.filter(obj => {
        if (obj.supportedcard && obj.supportedcard.includes(paymentMethod)) {
          return obj.subtype === "CreditCard";
        }
        return obj.subtype === paymentMethod;
      });

      if (isLimit && filteringPaymentMethod!= undefined && filteringPaymentMethod.length>0){
        if (paymentMethod == "FPS" || paymentMethod == "PPS"){
          filteringPaymentMethod[0].pointstonote = paymentMethod + intl.formatMessage({id: 'paymentLimitPrice1'})
          setFilteredPaymentMethod(filteringPaymentMethod[0]);
        } else if (isLimit) {
          filteringPaymentMethod[0].pointstonote = paymentMethod + intl.formatMessage({id: 'paymentLimitPrice2'})
          setFilteredPaymentMethod(filteringPaymentMethod[0]);
        }
      }
      
      if (!isLimit && filteringPaymentMethod!= undefined && filteringPaymentMethod.length>0){
        setFilteredPaymentMethod(filteringPaymentMethod);
      }
      
      if(isPPSLimit && filteringPaymentMethod!= undefined && filteringPaymentMethod.length>0 && paymentMethod =="PPS"){
        filteringPaymentMethod[0].pointstonote = paymentMethod + intl.formatMessage({id: 'paymentLimitPPS'})
        setFilteredPaymentMethod(filteringPaymentMethod[0]);
      }
  
      setFpsClass(paymentMethod == "FPS" || paymentMethod == "" ? "" : "grayscale")
      setVisaClass(paymentMethod == "Visa" || paymentMethod == "" ? "" : "grayscale")
      setMastercardClass(paymentMethod == "MasterCard" || paymentMethod == "" ? "" : "grayscale")
      setJCBClass(paymentMethod == "JCB" || paymentMethod == "" ? "" : "grayscale")
      setUnionPayClass(paymentMethod == "UnionPay" || paymentMethod == "" ? "" : "grayscale")
      setPPSlass(paymentMethod == "PPS" || paymentMethod == "" ? "" : "grayscale")

    }

  }, [paymentMethod]);
  
  const selectedPaymentMethodHandle = (method) => () =>{
    if (method != paymentMethod){
      resetForm()
      let totalAmount = props.totalAmount;
      // totalAmount = 99999999.99
      // totalAmount = 0.01
      const paymentLimitList = props.paymentLimit
      let limitRecordList;
  
      switch (method) { 
        case "Visa":
        case "JCB":
        case "MasterCard":
          limitRecordList = paymentLimitList.creditCardLimitRecord;
          break;
        case "FPS":
          limitRecordList = paymentLimitList.fpsLimitRecord;
          break;
        case "PPS":
          limitRecordList = paymentLimitList.ppsbLimitRecord;
          break;
        case "UnionPay":
          limitRecordList = paymentLimitList.unionPlayLimitRecord;
          break;
        default:
          break;
      }
  
      if (totalAmount >= limitRecordList.minLimit && totalAmount <= limitRecordList.maxLimit) {
        setIsLimit(false)
      } else {
        setIsLimit(true)
      }
      if (getBowserType() === "PC_Browser"){
        setPaymentMethod(method)
        props.setSelectedPaymentMethod(method);
        setIsPPSLimit(false)
      } else if (getBowserType() !== "PC_Browser" && method !== "PPS"){
        setPaymentMethod(method)
        props.setSelectedPaymentMethod(method);
      } else {
        setPaymentMethod(method)
        setIsPPSLimit(true)
      }

    }

  };

  const confirmPaymentHandle = () => () =>{
      handlePaymentCheck()
  };

  const handlePaymentCheck = () => {
    let appIdList = props.appIds
    // console.log(props.appIds)
    // console.log(appIdList)
    HttpUtils.post({
        url: UrlUtils.PAYMENT_CHECK,
        params: {
            appIds: appIdList
        },
        onSuccess: (responseData) => {
            const latestData = {};

            responseData.forEach(item => {
            const { appId, timeDiff } = item;
            if (latestData[appId] === undefined || timeDiff < latestData[appId].timeDiff) {
                latestData[appId] = item;
            }
            });
            const latestDataObjects = Object.values(latestData);
            
            // const filteredData = latestDataObjects.filter(item => item.timeDiff > 20 || item.status !== "APPR");
            const filteredData = latestDataObjects.filter(item => item.timeDiff > 30 || item.status == "CANC" || item.status == "REJT");

            const filteredAppIds = filteredData.map(item => item.appId);
            
            const appIdsNotInData = appIdList.filter(appId => !latestDataObjects.some(item => item.appId === appId));
            const combinedAppIdsArray = [...appIdsNotInData, ...filteredAppIds];
            
            const readyToPayment = appIdList.every(appId => combinedAppIdsArray.includes(appId));
            if (readyToPayment){
                props.setConfirmPayment(true);
                return;
            }else{
                const appIdsInData = appIdList.filter(appId => !combinedAppIdsArray.some(item => item === appId));
                const HoldingApplication = latestDataObjects.filter(item => appIdsInData.includes(item.appId));
                const resultString = HoldingApplication.map(item => item.appNo).join(' , ');
                setPaymentHoldedErrText(resultString);
                // setPaymentHoldedErrText(intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: record.appNo }));
                setPaymentHoldedErr(true);
            }
        }
    });
  };

  const closeHandle = () => () =>{
    resetForm()
    props.setOpen(false)
  };

  const resetForm = () =>{
    setOnReady(false)
    setPaymentMethod("")
    setFilteredPaymentMethod([])
    setIsLimit(false)
    setIsPPSLimit(false)
  };


  useEffect(() => {
    if(props.selectedPaymentMethod === ""){
      setPaymentMethod("")
    }
  }, [availableMethodData]);

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

  return (
    <Dialog
      open={props.open}
      onClose={() => props.setOpen(false)}
      fullWidth={true}
      maxWidth={'xl'}
      fullScreen={props.isFullScreen}
    >
      <DialogTitle >
        <Grid container>
          <Grid item>
            <Stack direction="column" justifyContent="flex-start" alignItems="center">
              <Typography variant="h4">
                {windowTitle}              
              </Typography>
            </Stack>
          </Grid>
        </Grid>
      </DialogTitle>
      <FormikProvider value={formik}>
        <form>
          <DialogContent>
            <DialogContentText>
              <FormLabel sx={{ fontSize: "20px", color: "#000000", textAlign: "left", width: "100%", whiteSpace: "pre-line", paddingLeft: 0 }}>
                <FormattedMessage id="paymentProcessLimited"/>
              </FormLabel>
              <Grid item xs={12} md={12} sx={{ pt: 2 }} style={{ height: '100%' }} width="100%">
                <Box xs={12} md={12} sx={{ p: 4, border: '3px solid #eee', borderRadius: '10px' }} >
                  <Grid container justifyContent="flex-start" alignItems="left" >
                    <center>
                        <Grid item xs={12} md={12} width="100%">
                              <Typography variant="h5" sx={{ textAlign: "left" }}>
                                <FormattedMessage id="transactionRefNo"/>: {transactionData.transactionid}
                              </Typography>

                              {/* <Typography variant="h5" sx={{ textAlign: "left" }}>
                                  付款金額: HK$ {FormatUtils.currencyFormat(props.totalAmount)}
                              </Typography> */}
                              {!props.onReady ?
                                  <LoadingComponent />
                                  :availableMethodData.length>0?
                                    <Grid container spacing={2} direction="column" justifyContent="space-between" alignItems="flex-start">
                                      <Grid item xs={12} md={12}>
                                        <Grid container spacing={1} direction="row" justifyContent="flex-start" alignItems="center">
                                          <Grid item>
                                              <Typography variant="h5" sx={{ textAlign: "left" }}>
                                                <FormattedMessage id="selectPaymentMethod"/>:
                                              </Typography>
                                          </Grid>
                                          <Grid item sx={{display: { sm: 'block', md: 'none' }}}></Grid>
                                          <Grid item>
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("FPS")} disabled={props.fpsStatus.active === "N"}>
                                                  <img className={fpsClass} src={FpsIcon} width="80" height="80" alt="FPS"></img>
                                              </Button>
                                          </Grid>
                                          <Grid item>
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("Visa")} disabled={props.creditCardStatus.active === "N"}>
                                                  <img className={visaClass} src={VisaIcon} width="80" height="80" alt="Visa"></img>
                                              </Button>
                                          </Grid>
                                          <Grid item>
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("MasterCard")} disabled={props.creditCardStatus.active === "N"}>
                                                  <img className={mastercardClass} src={MasterIcon} width="80" height="80" alt="MasterCard"></img>
                                              </Button>
                                          </Grid>
                                          <Grid item>
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("UnionPay")} disabled={props.unionPayStatus.active === "N"}>
                                                  <img className={unionPayClass} src={UnionPayIcon} width="80" height="80" alt="UnionPay"></img>
                                              </Button>
                                          </Grid>
                                          <Grid item>
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("JCB")} disabled={props.unionPayStatus.active === "N"}>
                                                  <img className={jCBClass} src={JcbIcon} width="80" height="80" alt="JCB"></img>
                                              </Button>
                                          </Grid>
                                          <Grid item>
                                            {props.browserType==mobileBrowser?
                                              null
                                            :
                                              <Button variant="contained" color="white" onClick={selectedPaymentMethodHandle("PPS")} disabled={props.ppsStatus.active === "N"}>
                                                  <img className={pPSClass} src={PpsIcon} width="80" height="80" alt="PPS"></img>
                                              </Button>
                                            }
                                          </Grid>
                                        </Grid>
                                      </Grid>
                                      {paymentMethod !=""?
                                        <Grid item xs={12} md={12}>
                                          <Grid container direction="row" justifyContent="flex-start" alignItems="center">
                                            <Grid item>
                                              <FormLabel sx={{ fontSize: "20px", color: "#000000", textAlign: "center" }}>
                                                <FormattedMessage id="selectedPaymentMethod"/>:&nbsp;
                                              </FormLabel>
                                            </Grid>
                                            <Grid item>
                                              <FormLabel sx={{ fontSize: "20px", color: "#000000", textAlign: "center" }}>
                                                {paymentMethod}
                                              </FormLabel>
                                            </Grid>
                                          </Grid>
                                        </Grid>
                                      : null}
                                    </Grid>:
                                    <Grid container direction="row" justifyContent="center" alignItems="center">
                                      <FormLabel sx={{ fontSize: "20px", color: "#000000", textAlign: "center"}}>
                                        <FormattedMessage id="paymentMethodNotAvailable"/>
                                      </FormLabel>
                                    </Grid>
                              }
                        </Grid>
                        <Grid item xs={12} md={12}>
                            <Grid container >
                                <Grid item>
                                    <Typography variant="h5" sx={{ color: "#000000", textAlign: "left" }}>
                                      <FormattedMessage id="payTotal"/>&nbsp;($):&nbsp;
                                    </Typography>
                                </Grid>
                                <Grid item>
                                    <Typography variant="h5" sx={{color: "#000000", textAlign: "left" }}>
                                        {" HK$ " + FormatUtils.currencyFormat(props.totalAmount)}
                                    </Typography>
                                </Grid>
                            </Grid>
                            {paymentMethod === "" ? 
                              paymentMethod !="" && !onReady ? <LoadingComponent/> : null
                              :
                              !isLimit? 
                                  !onReady? <LoadingComponent/> :
                                    !isLimit?
                                      filteredPaymentMethod.length>0?
                                        filteredPaymentMethod.map((availableMethod) => {
                                          return (
                                              <Grid container key={availableMethod.subtype} className={"css-1tx0bae"} sx={{ mt: 1, p:2 }}>
                                                { 
                                                  availableMethod.pointstonote.map((pointstonote) => {
                                                    return (
                                                      <Grid container key={pointstonote.order} sx={{ p:0.5 }} direction="row" justifyContent="flex-start" alignItems="center">
                                                        <Grid item>
                                                          <Typography sx={{fontSize: "16px", color: "#000000", textAlign: "left" }}>
                                                          {pointstonote.content}
                                                          </Typography> 
                                                        </Grid>
                                                      </Grid>
                                                    );
                                                  })
                                                }
                                              </Grid>
                                          );
                                        })
                                      : null
                                    : null
                                :  
                                !onReady? <LoadingComponent/> :
                                  <Grid container className={"css-1tx0bae"} sx={{ mt: 1, p:2 }}>
                                    <Grid container sx={{ p:0.5 }} direction="row" justifyContent="flex-start" alignItems="center">
                                      <Grid item>
                                        <Typography color="error" sx={{fontSize: "16px", textAlign: "left" }}>
                                        {filteredPaymentMethod.pointstonote}
                                        </Typography> 
                                      </Grid>
                                    </Grid>
                                  </Grid>
                            }
                        </Grid>
                    </center>
                  </Grid>
                </Box>
              </Grid>
            </DialogContentText>
          </DialogContent>
        </form>
      </FormikProvider>
      <Stack direction="row" justifyContent="space-around">
        <DialogActions>
          <Button variant="contained" onClick={closeHandle()} autoFocus sx={PRIMARY_CONTAINED_BUTTON_SX}>
            <FormattedMessage id="cancel"/>
          </Button>
        </DialogActions>
        <DialogActions>
          {
            props.onPayment? 
              <LoadingComponent disableText={true} alignItems="flex-start"/> 
            :
            <Button variant="contained" onClick={confirmPaymentHandle()} disabled={paymentMethod === "" || isLimit || isPPSLimit} sx={PAY_CONTAINED_BUTTON_SX}>
              <FormattedMessage id="pay"/>
            </Button>
          }
        </DialogActions>
      </Stack>
      <div>
          <Dialog
              open={paymentHoldedErr}
              onClose={() => setPaymentHoldedErr(false)}
              PaperProps={{
                  sx: {
                      minWidth: '40vw',
                      maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                      maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                  }
              }}
          >
              <DialogTitle></DialogTitle>
              <Typography variant="h4" style={{ paddingLeft: '24px' }}><FormattedMessage id="MSG.actionFail" /></Typography>
              <DialogContent style={{ display: 'flex', }}>
                  <Stack direction="column" justifyContent="space-between">
                      <div dangerouslySetInnerHTML={{ __html: intl.formatMessage({ id: 'MSG.paymentHolded' }, { appNo: paymentHoldedErrText }) }} />
                  </Stack>
              </DialogContent>
              <DialogActions>
                  <Button onClick={() => setPaymentHoldedErr(false)} aria-label={intl.formatMessage({ id: 'close' })}>
                      <Typography variant="h5">
                          <FormattedMessage id="close" />
                      </Typography></Button>
              </DialogActions>
          </Dialog>
      </div>
    </Dialog>
  );
};

export default MultiPaymentWindow;
