import React from "react";
import {useEffect, useState} from "react";
import CloseVisitModal from "../components/CloseVisitModal.jsx";
import api from "../api.js";
import {DATE_TOGGLE} from "../constants.js";
import SuppliesModal from "../components/SuppliesModal.jsx";

export default function VisitsModule() {
    const username = localStorage.getItem('username');
    const [currentDate, setCurrentDate] = useState(new Date(localStorage.getItem(DATE_TOGGLE)));
    const [serviceVisits, setServiceVisits] = useState([]);
    const [loading, setLoading] = useState(false);

    const handlePrevious = () => {
        setCurrentDate(prevDate => {
            const newDate = new Date(prevDate)
            newDate.setDate(prevDate.getDate() - 1)
            localStorage.setItem(DATE_TOGGLE, newDate.toLocaleDateString())
            return newDate
        })
    }
    const handleNext = () => {
        setCurrentDate(prevDate => {
            const newDate = new Date(prevDate)
            newDate.setDate(prevDate.getDate() + 1)
            localStorage.setItem(DATE_TOGGLE, newDate.toLocaleDateString())
            return newDate
        })
    }
    const fetchServiceVisits = async () => {
            setLoading(true);
            try {
                const date = currentDate.toLocaleDateString('en-CA', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                }).replace(/\//g, '-');
                const response = await api.post(`visits/`, {date, username});
                if (response.status === 200) {
                    setServiceVisits(response.data);
                }
            } catch (error) {
                alert(error);
            } finally {
                setLoading(false);
            }
        };
    const formattedDate = currentDate.toLocaleDateString(
        'en-US', {
            year: 'numeric', month: 'long', day: 'numeric'
        })
    useEffect(() => {
        fetchServiceVisits();
    }, [currentDate]);

    return (
        <div className="d-flex flex-column">
            <div className="d-flex align-items-center justify-content-center p-2">
                <h4>Service Visits Module</h4>
            </div>
            <div className="d-flex align-items-center justify-content-evenly p-2">
                <button onClick={handlePrevious} className="btn btn-secondary" type="button"
                        data-bs-target="#serviceVisitsCarousel">Prev
                </button>
                <h5>{formattedDate}</h5>
                <button onClick={handleNext} className='btn btn-secondary'
                        data-bs-target="#serviceVisitsCarousel">Next
                </button>
            </div>
            <div id="serviceVisitsCarousel" className="carousel slide d-flex align-items-center">
                <div className="carousel-inner flex-grow-1">
                    <div className="carousel-item active">
                        <div className='d-flex p-2 flex-column align-items-center justify-content-center'>
                            {loading ? <div className="d-flex align-items-center"><h4 className="m-2 p-2">Loading Visits...</h4><div className="m-2 spinner-border"></div></div> : (
                                <table className="table">
                                    <thead>
                                    <tr>
                                        <th scope="col" className="w-50">Account</th>
                                        <th scope="col" className="w-20">Status</th>
                                        <th scope="col" className="w-20">Notes</th>
                                        <th scope="col" className="w-10">Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {serviceVisits.map(visit => (
                                        <tr key={visit.id}>
                                            <th scope="row">{visit.full_name}</th>
                                            <td>{visit.status}</td>
                                            <td>{visit.notes ? visit.notes : null}</td>
                                            <td>
                                                <div className="d-flex">
                                                    <CloseVisitModal visit={visit}/>
                                                    <SuppliesModal visit={visit}/>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
