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 ViewReport() {
    // let navigate = useNavigate();
    let { id } = useParams();
    const [report, setReport] = useState({});
    const [error, setError] = useState("");

            const successAlert = () => {
        // window.alert("Invalid Credentials");
        toast.success("Bike is sent for maintenance sucessfully!", {
            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) => {
        setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
      });
  }, [id]);

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

      const sendToMaintenance = (id) => {
        axios.post(`/api/admin/maintenance/reported/${id}`, null, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            console.log(response);
            updatePage();
            successAlert();
        }).catch((error) => {
            toast.error("Failed to send bike for maintenance")
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    };

  return (
    <div className="container">
                        <span className="text-danger list-unstyled">{error}</span>
    <div className="card">
      <div className="card-body">
        <h6 className="card-subtitle mb-2 text-muted"> <span className="text-danger">{error}</span> </h6>
        <div>DateTime: {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>
    
        <div>Report Body: {report.body}</div>
        <div><img src={report.imageURL} width='400'></img></div>
        <Link to={"/admin/reports"}><button className="btn btn-primary green-btn mt-2">Back to Reports</button></Link>
        {report.bike && 
        (<span> 
          {report.bike.status == "ACTIVE" && !report.bike.currentlyInUse && report.bike.lastMaintenance < report.reportTime && ( 
            <span>{" "}<button className="btn btn-info mt-2" onClick={() => { sendToMaintenance(report.id) }}> Send Bike For Maintenance</button></span>)}</span>
        )
        }
      </div>
    </div>
    </div>
  )
}

export default ViewReport