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

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);

  useEffect(() => {
    // console.log(props.transactionData)
    if(Object.keys(props.transactionData).length > 0){
      setLoadtTransactionData(props.transactionData)
    }
  }, [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 = () => () =>{
      props.setConfirmPayment(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="row" justifyContent="flex-start" alignItems="center">
              <Typography variant="h4">
                {windowTitle}              
              </Typography>
            </Stack>
          </Grid>
        </Grid>
      </DialogTitle>
      <FormikProvider value={formik}>
        <form>
          <DialogContent>
            <DialogContentText>
              <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>
                                              <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="pnspsFormParagraphBold" sx={{ color: "#000000", textAlign: "left" }}>
                                      <FormattedMessage id="payTotal"/>(HK$):&nbsp;
                                    </Typography>
                                </Grid>
                                <Grid item>
                                    <Typography variant="pnspsFormParagraphBold" sx={{color: "#000000", textAlign: "left" }}>
                                        {" HK$ " + FormatUtils.currencyFormat(props.totalAmount)}
                                    </Typography>
                                </Grid>
                            </Grid>
                            {paymentMethod === "" ? 
                              paymentMethod !="" && !onReady ? <LoadingComponent/> : null
                              :
                              !isLimit? 
                                  !onReady? <LoadingComponent/> :
                                    !isLimit? 
                                      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
                                :  
                                !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 >
            <FormattedMessage id="cancel"/>
          </Button>
        </DialogActions>
        <DialogActions>
          <Button variant="contained" color="success" onClick={confirmPaymentHandle()} disabled={paymentMethod === "" || isLimit || isPPSLimit}>
            <FormattedMessage id="confirm"/>
          </Button>
        </DialogActions>
      </Stack>
    </Dialog>
  );
};

export default MultiPaymentWindow;
