'use client'
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { gradientClasses } from "@utils/constant.utils";
import client from "@auth";
import PageLoader from "@/components/common-component/PageLoader";
import PageNoData from "@/components/common-component/PageNoData";
import { Icon } from "@iconify/react";
import { useRouter } from "next/navigation";

const DayReservationMainComponent = () => {

    const router = useRouter()
    // const params = useParams();
    // const restaurantbranch = params?.restaurantbranch;
    // const RestaruntBranch = restaurantbranch

    const [daysData, setDaysData] = useState(null);
    const [error, setError] = useState(null);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [formData, setFormData] = useState({ day: "" });
    const [existingDays, setExistingDays] = useState([]);
    const [formError, setFormError] = useState("");
    const [deleteConfirm, setDeleteConfirm] = useState({ show: false, id: null });
    const [restaruntBranch, setRestaruntBranch] = useState("")

    useEffect(() => {
        const restarunt = localStorage.getItem("restaurantbranch")
        setRestaruntBranch(restarunt)

    }, [])

    useEffect(() => {
        const isLogin = JSON.parse(localStorage.getItem("isLogin"));
        if (!isLogin) {
            router.push(`/admin?restaurantbranch=${restaruntBranch}`);
        }
    }, [router]);

    useEffect(() => {
        if (restaruntBranch && restaruntBranch !== "")
            getDayData();
    }, [restaruntBranch]);



    const getDayData = async () => {
        try {
            setLoading(true);
            // const res = await client?.get(`/Dine360%20Days?fields=["*"]`);
            const res = await client?.get(`/Dine360%20Days?fields=["*"]&filters=[["restaurantbranch","=","${restaruntBranch}"]]`);
            const fetchedData = res?.data?.data || [];
            setDaysData(fetchedData);
            setExistingDays(fetchedData.map(item => item.day));
        } catch (error) {
            console.error("Error fetching days:", error);
            setError(error?.message || "Failed to fetch day data");
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!formData.day) {
            setFormError("Please select a day");
            return;
        }

        setFormError("");
        const body = { day: formData.day, restaurantbranch: restaruntBranch };

        try {
            await client.post(`/Dine360 Days`, body);
            setShowModal(false);
            setFormData({ day: "" });
            getDayData();
        } catch (err) {
            alert("Error: " + (err?.response?.data?.message || "Request failed"));
        }
    };

    const handleDeleteConfirm = async () => {
        if (!deleteConfirm.id) return;
        try {
            await client.delete(`/Dine360 Days/${deleteConfirm.id}`);
            setDeleteConfirm({ show: false, id: null });
            getDayData();
        } catch (err) {
            alert("Delete failed.");
        }
    };

    return (
        <>
            <div className="container" style={{ marginBottom: "100px" }}>
                <div className=' h-100 p-0 radius-12'>
                    <div className='p-3 '>
                        <div className='d-flex justify-content-end align-items-center mb-3'>
                            {/* <div>
                                <h6 className="mb-0 text-lg">Day Reservation</h6>
                            </div> */}
                            <button className="btn btn-bg-theme" onClick={() => {
                                setFormData({ day: "" });
                                setFormError("");
                                setShowModal(true);
                            }}>
                                Create Day
                            </button>
                        </div>
                        <div className='row gy-3 gx-3 gx-lg-5 gy-lg-5 justify-content-center'>
                            {loading ? (
                                <PageLoader />
                            ) : daysData?.length === 0 ? (
                                <PageNoData />
                            ) : (
                                daysData.map((days, index) => {
                                    const gradientClass = gradientClasses[index % gradientClasses.length];
                                    return (
                                        <div className="col-xxl-3 col-lg-4 col-sm-6 cursor-pointer" key={days.name}>

                                            <div className="card p-3 shadow-2 radius-8 h-100 border border-white position-relative">
                                                <div className="card-body d-flex justify-content-center align-items-center p-0 ">

                                                    {/* Day Image Link */}
                                                    <Link
                                                        href={`/admin/day-reservation-enable-table?restaurantbranch=${restaruntBranch}&name=${days?.name}&day=${encodeURIComponent(days?.day)}`}
                                                    >
                                                        <img
                                                            src={`/assets/images/day/${days.day.slice(0, 3).toLowerCase()}.webp`}
                                                            alt={days.day}
                                                            style={{ width: "200px" }}
                                                        />
                                                    </Link>

                                                    {/* Delete Button Top-Right */}
                                                    <button
                                                        className="remove-item-btn bg-danger-focus bg-hover-danger-200 text-danger-600 fw-medium w-40-px h-40-px d-flex justify-content-center align-items-center rounded-circle position-absolute"
                                                        style={{ top: "8px", right: "8px" }}
                                                        onClick={() => setDeleteConfirm({ show: true, id: days.name })}
                                                    >
                                                        <Icon icon="fluent:delete-24-regular" className="menu-icon" />
                                                    </button>
                                                </div>
                                            </div>


                                        </div>
                                    );
                                })
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Create Modal */}
            {showModal && (
                <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="mb-3 d-flex justify-content-between align-items-center">
                                    <h6 className="mb-0 text-lg">Create Day</h6>
                                    <button type="button" className="btn-close" onClick={() => setShowModal(false)}></button>
                                </div>
                                <form onSubmit={handleSubmit}>
                                    <div className="mb-3">
                                        <label className="form-label">Day</label>
                                        <select
                                            className="form-select"
                                            value={formData.day}
                                            onChange={(e) => {
                                                setFormData({ day: e.target.value });
                                                setFormError("");
                                            }}
                                        >
                                            <option value="">Select Day</option>
                                            {["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
                                                .filter(day => !existingDays.includes(day))
                                                .map(day => (
                                                    <option key={day} value={day}>{day}</option>
                                                ))}
                                        </select>
                                        {formError && <small className="text-danger">{formError}</small>}
                                    </div>
                                    <div className="text-end">
                                        <button type="submit" className="btn btn-bg-theme">Create</button>
                                    </div>
                                </form>
                            </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="mb-1 d-flex justify-content-between align-items-center">
                                    <h5 className="mb-0 text-lg">Delete Confirmation</h5>
                                    <button type="button" className="btn-close" onClick={() => setDeleteConfirm({ show: false, id: null })}></button>
                                </div>
                                <div>
                                    <p>Are you sure you want to delete this day?</p>
                                </div>
                                <div className="d-flex justify-content-end align-items-center gap-2">
                                    <button
                                        className="btn btn-secondary"
                                        onClick={() => setDeleteConfirm({ show: false, id: null })}
                                    >
                                        Cancel
                                    </button>
                                    <button className="btn btn-danger" onClick={handleDeleteConfirm}>
                                        Yes, Delete
                                    </button>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default DayReservationMainComponent;
