import axios from "axios";
import { useNavigate } from 'react-router-dom';
import { useEffect, useState } from "react";
import { useParams } from 'react-router-dom';
import React from 'react'
import Button from '@mui/material/Button';
import {Link} from 'react-router-dom';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';


export default function DeleteStation() {

    let navigate = useNavigate();
    let { id } = useParams();
    const [station, setStation] = useState({});
    const [errorList, setErrorList] = useState([]);

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

    useEffect(() => {
        axios.get(`/api/admin/stations/${id}`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            setStation(response.data);
        })
        .catch((error) => {
            setErrorList(list => list.push(error.response.data.error ?? error.response.data.message ?? "There was a problem"));
        });
    }, [id]);

    const deleteStation = () => {
        axios.delete(`/api/admin/stations/${id}`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            successAlert();
            navigate("/admin/stations");
        })
        .catch((error) => {
            setErrorList(list => list.push(error.response.data.error ?? error.response.data.message ?? "There was a problem"));
        });

    }



  return (

<div className="container">
{errorList.map((value, key) => {
            return (
                <ul>
                    <li className="text-danger list-unstyled">{value}</li>
                </ul>

                    )
            })}
<div className="card">
  <div className="card-body">
    <h5 className="card-title">Are you sure you want to delete this station?</h5>
    <h6 className="card-subtitle mb-2 text-muted">{station.name}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Total Slots: {station.totalSlots}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Status: {station.status}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Latitude: {station.latitude}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Longitude: {station.longitude}</h6>
    <Link to={"/admin/stations"}><button className="btn btn-secondary green-btn m-2">Back to Stations</button></Link>
    <Button className="bg-danger text-white" onClick={() => { deleteStation(id) }}>Delete</Button>
  </div>
</div>
</div>


  )
}

 