import React from "react";
import api from "../api.js";
import {useState} from "react";

export default function CloseVisitModal({visit}) {
    const modalId = `modal-${visit.id.replace(/\s+/g, '-')}`;
    const username = localStorage.getItem("username");
    const [notes, setNotes] = useState('');
    const handleCloseVisit = async () => {
        try {
            const response = await api.post('visits/close/', {id: visit.id, notes: notes});
            if (response.status === 200) {
                onSuccess()
            }
        } catch (error) {
            alert(error.detail);
        }
    }
    const handleChange = (e) => {
        setNotes(e.target.value);
    }
    const onSuccess = () => {
        alert('Visit closed successfully!');
        window.location.reload();
    }
    return (
        <div>
            <button type="button" className="btn btn-primary" data-bs-toggle="modal" disabled={visit.status === 'Closed'}
                    data-bs-target={`#${modalId}`}>Close</button>
            <div className='modal fade' id={modalId} data-bs-backdrop="static"
                 data-bs-keyboard="false" tabIndex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h1 className="modal-title fs-5" id="staticBackdropLabel">
                                Close service visit?
                            </h1>
                            <button type="button" className="btn-close" data-bs-dismiss="modal"
                                    aria-label="Close"></button>
                        </div>
                        <div className="modal-body">
                            <p>Visit ID: {visit.id}</p>
                            <p>Date: {visit.date}</p>
                            <p>Account: {visit.full_name}</p>
                            <p>Submitted by: {username}</p>
                            <input onChange={handleChange} type="text" className="form-control" placeholder="Add notes here..."></input>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary"
                                    data-bs-dismiss="modal">Close
                            </button>
                            <button type="button" className="btn btn-primary" onClick={handleCloseVisit} data-bs-dismiss="modal">Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
