"use client"
import MasterLayout from "@/masterLayout/MasterLayout";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import client from "@auth";
import classNames from "classnames";
import Link from "next/link";
import PageLoader from "@/components/common-component/PageLoader";
import PageNoData from "@/components/common-component/PageNoData";
import Breadcrumb from "@/components/Breadcrumb";
import { Icon } from "@iconify/react";


const TableOrderInner = () => {

    const router = useRouter();
    const searchParams = useSearchParams();

    const roomName = decodeURIComponent(searchParams.get("roomname") || "");
    const FloorName = decodeURIComponent(searchParams.get("floor") || "");

    const [tables, setTables] = useState([]);
    const [showModalTable, setShowModalTable] = useState(false);
    const [showModal, setShowModal] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);
    const [selectedFloorId, setSelectedFloorId] = useState(null);
    const [selectedTable, setSelectedTable] = useState(null);
    const [seatCount, setSeatCount] = useState(1);
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(true)
    const [formData, setFormData] = useState({
        tablename: "",
        minimumoccupancy: "",
        totalcapacity: "",
        description: "",
    });
    const [errors, setErrors] = useState({});
    const [deleteConfirm, setDeleteConfirm] = useState({ show: false, id: null });
    const [restaruntBranch, setRestaruntBranch] = useState("")
    const [floorData, setFloorData] = useState(null);
    const [roomData, setRoomData] = useState(null);
    const [selectedFloor, setSelectedFloor] = useState("");
    const [selectedRoom, setSelectedRoom] = 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]);



    // Get floor data when branch is ready
    useEffect(() => {
        if (restaruntBranch) {
            getFloor();
        }
    }, [restaruntBranch]);

    const getFloor = async () => {
        try {
            const res = await client.get(
                `/Dine360 Floor?fields=["*"]&limit_page_length=100&filters=[["restaurantbranch","=","${restaruntBranch}"]]`
            );
            const floors = res?.data?.data || [];
            setFloorData(floors);

            if (floors.length > 0) {
                setSelectedFloor(floors[0].name);
                setSelectedRoom(null);
                getRoomData(floors[0].name);
            } else {
                setSelectedFloor(null);
                setRoomData([]);
                setTables([]);
            }
        } catch (error) {
            console.error("Error fetching floor data:", error);
        }
    };


    const getRoomData = async (floorName) => {
        try {
            const res = await client.get(
                `/Dine360 Room?fields=["*"]&limit_page_length=100&filters=[["floor","=","${floorName}"]]`
            );
            const rooms = res?.data?.data || [];
            setRoomData(rooms);

            if (rooms.length > 0) {
                setSelectedRoom(rooms[0].name);
                getTableData(rooms[0].name);
            } else {
                setSelectedRoom(null); // clear selection if no rooms
                setTables([]); // clear table data
            }
        } catch (error) {
            console.error("Error fetching room data:", error);
        }
    };


    const getTableData = async (roomName) => {
        try {
            setLoading(true);
            const res = await client.get(
                `/Dine360 Table?fields=["*"]&limit_page_length=100&filters=[["room","=","${roomName}"]]`
            );
            setTables(res?.data?.data || []);
        } catch (error) {
            console.error("Error fetching table data:", error);
        } finally {
            setLoading(false);
        }
    };

    const handleTableClick = (table) => {
        setSelectedTable(table);
        setSeatCount(1);
        setError('');
        setShowModalTable(true);
    };

    const handleSeatChange = (e) => {
        const value = parseInt(e.target.value);
        if (value > selectedTable?.totalcapacity) {
            setError(`Maximum capacity is ${selectedTable?.totalcapacity} seats`);
        } else {
            setError('');
        }
        setSeatCount(value);
    };

    const handleSeatSubmit = () => {
        if (
            selectedTable &&
            seatCount > 0 &&
            seatCount <= selectedTable?.totalcapacity
        ) {
            const now = new Date();

            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // month is 0-based
            const day = String(now.getDate()).padStart(2, '0');
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            const second = String(now.getSeconds()).padStart(2, '0');

            const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;

            console.log(formattedTime);

            // Push the route with formatted timestamp
            router.push(
                `/waiter/menu-items?restaurantbranch=${restaruntBranch}&table=${encodeURIComponent(selectedTable.name)}&seats=${seatCount}&time=${encodeURIComponent(formattedTime)}`
            );
        }
    };


    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
    };

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

        const newErrors = {};
        Object.entries(formData).forEach(([key, value]) => {
            if (!String(value).trim()) {
                newErrors[key] = `${key} is required`;
            }
        });
        setErrors(newErrors);
        if (Object.keys(newErrors).length > 0) return;


        const Body = {
            tablename: formData?.tablename,
            minimumoccupancy: formData?.minimumoccupancy,
            totalcapacity: formData?.totalcapacity,
            description: formData?.description,
            room: roomName,
            floor: FloorName,
            status: "Available",
            restaurantbranch: restaruntBranch
        }

        try {
            if (isEditMode) {
                await client.put(`/Dine360 Table/${selectedFloorId}`, Body);
            } else {
                await client.post(`/Dine360 Table`, Body);
            }
            getTableData();
            resetForm();
        } 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 {
                alert("An error occurred. Please try again.");
            }
        }
    };

    const resetForm = () => {
        setFormData({
            tablename: "",
            minimumoccupancy: "",
            totalcapacity: "",
            // branch: "",
            description: "",
        });
        setShowModal(false);
        setIsEditMode(false);
        setSelectedFloorId(null);
        setErrors({});
    };

    const handleEdit = (table) => {
        setIsEditMode(true);
        setSelectedFloorId(table.name);
        setFormData({
            tablename: table.tablename || "",
            minimumoccupancy: table.minimumoccupancy || "",
            totalcapacity: table.totalcapacity || "",
            description: table.description || "",
            // branch: room.branch || "",
        });
        setShowModal(true);
    };

    const handleDelete = async () => {
        try {
            await client.delete(`/Dine360 Table/${deleteConfirm.id}`);
            setDeleteConfirm({ show: false, id: null });
            getTableData();
        } catch (error) {
            console.error("Delete error:", error);
        }
    };


    return (
        <>
            <div className="card">
                <div className="card-body">
                    <div className="row " style={{ position: "sticky", top: "150px", zIndex: 1020 }}>
                        {/* Floor Column */}
                        <div className="col-12 col-md-4">
                            <div className="overflow-auto" style={{ whiteSpace: "nowrap" }}>
                                <ul
                                    className="nav bordered-tab border border-top-0 border-start-0 border-end-0 nav-pills"
                                    role="tablist"
                                >
                                    {floorData?.map((floor, index) => (
                                        <li className="nav-item d-inline-block" role="presentation" key={floor.name}>
                                            <button
                                                className={`nav-link px-4 mx-3 py-2 ${selectedFloor === floor.name ? "active" : ""
                                                    }`}
                                                id={`floor-tab-${index}`}
                                                type="button"
                                                role="tab"
                                                aria-selected={selectedFloor === floor.name}
                                                onClick={() => {
                                                    setSelectedFloor(floor.name);
                                                    getRoomData(floor.name);
                                                }}
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                title={`Floor: ${floor.floorname}`}
                                            >
                                                {floor.floorname}
                                            </button>
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        </div>

                        {/* Status Column */}
                        <div className="col-12 col-md-4">
                            <div className="d-flex flex-wrap gap-5">
                                <div
                                    className="d-flex align-items-center gap-2"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Available"
                                >
                                    <span className="w-8-px h-8-px bg-success rounded-circle"></span>
                                    <span className="text-success fw-medium">Available</span>
                                </div>
                                <div
                                    className="d-flex align-items-center gap-2"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Primary"
                                >
                                    <span className="w-8-px h-8-px bg-primary rounded-circle"></span>
                                    <span className="text-primary fw-medium">occupied</span>
                                </div>
                                <div
                                    className="d-flex align-items-center gap-2"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    title="Secondary"
                                >
                                    <span className="w-8-px h-8-px bg-secondary rounded-circle"></span>
                                    <span className="text-secondary fw-medium">Booked</span>
                                </div>
                            </div>
                        </div>

                        {/* Room Column */}
                        <div className="col-12 col-md-4">
                            <div className="overflow-auto" style={{ whiteSpace: "nowrap" }}>
                                {roomData && roomData.length > 0 ? (
                                    <ul
                                        className="nav bordered-tab border border-top-0 border-start-0 border-end-0 nav-pills"
                                        role="tablist"
                                    >
                                        {roomData.map((room, index) => (
                                            <li className="nav-item d-inline-block" role="presentation" key={room.name}>
                                                <button
                                                    className={`nav-link px-4 mx-3 py-2 ${selectedRoom === room.name ? "active" : ""
                                                        }`}
                                                    id={`room-tab-${index}`}
                                                    type="button"
                                                    role="tab"
                                                    aria-selected={selectedRoom === room.name}
                                                    onClick={() => {
                                                        getTableData(room.name);
                                                        setSelectedRoom(room.name);
                                                    }}
                                                    data-bs-toggle="tooltip"
                                                    data-bs-placement="top"
                                                    title={`Room: ${room.roomname}`}
                                                >
                                                    {room.roomname}
                                                </button>
                                            </li>
                                        ))}
                                    </ul>
                                ) : (
                                    <div className="text-muted px-4">No rooms available for this floor</div>)}
                            </div>
                        </div>

                    </div>
                </div>
            </div>

            <div className="container-fluid " style={{ marginBottom: "100px" }}>
                <div className='card h-100 p-0 mt-3 radius-12 bg-theme'>
                    <div className='card-body p-3 p-lg-5'>
                        <div className='row gy-3 gx-3 gx-lg-5 gy-lg-5  '>

                            {loading ? (
                                <PageLoader />
                            ) : tables.length === 0 ? (
                                <div className="d-flex justify-content-center align-items-center">
                                    <p>  No tables available in this room.</p>

                                </div>
                            ) : (
                                <>
                                    {tables.map((table) => (
                                        <div className="col-xxl-2 col-lg-3 col-md-4 col-6 mb-4  text-center" key={table.name}>
                                            <div className="d-inline-block">
                                                <div
                                                // className={`
                                                //         card p-3 shadow-sm radius-8 border border-white w-auto
                                                //         ${table.status === 'Available' ? "bg-tb-success" : ''}
                                                //         ${table.status === 'occupied' ? 'bg-tb-lilac' : ''}
                                                //         ${table.status === 'booked' ? "bg-tb-warning" : ''}
                                                //         `}

                                                >
                                                    <div className="p-0 position-relative">
                                                        {/* Top-right action buttons */}

                                                        <div className="cursor-pointer"
                                                            onClick={() => handleTableClick(table)}
                                                        >
                                                            <div style={{ position: 'relative', paddingTop: "20px", width: "120px" }}>
                                                                {
                                                                    table?.totalcapacity <= 2 ? (
                                                                        <img
                                                                            src="/assets/images/seat/seating-24.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 3 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-25.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 4 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-25.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 5 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-26.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 6 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-26.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 7 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-27.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 8 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-27.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 9 ? (

                                                                        <img
                                                                            src="/assets/images/seat/seating-28.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 10 && (

                                                                        <img
                                                                            src="/assets/images/seat/seating-28.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    )
                                                                }

                                                                <h6
                                                                    className={`position-absolute text-xs translate-middle text-white fw-bold text-center d-flex align-items-center justify-content-center ${table?.status === "Available" ? "bg-success-500" : table?.status === "Booked" ? "bg-warning-300" : "bg-secondary-500"}`}
                                                                    style={{
                                                                        pointerEvents: "none",
                                                                        top: "55%",
                                                                        left: "50%",
                                                                        width: "50px",
                                                                        height: "50px",
                                                                        borderRadius: "50%",

                                                                    }}
                                                                >
                                                                    {table?.tablename}
                                                                </h6>

                                                            </div>
                                                        </div>
                                                    </div>

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

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

            {/* Seat Count Modal */}
            {
                showModalTable && (
                    <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-header border-0 pb-0">
                                    <h6 className="modal-title text-lg">Enter Seat Count - {selectedTable.tablename}</h6>
                                    <button type="button" className="btn-close" onClick={() => setShowModalTable(false)}></button>
                                </div>
                                <div className="modal-body">
                                    <div className="mb-3">
                                        <label htmlFor="seatCount" className="form-label">Number of Seats</label>
                                        <input
                                            type="number"
                                            className={`form-control ${error ? 'is-invalid' : ''}`}
                                            id="seatCount"
                                            max={selectedTable?.totalcapacity}
                                            value={seatCount || ''}   // 👈 fallback if seatCount is undefined or NaN
                                            onChange={handleSeatChange}
                                        />

                                        {error ? (
                                            <div className="invalid-feedback">
                                                {error}
                                            </div>
                                        ) : (
                                            <small >
                                                Maximum capacity: {selectedTable?.totalcapacity}
                                            </small>
                                        )}
                                    </div>
                                </div>
                                <div className="modal-footer border-0 pt-0">
                                    <button type="button" className="btn btn-sm btn-outline-theme" onClick={() => setShowModalTable(false)}>Cancel</button>
                                    <button type="button" className="btn btn-sm btn-bg-theme" onClick={handleSeatSubmit}>Proceed to Menu</button>
                                </div>
                            </div>
                        </div>
                    </div>
                )
            }

            {/* 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-header border-0 pb-0">
                                    <h6 className="modal-title text-lg">{isEditMode ? "Edit Table" : "Create Table"}</h6>
                                    <button
                                        type="button"
                                        className="btn-close"
                                        onClick={resetForm}
                                    ></button>
                                </div>
                                <div className="modal-body">
                                    <form onSubmit={handleSubmit}>
                                        <div className="mb-3">
                                            <label className="form-label">Table Name</label>
                                            <input
                                                type="text"
                                                className={`form-control ${errors.tablename ? "is-invalid" : ""}`}
                                                name="tablename"
                                                value={formData.tablename || ""}
                                                onChange={handleChange}
                                            />
                                            {errors.tablename && (
                                                <div className="invalid-feedback">{errors.tablename}</div>
                                            )}
                                        </div>

                                        <div className="mb-3">
                                            <label className="form-label">Minimum Occupancy</label>
                                            <input
                                                type="number"
                                                className={`form-control ${errors.minimumoccupancy ? "is-invalid" : ""}`}
                                                name="minimumoccupancy"
                                                value={formData.minimumoccupancy || ""}
                                                onChange={handleChange}
                                            />
                                            {errors.minimumoccupancy && (
                                                <div className="invalid-feedback">{errors.minimumoccupancy}</div>
                                            )}
                                        </div>

                                        <div className="mb-3">
                                            <label className="form-label">Total Capacity</label>
                                            <input
                                                type="number"
                                                className={`form-control ${errors.totalcapacity ? "is-invalid" : ""}`}
                                                name="totalcapacity"
                                                value={formData.totalcapacity || ""}
                                                onChange={handleChange}
                                            />
                                            {errors.totalcapacity && (
                                                <div className="invalid-feedback">{errors.totalcapacity}</div>
                                            )}
                                        </div>

                                        <div className="mb-3">
                                            <label className="form-label">Description</label>
                                            <textarea
                                                className={`form-control ${errors.description ? "is-invalid" : ""}`}
                                                name="description"
                                                value={formData.description || ""}
                                                onChange={handleChange}
                                                rows="3"
                                            ></textarea>
                                            {errors.description && (
                                                <div className="invalid-feedback">{errors.description}</div>
                                            )}
                                        </div>

                                        {/* <div className="mb-3">
                                            <label className="form-label">Branch</label>
                                            <select
                                                className={`form-select ${errors.branch ? "is-invalid" : ""}`}
                                                name="branch"
                                                value={formData.branch}
                                                onChange={handleChange}
                                            >
                                                <option value="">Select Branch</option>
                                                {branchData.map((branch) => (
                                                    <option key={branch.name} value={branch.name}>
                                                        {branch.branch}
                                                    </option>
                                                ))}
                                            </select>
                                            {errors.branch && (
                                                <div className="invalid-feedback">{errors.branch}</div>
                                            )}
                                        </div> */}

                                        <div className="d-flex justify-content-end">
                                            <button type="submit" className="btn btn-bg-theme">
                                                {isEditMode ? "Update" : "Submit"}
                                            </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="d-flex justify-content-between mb-1">
                                        <h6 className="text-lg mb-0">Confirm Delete</h6>
                                        <button
                                            type="button"
                                            className="btn-close"
                                            onClick={() => setDeleteConfirm({ show: false, id: null })}
                                        ></button>
                                    </div>
                                    <p className="m-0">Are you sure you want to delete this floor?</p>
                                    <div className="d-flex justify-content-end gap-2 mt-1">
                                        <button
                                            className="btn btn-outline-danger px-14 py-6 text-sm"
                                            onClick={() => setDeleteConfirm({ show: false, id: null })}
                                        >
                                            Cancel
                                        </button>
                                        <button className="btn btn-danger px-14 py-6 text-sm" onClick={handleDelete}>
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                )
            }
        </>
    );
};


const TableOrder = (() => {
    return (
        <MasterLayout>
            {/* Breadcrumb */}
            <Breadcrumb title='Table' />
            <Suspense fallback={<PageLoader />}>
                <TableOrderInner />
            </Suspense>
        </MasterLayout>
    )
})
export default TableOrder;
