import React from 'react';
// import {useParams} from 'react-router-dom';
import { useState } from 'react';
import axios from "axios";
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import '../styles/Admin.css'
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Container from '@mui/material/Container';
import CssBaseline from '@mui/material/CssBaseline';
import { PedalBikeRounded } from '@mui/icons-material';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
import { Link } from 'react-router-dom'


export default function EditBike({preloadedValues}){
    let navigate = useNavigate();
    const theme = createTheme();
    const [error, setError] = useState('');

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

    const {register, handleSubmit, formState: {errors} } = useForm({
         defaultValues: preloadedValues
  
    });
     

    


        const onSubmit = (data) => {
        axios.put(`/api/admin/bikes/${preloadedValues.id}`, data, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            successAlert();
            navigate("/admin/bikes");
        })
        .catch((error) => {
            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' }}>
                            <PedalBikeRounded />
                        </Avatar> 
                        <Typography component="h1" variant="h5">
                            Update Bike
                        </Typography>
                         <span className="text-danger">{error}</span>
            <form onSubmit={handleSubmit(onSubmit)}>
                <div className="form-group ">
                <p className="text-danger">{errors.serialNumber?.message}</p>
                <label>Serial Number:</label>
                <input 
                className="form-control col-3 mb-3" type="text" name="serialNumber" {...register ("serialNumber", {
                    required: "serial number should be entered", 
                    pattern: {
                        value: /^[A-Z]{2}[0-9]{8}$/,
                        message: "Serial number Pattern is invalid 2 uppercase 8 digits"
                      },
                    })} 
                    placeholder="AA12345678"/>
                <p className="text-danger">{errors.lastMaintenance?.message}</p>
                <label>Last Maintenance:</label>
                <input className="form-control col-4 mb-4" type="date" {...register ("lastMaintenance", {
                    required: "Last maintenace date is required",
                    })} />
                <p className="text-danger">{errors.stationId?.message}</p>
                <label>Station Id:</label>
                <input type="number" className="form-control col-4 mb-4" {...register ("stationId", {
                    required: "Id for station is required. Enter 0 if Bike is currently in use",
                    min: {value: 0, message: "Station Id cannot be negative"},
                })}/>
                <p className="text-danger">{errors.bikeType?.message}</p>
                <label>Bike Type:</label>
                <select className = "form-control" name="bikeType" {...register ("bikeType", {
                    required: "Bike Type is required", 
                })}>
                    <option value="">Please Choose Bike Type...</option>
                    <option value="STANDARD">STANDARD</option>
                    <option value="ELECTRIC">ELECTRIC</option>
                </select>
                <p className="text-danger">{errors.currentlyInUse?.message}</p>
                <label>Currently In Use:</label>
                <input type="checkbox"  {...register ("currentlyInUse", {
                    })} 
                 />
                <Grid item xs={12}>

                </Grid>
                
                <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    sx={{ mt: 3, mb: 2 }}
                >
                    Update Bike
                </Button>
                <Link to={"/admin/bikes"}><button className="btn btn-secondary green-btn w-100">Back to Bikes</button></Link>


                </div>
            </form>
            </Box>
                </main>
                </Container>
                    </ThemeProvider>
        </div>
    )
}

