"use client";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useEffect, useState } from "react";
import client from "../../../Auth";
import dayjs from "dayjs";
import PageLoader from "../common-component/PageLoader";
import PageNoData from "../common-component/PageNoData";
import { useRouter } from "next/navigation";
import { formatTime } from "../../../utils/CommonFunction";

const DateReservationSection = () => {

    const router = useRouter()

    const [dateReservation, setDateReservation] = useState([]);
    const [loading, setLoading] = useState(true);
    const [deleteConfirm, setDeleteConfirm] = useState({ show: false, id: null });


    useEffect(() => {
        getReservationDate();
    }, []);

    const getReservationDate = async () => {
        try {
            setLoading(true)
            const res = await client.get(
                '/Dine360%20Table%20Reservation%20Master?fields=["*"]'
            );
            setDateReservation(res?.data?.data);
            setLoading(false)
        } catch (error) {
            setLoading(false)
            console.error("Fetch error:", error);
        }
    };


    const handleCreateDateReservation = () => {
        router?.push("/create-reservation-date-table")
    }

    const handleEditModel = async (reservation) => {
        router?.push(`/edit-reservation-date-table?name=${reservation?.name}`)
    }

    const handleDelete = async () => {
        try {
            await client.delete(`/Dine360 Table Reservation Master/${deleteConfirm?.id}`);
            setDeleteConfirm({ show: false, id: null });
            getReservationDate();
        } catch (error) {
            if (
                error?.response?.data?.exception?.includes("DuplicateEntryError") ||
                error?.response?.data?.message?.includes("Duplicate entry")
            ) {
                alert("Floor with this name already exists. Please use a different name.");
            } else if (error?.response?.data?.exception?.includes("LinkExistsError") ||
                error?.response?.data?.message?.includes("LinkExistsError")) {
                alert(" Cannot delete or cancel because Dine360 Floor three is linked with Dine360 Room fsrf65ahb5");
            }
        }
    };

    return (
        <>
            {loading ? (
                <PageLoader />
            ) : dateReservation?.lenght === 0 ? (
                <PageNoData />
            ) : (
                <div className="container-fluid">
                    <div className="card h-100 p-0 radius-12">


                        <div className="card-body p-24">
                            <div className="d-flex justify-content-between align-items-center mb-3">
                                <div>
                                    <h6 className="text-lg mb-0">Date Reservation</h6>
                                </div>
                                <button
                                    type="button"
                                    onClick={() => handleCreateDateReservation()}
                                    className="btn btn-danger-500 text-sm btn-sm px-12 py-12 radius-8 d-flex align-items-center gap-2"
                                >
                                    Create
                                </button>
                            </div>
                            <div className="table-responsive scroll-sm">
                                <table className="table bordered-table sm-table mb-0">
                                    <thead>
                                        <tr>
                                            {/* <th>S.L</th> */}
                                            <th className="text-center">From Date</th>
                                            <th className="text-center">To Date</th>
                                            <th className="text-center">Start Time</th>
                                            <th className="text-center">End Time</th>
                                            <th className="text-center">Actions</th>

                                        </tr>
                                    </thead>
                                    <tbody>
                                        {
                                            dateReservation?.map((reservation) => {
                                                return (
                                                    <tr key={reservation?.name}>
                                                        {/* <td>01</td> */}
                                                        <td className="text-center">
                                                            {reservation?.from_date ? dayjs(reservation.from_date).format("DD-MMM-YYYY") : ""}
                                                        </td>
                                                        <td className="text-center">
                                                            {reservation?.to_date ? dayjs(reservation.to_date).format("DD-MMM-YYYY") : ""}
                                                        </td>
                                                        <td className="text-center">{formatTime(reservation?.start_time)}</td>
                                                        <td className="text-center">{formatTime(reservation?.end_time)}</td>

                                                        <td className="text-center">
                                                            <div className="d-flex justify-content-center gap-3">
                                                                <button
                                                                    type="button"
                                                                    onClick={() => handleEditModel(reservation)}
                                                                    className="bg-success-100 text-success-600 w-40-px h-40-px d-flex justify-content-center align-items-center rounded-circle"
                                                                >
                                                                    <Icon icon="lucide:edit" className="menu-icon" />
                                                                </button>
                                                                <button onClick={(e) => {
                                                                    e.preventDefault();
                                                                    setDeleteConfirm({ show: true, id: reservation.name })
                                                                }}
                                                                    type="button"
                                                                    className="bg-danger-focus text-danger-600 w-40-px h-40-px d-flex justify-content-center align-items-center rounded-circle"
                                                                >
                                                                    <Icon icon="fluent:delete-24-regular" className="menu-icon" />
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                )
                                            })
                                        }

                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>


                </div >
            )}

            {/* Delete Confirmation Modal */}
            {deleteConfirm.show && (
                <div className="modal fade show" style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}>
                    <div className="modal-dialog modal-dialog-centered">
                        <div className="modal-content">

                            <div className="modal-body">
                                <div className="d-flex justify-content-between mb-1">
                                    <h6 className="text-xl mb-0">Confirm Delete</h6>
                                    <button
                                        type="button"
                                        className="btn-close"
                                        onClick={() => setDeleteConfirm({ show: false, id: null })}
                                    ></button>
                                </div>
                                <p>Are you sure you want to delete this Reservation?</p>
                                <div className="d-flex justify-content-end gap-2">
                                    <button
                                        className="btn btn-secondary"
                                        onClick={() => setDeleteConfirm({ show: false, id: null })}
                                    >
                                        Cancel
                                    </button>
                                    <button className="btn btn-danger" onClick={handleDelete}>
                                        Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default DateReservationSection;
