"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";
import axios from "axios";
import { Baseurl } from "@utils/BaseUrl.utils";


const DineInInner = () => {

    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: "",
        enable: 0,
    });
    const [errors, setErrors] = 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(() => {
        getTableData();
    }, [roomName]);

    const getTableData = async () => {
        try {
            setLoading(true)
            const tableRes = await client.get(`/Dine360%20Table?fields=[\"*\"]&limit_page_length=100&filters=[["room","=","${roomName}"]]`);
            console.log("tableRes", tableRes);
            setTables(tableRes.data.data);
            setLoading(false)
        } catch (error) {
            console.error("Error fetching data:", error);
            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(
                `/admin/pos/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 {
                const createTable = await client.post(`/Dine360 Table`, Body);

                if (formData.enable == 1) {
                    const tableName = createTable?.data?.data?.name;
                    const RestaurantBranch = createTable?.data?.data?.restaurantbranch;
                    const AutoCreateBody = {
                        table: tableName,
                        restaurantbranch: RestaurantBranch,
                        enabled: formData.enable, // Uncomment if needed
                    };

                    try {
                        await axios.post(`${Baseurl}/Add-Table-To-Day`, AutoCreateBody);
                    } catch (apiError) {
                        console.error("Error while auto-creating table for the day:", apiError);
                        alert("Table created, but failed to assign it to the day.");
                    }
                }

            }
            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: "",
            enable: 0,
        });
        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="container-fluid " style={{ marginBottom: "100px" }}>
                <div className='card h-100 p-0 radius-12'>
                    <div className='card-body p-3 p-lg-5'>
                        <div className='row gy-3 gx-3 gx-lg-5 gy-lg-5  '>
                            <div className="d-flex justify-content-between align-items-center mb-3">
                                <h6 className="mb-0">Table</h6>
                                <button
                                    type="button"
                                    className="btn btn-bg-theme radius-8 px-20 py-11"
                                    onClick={() => setShowModal(true)}
                                >
                                    Create
                                </button>
                            </div>
                            {loading ? (
                                <PageLoader />
                            ) : tables.length === 0 ? (
                                <PageNoData />
                            ) : (
                                <>
                                    {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="card-body p-0 position-relative">
                                                        {/* Top-right action buttons */}
                                                        <div className="position-absolute  " style={{ zIndex: 1, top: "-15px", right: "-15px" }}>

                                                            <div className='dropdown'>
                                                                <button
                                                                    className='btn px-1 py-1 d-flex align-items-center text-primary-light'
                                                                    type='button'
                                                                    data-bs-toggle='dropdown'
                                                                    aria-expanded='false'
                                                                >
                                                                    <Icon icon='entypo:dots-three-vertical' className='menu-icon' />
                                                                </button>
                                                                <ul className='dropdown-menu'>
                                                                    <li>
                                                                        <Link
                                                                            href="#"
                                                                            className='dropdown-item px-16 py-8 d-flex align-items-center gap-2 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900'
                                                                            onClick={(e) => {
                                                                                e.preventDefault();
                                                                                handleEdit(table)
                                                                            }}
                                                                        >
                                                                            <Icon icon='lucide:edit' className='menu-icon' />
                                                                            Edit
                                                                        </Link>
                                                                    </li>
                                                                    <li>
                                                                        <Link
                                                                            href="#"
                                                                            className='dropdown-item px-16 py-8 d-flex align-items-center gap-2 rounded text-secondary-light bg-hover-neutral-200 text-hover-neutral-900'
                                                                            onClick={(e) => {
                                                                                e.preventDefault();
                                                                                setDeleteConfirm({ show: true, id: table.name })
                                                                            }}
                                                                        >  <Icon
                                                                                icon='fluent:delete-24-regular'
                                                                                className='menu-icon'
                                                                            />
                                                                            Delete
                                                                        </Link>
                                                                    </li>
                                                                </ul>

                                                            </div>


                                                        </div>
                                                        <div
                                                        //  onClick={() => handleTableClick(table)}
                                                        >
                                                            <div style={{ position: 'relative', paddingTop: "20px" }}>
                                                                {
                                                                    table?.totalcapacity <= 2 ? (
                                                                        <img
                                                                            src="/assets/images/seat/seating-02.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-04.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-04.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-06.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-06.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-08.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-08.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-10.png"
                                                                            alt="table"
                                                                            className={classNames(
                                                                                'w-100 h-100 object-fit-cover radius-8',
                                                                                { 'grayscale': table.status === 'booked' }
                                                                            )}
                                                                        />
                                                                    ) : table?.totalcapacity == 10 && (

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

                                                                <h6
                                                                    className="position-absolute translate-middle text-sm fw-bold text-center"
                                                                    style={{ pointerEvents: 'none', top: "2px", left: "20px" }}
                                                                >
                                                                    {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</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-danger" onClick={() => setShowModalTable(false)}>Cancel</button>
                                <button type="button" className="btn btn-sm btn-danger-500" 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> */}
                                    {
                                        !isEditMode && (
                                            <div className="mb-3 form-check d-flex align-items-center gap-2">
                                                <input
                                                    type="checkbox"
                                                    className="form-check-input"
                                                    id="enableTable"
                                                    name="enable"
                                                    checked={formData.enable === 1}
                                                    onChange={(e) =>
                                                        setFormData({
                                                            ...formData,
                                                            enable: e.target.checked ? 1 : 0,
                                                        })
                                                    }
                                                />
                                                <label className="form-check-label" htmlFor="enableTable">
                                                    Auto Generate Day table creation
                                                </label>
                                            </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 DineIn = (() => {
    return (
        <MasterLayout>
            {/* Breadcrumb */}
            <Breadcrumb title='Table' />
            <Suspense fallback={<PageLoader />}>
                <DineInInner />
            </Suspense>
        </MasterLayout>
    )
})
export default DineIn;
