import React, { useEffect, useState, useContext } from "react";
import axios from "axios";
import { AuthContext } from '../../helpers/AuthContext';
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as Yup from "yup";
import { yupResolver } from '@hookform/resolvers/yup';
import "../../App.css"
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 { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
const FormData = require('form-data');

function ReportForm() {
    let navigate = useNavigate();
    const theme = createTheme();
    const { authState } = useContext(AuthContext);
    const [error, setError] = useState('');
    const [listOfStations, setListOfStations] = useState([]);


    const validationSchema = Yup.object().shape({
        stationName: Yup.string().max(100, "Station name cannot exceed 100 characters"),
        serialNumber: Yup.string().max(10, "Serial number must include 2 uppercase letter and 8 digits"),
        body: Yup.string().min(1).max(1000).required("You must input a report body")
    });

    const { register, handleSubmit, formState, setValue } = useForm({
        mode: "all",
        defaultValues: {
            stationId: "",
            serialNumber: "",
            file: "",
            body: ""
        },
        resolver: yupResolver(validationSchema)
    });

    const { errors } = formState;

    useEffect(() => {
        if (authState.provisionAccess === false) {
            return navigate(`/pricing`);
        }
        axios.get(`/api/stations`, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            setListOfStations(response.data);
        });
    }, [authState, navigate]);

    const successAlert = () => {
        toast.success("Your report has been sent!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }

    const onSubmit = (data) => {
        const formData = new FormData();
        formData.append("stationId", data.stationId);
        formData.append("serialNumber", data.serialNumber);
        formData.append("file", data.file[0]);
        formData.append("body", data.body)

        axios.post(`/api/reports`, formData, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
        }).then((response) => {
            successAlert();
            navigate("/");
        })
            .catch((error) => {
                setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");

            });


    };

    return (
        <div className="w-100 text-center">
            <h1 className="mt-5">We appreciate your feedback.</h1>

            <ThemeProvider theme={theme}>
                <Container sx={{ minHeight: "100vh" }} component="main" maxWidth="lg">
                    <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'
                        >
                            <Typography component="h1" variant="h5">
                                File a Report
                            </Typography>
                            <Box sx={{ mt: 3 }} className="w-50">
                                <form onSubmit={handleSubmit(onSubmit)} enctype="multipart/form-data">
                                    <span className="text-danger">{error}</span>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12} sm={6}>
                                            <label>Station Name (Optional): </label>
                                            <p className="text-danger">{errors.stationId?.message}</p>
                                            <select className="form-control" {...register("stationId")} >
                                                <option value="">Select a station </option>
                                                {listOfStations.map((value) => (
                                                    <option value={`${value.id}`}>{value.name}</option>
                                                ))}
                                            </select>
                                        </Grid>
                                        <Grid item xs={12} sm={6}>
                                            <label>Bike Serial Number (Optional): </label>
                                            <p className="text-danger">{errors.serialNumber?.message}</p>
                                            <input className="form-control"
                                                {...register("serialNumber")} />
                                        </Grid>
                                        <Grid item xs={12} sm={6}>
                                            <label>Image (Optional): </label>
                                            <p className="text-danger">{errors.image?.message}</p>
                                            <input className="form-control" type="file" {...register("file")} accept="image/png, image/jpeg, image/jpg" />
                                        </Grid>
                                        <Grid item xs={12}>
                                            <label>Report: </label>
                                            <p className="text-danger">{errors.body?.message}</p>
                                            {/* <div className="container-sm"> */}
                                            <CKEditor className="fw-normal" editor={ClassicEditor} onReady={editor => { }} config={{ removePlugins: ["EasyImage", "ImageUpload", "MediaEmbed"] }}
                                                onChange={(value, editor) => setValue("body", editor.getData())}
                                            />
                                            {/* </div> */}
                                        </Grid>
                                    </Grid>
                                    <Button
                                        type="submit"
                                        variant="contained"
                                        sx={{ mt: 3, mb: 2 }}
                                    >
                                        Send
                                    </Button>
                                </form>
                            </Box>
                        </Box>
                    </main>
                </Container>
            </ThemeProvider>


        </div>
    )
}

export default ReportForm