"use client";
import React, { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import MasterLayout from "@/masterLayout/MasterLayout";
import client from "@auth";
import { gradientClasses } from "@utils/constant.utils";
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 FloorSectionPageInner = () => {
    // const params = useParams();
    const router = useRouter()
    const searchParams = useSearchParams()
    const floorName = decodeURIComponent(searchParams.get("floorname"))

    // const restaurantbranch = params?.restaurantbranch;
    // const RestaruntBranch = restaurantbranch
    // const floorName = decodeURIComponent(params.name);
    const [roomData, setRoomData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [showRoomModal, setShowRoomModal] = useState(false);
    const [editRoomMode, setEditRoomMode] = useState(false);
    const [editingRoomId, setEditingRoomId] = useState(null);
    const [roomFormData, setRoomFormData] = useState({
        roomname: "",
        description: "",
    });
    const [roomErrors, setRoomErrors] = useState({});
    const [roomDeleteConfirm, setRoomDeleteConfirm] = 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 (floorName) {
            getRoomData();
        }
    }, [floorName]);

    const getRoomData = async () => {
        try {
            setLoading(true);
            const roomRes = await client.get(
                `/Dine360%20Room?fields=["*"]&limit_page_length=100&filters=[["floor","=","${floorName}"]]`
            );
            setRoomData(roomRes?.data?.data || []);
        } catch (error) {
            console.error("Error fetching data:", error);
        } finally {
            setLoading(false);
        }
    };


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

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

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

        const body = {
            roomname: roomFormData.roomname,
            description: roomFormData.description,
            floor: floorName,
            restaurantbranch: restaruntBranch
        };

        try {
            if (editRoomMode) {
                await client.put(`/Dine360 Room/${editingRoomId}`, body);
            } else {
                await client.post(`/Dine360 Room`, body);
            }
            getRoomData();
            resetRoomForm();
        } catch (error) {
            console.error("❌ Submission error:", error);
        }
    };

    const handleEdit = (room) => {
        setRoomFormData({
            roomname: room.roomname || "",
            description: room.description || "",
            // branch: room.branch || "",
        });
        setEditingRoomId(room.name);
        setEditRoomMode(true);
        setShowRoomModal(true);
    };

    const handleRoomDelete = async () => {
        try {
            await client.delete(`/Dine360 Room/${roomDeleteConfirm?.id}`);
            setRoomDeleteConfirm({ show: false, id: null });
            getRoomData();
        } 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");
            }
        }
    };

    const resetRoomForm = () => {
        setRoomFormData({ roomname: "", description: "", });
        setRoomErrors({});
        setEditRoomMode(false);
        setEditingRoomId(null);
        setShowRoomModal(false);
    };

    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="d-flex justify-content-between align-items-center mb-3">
                        <h6 className="mb-0">Room</h6>
                        <button
                            type="button"
                            className="btn btn-bg-theme radius-8 px-20 py-11"
                            onClick={() => setShowRoomModal(true)}
                        >
                            Create
                        </button>
                    </div>

                    <div className="row gy-3 gx-3 gx-lg-5 gy-lg-5 justify-content-center">
                        {loading ? (
                            <PageLoader />
                        ) : roomData?.length === 0 ? (
                            <PageNoData />
                        ) : (
                            roomData?.map((room, index) => {
                                const gradientClass = gradientClasses[index % gradientClasses.length];
                                return (
                                    <div className="col-xxl-3 col-lg-4 col-sm-6 cursor-pointer" key={room?.name}>
                                        <div className={`card p-3 shadow-2 radius-8 h-100 bg-theme border border-white position-relative`}>
                                            <div className="position-absolute top-0 end-0 me-1 mt-1 d-flex gap-2">

                                                <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(room)
                                                                }}
                                                            >
                                                                <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();
                                                                    setRoomDeleteConfirm({ show: true, id: room.name })
                                                                }}
                                                            >  <Icon
                                                                    icon='fluent:delete-24-regular'
                                                                    className='menu-icon'
                                                                />
                                                                Delete
                                                            </Link>
                                                        </li>
                                                    </ul>

                                                </div>

                                                {/* <button
                                                        className="bg-success-focus text-success-600 bg-hover-success-200 fw-medium w-40-px h-40-px d-flex justify-content-center align-items-center rounded-circle"
                                                        onClick={() => handleEdit(room)}
                                                    >
                                                        <Icon icon='lucide:edit' className='menu-icon' />
                                                    </button>
                                                    <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"
                                                        onClick={() => setRoomDeleteConfirm({ show: true, id: room.name })}
                                                    >
                                                        <Icon
                                                            icon='fluent:delete-24-regular'
                                                            className='menu-icon'
                                                        />
                                                    </button> */}
                                            </div>

                                            <div className="card-body text-center p-0">
                                                <Link href={`/admin/pos/dine-in?restaurantbranch=${restaruntBranch}&roomname=${room?.name}&floor=${floorName}`}>
                                                    <h6 className="text-lg mt-0 mb-0">{room?.roomname}</h6>
                                                    <p className="mb-0 text-sm">{room?.description}</p>
                                                </Link>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>
                </div>
            </div>

            {/* Modal */}
            {showRoomModal && (
                <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">{editRoomMode ? "Edit Room" : "Create Room"}</h6>
                                <button
                                    type="button"
                                    className="btn-close"
                                    onClick={resetRoomForm}
                                ></button>
                            </div>
                            <div className="modal-body">
                                <form onSubmit={handleRoomSubmit}>
                                    <div className="mb-3">
                                        <label className="form-label">Room Name</label>
                                        <input
                                            type="text"
                                            className={`form-control ${roomErrors.roomname ? "is-invalid" : ""}`}
                                            name="roomname"
                                            value={roomFormData.roomname}
                                            onChange={handleRoomChange}
                                        />
                                        {roomErrors.roomname && (
                                            <div className="invalid-feedback">{roomErrors.roomname}</div>
                                        )}
                                    </div>

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



                                    <div className="d-flex justify-content-end">
                                        <button type="submit" className="btn btn-bg-theme">
                                            {editRoomMode ? "Update" : "Submit"}
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Delete Confirmation Modal */}
            {roomDeleteConfirm.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={() => setRoomDeleteConfirm({ show: false, id: null })}
                                    ></button>
                                </div>
                                <p className="mb-0">Are you sure you want to delete this Room?</p>
                                <div className="d-flex justify-content-end gap-2 mt-1">
                                    <button
                                        className="btn btn-outline-danger-600  px-14 py-6 text-sm"
                                        onClick={() => setRoomDeleteConfirm({ show: false, id: null })}
                                    >
                                        Cancel
                                    </button>
                                    <button className="btn btn-danger  px-14 py-6 text-sm" onClick={handleRoomDelete}>
                                        Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>

    );
};

const FloorSectionPage = (() => {
    return (
        <MasterLayout>
            <Breadcrumb title="Floor Section" />
            <Suspense fallback={<PageLoader />}>
                <FloorSectionPageInner />
            </Suspense>
        </MasterLayout>
    )
})

export default FloorSectionPage;
