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

function DeleteReport() {

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

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

  useEffect(() => {
    axios.get(`/api/admin/reports/${id}`, {
    headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
    }
}).then((response) => {
        response.data.body = parse(response.data.body)
        setReport(response.data);
    })
    .catch((error) => {

        setErrorList(list => list.push(error.response.data.error ?? error.response.data.message ?? "There was a problem"));
    });
}, [id]);

const deleteReport = () => {
  axios.delete(`/api/admin/reports/${id}`, {
  headers: {
      Authorization: 'Bearer ' + localStorage.getItem('accessToken')
  }
}).then((response) => {
      successAlert();
      navigate("/admin/reports");
  })
  .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">
    <h1 className="card-title">Are you sure you want to delete this report?</h1>
    <h6 className="card-subtitle mb-2 text-muted"></h6>
    <div>{report.reportTime}</div>
    <div>User: 
    {report.user && (
      <span> {report.user.username}</span>
    )}
    </div>
    <div>Station:
    {report.station && (
      <span> {report.station.name}</span>
    )}
    </div>
    <div>Bike:
    {report.bike && (
      <span> {report.bike.serialNumber}</span>
    )}
    </div>

    <label>Report Body: {report.body}</label>
    <div><img src={report.imageURL} width='400'></img></div>
    <Link to={"/admin/reports"}><button className="btn btn-secondary green-btn m-2">Back to Reports</button></Link>
    <Button className="bg-danger text-white" onClick={() => { deleteReport(id) }}>Delete</Button>
  </div>
</div>
</div>
  )
}

export default DeleteReport