import React, { useEffect, useState } from "react";
import axios from "axios";
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import TablePagination from '@mui/material/TablePagination';
import { MenuItem } from "@mui/material";
import Button from '@mui/material/Button';
import { Checkbox } from "@mui/material";
// import { FormControl } from '@mui/material';
import { useNavigate } from "react-router-dom";
import { Formik, Form, Field, ErrorMessage } from "formik";
import Select from '@mui/material/Select';
import * as Yup from "yup";
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Link } from 'react-router-dom';

function SendPromo() {
    const today = new Date();
    let tomorrow = new Date();
    tomorrow.setDate(today.getDate() + 1);
    const defaultDate = tomorrow.toLocaleDateString('en-CA')
    const [expirationDate, setExpirationDate] = useState(tomorrow);
    const [error, setError] = useState('');
    const [errorList, setErrorList] = useState([]);
    const [data, setData] = useState('');
    const [listOfUsers, setListOfUsers] = useState([]);
    const [listOfPromos, setListOfPromos] = useState([]);
    let navigate = useNavigate();

    const successAlert = () => {
        toast.success("Promos sent into the wild!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }

    useEffect(() => {
        axios.get(`/api/admin/user/activeUsers`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setData(response.data);
            setListOfUsers(response.data);
        }).catch((error) => {
            if (error.response.data.message) {
                setError(error.response.data.message);
            }
        });
    }, []);

    useEffect(() => {
        axios.get(`/api/admin/coupons/visible`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfPromos(response.data)
        }).catch((error) => {
            if (error.response.data.message) {
                setError(error.response.data.message);
            }
        });
    }, []);

    function createData(id, username, email, status, stripeUserId, firstName, lastName, userRoles) {
        let roles = userRoles.map(role => {
            return role.name.replace("ROLE_", "").toLowerCase();
        })
        return { id, username, email, status, stripeUserId, firstName, lastName, roles };
    }

    const rows = listOfUsers.map((value) => (
        createData(value.id, value.username, value.email, value.status, value.stripeUserId, value.firstName, value.lastName, value.roles)
    ))

    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(5);


    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    const initialValues = {
        customerIds: [],
        couponId: ""

    };

    const validationSchema = Yup.object().shape({
        customerIds: Yup.array().min(1, "You must select at least 1 user").required(),
        couponId: Yup.number().required("You must select a promo"),
    });

    const onSubmit = (data) => {
        console.log(expirationDate)
        if (expirationDate < defaultDate) {
            setError(`Expiration date ${expirationDate} must be after today ${defaultDate}`)
            return;
        }
        let submit = {
            customerIds: data.customerIds,
            couponId: parseFloat(data.couponId),
            expiresAt: expirationDate
        }

        console.log(submit);

        axios.post(`/api/admin/email/sendReturningDiscount`, submit, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            console.log(response.data)
            successAlert();
            navigate("/admin/promos");
        }).catch((error) => {
            toast.error("Failed to send Promos")
            console.log(error.response)
            setErrorList([]);
            let tmpArray = []
            Object.entries(error.response.data).forEach(([key, value]) =>
                tmpArray.push(value))
            setErrorList(tmpArray);
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    };

    return (
        <div className='d-flex justify-content-center bg-grey '>
            <Formik onSubmit={onSubmit} initialValues={initialValues} validationSchema={validationSchema}>
                <Form >
                    <TableContainer
                        className='mt-5 w-100 shadow'
                        component={Paper}
                    >
                        <h1 className='text-center mt-2'>List of Users for Promos</h1>
                        <Table className='shadow-sm mb-3' sx={{ minWidth: 850 }} aria-label="simple table">
                            <TableHead className='shadow-sm'>
                                <TableRow>
                                    <TableCell align="right">ID</TableCell>
                                    <TableCell align="right">Username</TableCell>
                                    <TableCell align="right">Email</TableCell>
                                    <TableCell align="right">Last Name</TableCell>
                                    <TableCell align="right">First Name</TableCell>
                                    <TableCell align="right">Stripe Id</TableCell>
                                    <TableCell align="center">User Roles</TableCell>
                                    <TableCell align="center">Account Status</TableCell>
                                    <TableCell align="center">Transfer</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => (
                                    <TableRow
                                        key={row.id}
                                        sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                                    >
                                        <TableCell align="right">{row.id}</TableCell>
                                        <TableCell align="right">{row.username}</TableCell>
                                        <TableCell align="right">{row.email}</TableCell>
                                        <TableCell align="right">{row.lastName}</TableCell>
                                        <TableCell align="right">{row.firstName}</TableCell>
                                        <TableCell align="right">{row.stripeUserId}</TableCell>
                                        <TableCell align="right">{row.roles.join(", ")}</TableCell>
                                        <TableCell align="right">{row.status}</TableCell>
                                        <TableCell align="right">
                                            <Field name="customerIds" type="checkbox" as={Checkbox} value={`${row.id}`} />
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>

                        {listOfUsers.length > 0 && (
                            <div className='d-flex flex-wrap justify-content-center mt-5'>
                                <label htmlFor="couponId">Promo: </label>
                                <Field as={Select} name="couponId" displayEmpty className='me-5'>
                                    <MenuItem value='' selected="true" >Select a promo</MenuItem>
                                    {listOfPromos.map((value, key) => (
                                        <MenuItem key={key} value={`${value.id}`}>{value.title}</MenuItem>
                                    ))}
                                </Field>

                                <label htmlFor="expirationDate">Expiration: </label>
                                <input
                                    type="date"
                                    className="form-control w-25 me-5"
                                    name="expirationDate"
                                    min={defaultDate}
                                    onChange={
                                        (event) => {
                                            setExpirationDate(event.target.value);
                                        }
                                    }
                                />

                                <Button
                                    className="bg-info text-white m-2 align-middle"
                                    type="submit"
                                >
                                    Send Promos
                                </Button>
                                <Link to={"/admin/promos"}><button className="btn btn-secondary green-btn m-2">Back to Promos</button></Link>
                                <span className="text-danger mt-3">{error}</span>
                                <ul>
                                    {errorList.map((value, key) => {
                                        <>
                                            <li className="text-danger list-unstyled">{value}</li>
                                        </>
                                    })}
                                </ul>
                                <ul className="list-unstyled mt-5">
                                    <li><ErrorMessage name="customerIds" component="span" className='error-text' /></li>
                                    <li><ErrorMessage name="couponId" component="span" className='error-text' /></li>
                                </ul>
                            </div>
                        )}
                        <hr />

                        <TablePagination
                            rowsPerPageOptions={[5, 10, 25]}
                            component="div"
                            count={rows.length}
                            rowsPerPage={rowsPerPage}
                            page={page}
                            onPageChange={handleChangePage}
                            onRowsPerPageChange={handleChangeRowsPerPage}
                        ></TablePagination>

                    </TableContainer>
                </Form>
            </Formik>
        </div>
    )
}

export default SendPromo