import React from "react";
import api from "../api";

export default function ProjectCloseModal({ proj }) {
    const modalId = `modal-project-close-${proj.id.replace(/\s+/g, '-')}`;

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await api.post('projects/close/', {
                id: proj.id
            });
            if (response.status === 200) {
                onSuccess()
            }
        } catch (error) {
            alert(error.detail);
        }
    }
    const onSuccess = () => {
        alert('Project closed successfully!');
        window.location.reload();
    }

    return (
        <div>
            <button type="button" className="btn btn-primary" data-bs-toggle="modal"
                    data-bs-target={`#${modalId}`}>
                Close Project
            </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 Project
                            </h1>
                            <button type="button" className="btn-close" data-bs-dismiss="modal"
                                    aria-label="Close"></button>
                        </div>
                        <div className="modal-body">
                            <p>Project ID: {proj.id}</p>
                            <p>Store #: {proj.store} - {proj.city}</p>
                            <p>Date: {proj.date}</p>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-secondary"
                                    data-bs-dismiss="modal">Cancel
                            </button>
                            <button onClick={handleSubmit} type="button" className="btn btn-primary"
                                    data-bs-dismiss="modal">
                                Submit
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
