import React, { useState, useEffect } from "react";
import Button from '@mui/material/Button';
import img_visa_mastercard from "./../mysy_img/visa_mastercard.png"
import img_logo_stripe from  "./../mysy_img/logo-stripe-secure.png";
import img_paypal from "./../mysy_img/paypal.png"
import axios from "axios";
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { useHistory } from "react-router-dom";
import { getCookie } from 'react-use-cookie';
import InputAdornment from '@mui/material/InputAdornment';
import IconButton from '@mui/material/IconButton';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';

function PaymentMethodeNoConnect(props) {
    const [menu, setmenu] = useState("cb");
    const [myApiResponse, setmyApiResponse] = useState("");
    const [result, setResult] = useState("");

    const [paymentadded, setpaymentadded] = useState("");


    function menu_sepa() {
        setmenu("sepa");
    }

    function menu_cb() {
        setmenu("cb");
    }

    function handleChange1(prop) {
        return (event) => {
            setValuesPass1({ ...valuesPass1, [prop]: event.target.value });
        };
    }

    function handleChange2(prop) {
        return (event) => {
            setValuesPass2({ ...valuesPass2, [prop]: event.target.value });
        };
    }
    const [currentpawdvisible, setcurrentpawdvisible] = useState(false);
    const [currentpawdvisible2, setcurrentpawdvisible2] = useState(false);

    const handleClickShowPassword_current_pwd = () => {
        var filtre2_value = document.getElementsByName("pwd")[0].value;

        if (currentpawdvisible == false) {
            document.getElementsByName("pwd")[0].type = "text";
            setcurrentpawdvisible(true);
        }
        else if (currentpawdvisible == true) {
            document.getElementsByName("pwd")[0].type = "password";
            setcurrentpawdvisible(false);
        }

    };

    const handleClickShowPassword_current_pwd2 = () => {
        var filtre2_value = document.getElementsByName("secret")[0].value;

        if (currentpawdvisible2 == false) {
            document.getElementsByName("secret")[0].type = "text";
            setcurrentpawdvisible2(true);
        }
        else if (currentpawdvisible2 == true) {
            document.getElementsByName("secret")[0].type = "password";
            setcurrentpawdvisible2(false);
        }

    };


    const [values, setValues] = React.useState({
        password: '',
        showPassword: false,
    });



    const [valuesPass1, setValuesPass1] = React.useState({
        password1: '',
        showPassword1: false,
    });

    const [valuesPass2, setValuesPass2] = React.useState({
        password2: '',
        showPassword2: false,
    });


    // recuperation et gestion  du token utilisateur 
    const history = useHistory();
    const stored_part = getCookie('tokenmysypart');



    function RecordData() {

        const formData = new FormData();
        const url = process.env.REACT_APP_API_URL + "myclass/api/add_payement_mode/";


        var pwd = document.getElementsByName("pwd")[0].value;
        var secret = document.getElementsByName("secret")[0].value;

        formData.append('token', stored_part);
        formData.append('type', String(menu));
        formData.append('pwd', pwd);
        formData.append('secret', secret);

        if (String(menu) === String("cb")) {
            var nom_carte = document.getElementsByName("nom_carte")[0].value;
            var num_carte = document.getElementsByName("num_carte")[0].value;
            var date_exp_carte = document.getElementsByName("date_exp")[0].value;
            var cvv_carte = document.getElementsByName("cvv")[0].value;
            formData.append('nom_carte', nom_carte);
            formData.append('num_carte', num_carte);
            formData.append('date_exp_carte', date_exp_carte);
            formData.append('cvv_carte', cvv_carte);
        }
        else if (String(menu) === String("sepa")) {
            var nom_compte = document.getElementsByName("nom_compte")[0].value;
            var iban = document.getElementsByName("num_iban")[0].value;
            var bic = document.getElementsByName("bic")[0].value;
            formData.append('nom_compte', nom_compte);
            formData.append('iban', iban);
            formData.append('bic', bic);
        }

        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                //console.log('Success:', result['message'], "result['status'] = ", result['status']);
                setmyApiResponse(result['status']);
                setResult(result['message']);

                if (String(result['status']) === String("true")) {
                    setpaymentadded("1");
                }else if (String(result['status']) === String("Err_Connexion")) {
                    alert('Erreur: ' + result['message']);
                    history.push("/Connexion");
                }

                else {
                    setpaymentadded("0");
                }


            })
            .catch((error) => {
                console.error('Error:', error);
                setmyApiResponse("false");
                setpaymentadded("0");
            });


    };

    const [mynote, setmynote] = useState("");
    function CheckCardNumber(e) {
        const val = e.target.value;
        if (!isNaN(val) && String(val).length <= 16) {
            setmynote(val);
        }
        else {
            document.getElementById("num_carte").value = mynote;
        }
    }


    const [dateexp, setdateexp] = useState("");

    function Onleave_expdate_exp(e){
        const regex = /^\d{2}\/\d{2}$/;
        var val = document.getElementById("date_exp").value 
        const found = val.match(regex);

        if (!found) {
            setdateexp("");
            document.getElementById("date_exp").value = "";           
        }
    }


    function Checkdate_expdate_exp(e) {
        const val = e.target.value;

        if (String(val).length < 6) {
            setdateexp(val);
        }

        if (String(val).length == 6) {
            const regex = /^\d{2}\/\d{2}$/;
            const found = dateexp.match(regex);

            if (!found) {
                alert(" pas bon ");
            }
        }

        if (String(val).length > 6) {
            document.getElementById("date_exp").value = dateexp;
        }


    }
    useEffect(() => {
        window.scrollTo({
            top: 0,
            behavior: "smooth",
          });
    }, []);


    return (
        <div className="paymentmethode">


            <div className="div_row_central">
                {String(paymentadded) === String("1") && <div className="okUpdateData">
                    Le mode de Paiement a été correctement ajouté
                </div>
                }

                {String(paymentadded) === String("0") && <div className="koUpdateData">
                    {result}
                </div>
                }

                <div className="titre1" onClick={menu_cb}> Prélèvement par carte bancaire </div>
                {String(menu) === String("cb") && <div>

                    <div className="div_row_gauche"> Carte Bancaire </div>
                    <div className="div_row_droite" style={{ "textAlign": "right" }}>
                        <img src={img_logo_stripe} className="img_payment" /> &nbsp;
                        
                    </div>

                     &nbsp;
<Box alignItems="left" sx={{ '& > :not(style)': { m: 1 }, width: '100%', }}>

                        <TextField
                            required

                            label="Nom inscrit sur la carte"
                            name="nom_carte"
                            className="texte_area"
                            sx={{ m: 1, width: '95%' }}

                            variant="standard"
                        />

                        <TextField
                            required
                            onChange={CheckCardNumber}
                            label="Numéro de carte"
                            name="num_carte"
                            id="num_carte"
                            autoComplete="off"
                            className="texte_area"
                            sx={{ m: 1, width: '95%' }}

                            variant="standard"
                        />

                        <TextField
                            required

                            label="Expiration (MM/AA)"
                            name="date_exp"
                            id="date_exp"
                            autoComplete="new-qsq"
                            value={dateexp}
                            className="texte_area"
                            sx={{ m: 1, width: '45%' }}
                            onChange={Checkdate_expdate_exp}
                            onBlur={Onleave_expdate_exp}
                            variant="standard"
                        />

                        <TextField
                            required
                            autoComplete='off'
                            label="CVV"
                            name="cvv"
                            className="texte_area"
                            sx={{ m: 1, width: '45%' }}

                            variant="standard"
                        />



                    </Box>

                </div>


                }
            </div>


            <hr />
            <div className="div_row_central">
                <div className="titre1" onClick={menu_sepa}> Prélèvement par virement SEPA</div>

                {String(menu) === String("sepa") && <div>
                     &nbsp;
<Box alignItems="left" sx={{ '& > :not(style)': { m: 1 }, width: '100%', }}>

                        <TextField
                            required

                            label="Nom du titulaire du compte"
                            name="nom_compte"
                            className="texte_area"
                            sx={{ m: 1, width: '95%' }}

                            variant="standard"
                        />

                        <TextField
                            required

                            label="IBAN"
                            name="num_iban"
                            className="texte_area"
                            sx={{ m: 1, width: '95%' }}

                            variant="standard"
                        />

                        <TextField
                            required

                            label="BIC"
                            name="bic"
                            className="texte_area"
                            sx={{ m: 1, width: '95%' }}

                            variant="standard"
                        />

                    </Box>

                </div>}


            </div>

            <hr />

        
            <div className="div_row_centre">
                <Button variant="contained" color="success" className="div_row22 btn_enreg " onClick={RecordData}>Enregistrer </Button>
            </div>

        </div>
    );

}

export default PaymentMethodeNoConnect;