import React, { useEffect, useState } from 'react';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
import axios from "axios";
import { useNavigate } from "react-router-dom";
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import '../../styles/LoginRegistration.css';
import MonetizationOnIcon from '@mui/icons-material/MonetizationOn';
//import DatePicker from "react-datepicker";
import { Select, MenuItem } from "@material-ui/core";
import { Link } from 'react-router-dom';


export default function AddPromo() {
    const today = new Date();
    const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    let navigate = useNavigate();
    const theme = createTheme();
    const [title, setTitle] = useState('');
    const [promoType, setPromoType] = useState('percentOff');
    const [percentOff, setPercentOff] = useState(null);
    const [amountOff, setAmountOff] = useState(null);
    const [expirationDate, setExpirationDate] = useState(date);
    const [error, setError] = useState('');
    const [errorList, setErrorList] = useState([]);

    const successAlert = () => {
        // window.alert("Invalid Credentials");
        toast.success("Promo has been added successfully!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }

    const handleSubmit = () => {
        let data = {
            title: title,
            percentOff: null,
            amountOff: null,
            expirationDate: expirationDate
        };
        if (percentOff === null && amountOff === null) {
            setError("Either Percent off or Amount off must be submitted")
            return;
        }
        if (percentOff === null) {
            data.amountOff = Math.trunc(amountOff * 100);
        } else {
            data.percentOff = percentOff;
        }
        axios.post(`/api/admin/coupons/`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            successAlert();
            navigate("/admin/promos");
        }).catch((error) => {
            toast.error("Failed to add Promo")
            setErrorList([]);
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    }

    return (
        <div>
            <ThemeProvider theme={theme}>
                <Container sx={{ minHeight: "100vh" }} component="main" maxWidth="xs">
                    <CssBaseline />
                    <main className="w-100 bg-white rounded-3 shadow-sm">
                        <Box
                            sx={{
                                p: 5,
                                marginTop: 8,
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}
                            className='contentBox rounded-3'
                        >
                            <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                                <MonetizationOnIcon />
                            </Avatar>
                            <Typography component="h1" variant="h5">
                                Add Coupon
                            </Typography>
                            <Box sx={{ mt: 3 }}>
                                <Grid container spacing={2}>
                                    <Grid item xs={12}>
                                        <label>Promo Title: </label>
                                        <input
                                            className="form-control"
                                            name="title"
                                            onChange={
                                                (event) => {
                                                    setTitle(event.target.value);
                                                }
                                            }
                                        />
                                    </Grid>

                                    <Grid item xs={12}>
                                        <label htmlFor="promoTypeSelect">Choose Discount Type: </label>
                                        <select
                                            name="promoTypeSelect"
                                            id="promoTypeSelect"
                                            onChange={
                                                (event) => {
                                                    setPromoType(event.target.value);
                                                }
                                            }
                                        >
                                            <option value="percentOff">Percentage Off</option>
                                            <option value="amountOff">Dollar Amount Off</option>
                                        </select>
                                        <br />
                                    </Grid>

                                    {promoType.includes('percentOff') ? (
                                        <Grid item xs={12}>
                                            <label htmlFor="percentOff">Percentage Off: </label>
                                            <input
                                                type="number"
                                                className="form-control"
                                                name="percentOff"
                                                onChange={
                                                    (event) => {
                                                        setPercentOff(event.target.value);
                                                    }
                                                }
                                            />
                                        </Grid>
                                    ) : (
                                        <Grid item xs={12}>
                                            <label htmlFor="amountOff">Dollar Amount Off: </label>
                                            <input
                                                type="number"
                                                className="form-control"
                                                name="amountOff"
                                                onChange={
                                                    (event) => {
                                                        setAmountOff(event.target.value);
                                                    }
                                                }
                                            />
                                        </Grid>
                                    )}

                                    <Grid item xs={12}>
                                        <label htmlFor="expirationDate">Expiration: </label>
                                        <input
                                            type="date"
                                            className="form-control"
                                            name="expirationDate"
                                            min={date}
                                            onChange={
                                                (event) => {
                                                    setExpirationDate(event.target.value);
                                                }
                                            }
                                        />
                                    </Grid>

                                </Grid>
                                <Button
                                    onClick={handleSubmit}
                                    fullWidth
                                    variant="contained"
                                    sx={{ mt: 3, mb: 2 }}
                                >
                                    Add Promo
                                </Button>
                                <Link to={"/admin/promos"}><button className="btn btn-secondary green-btn w-100">Back to Promos</button></Link>
                                <span className="text-danger">{error}</span>
                            </Box>
                        </Box>
                    </main>
                </Container>
            </ThemeProvider>
        </div>
    )
}



