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

const FloorComponent = ({ floorData, getFloor }) => {

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

    // const searchParams = useSearchParams()
    // const restaurantbranch = searchParams.get('restaurantbranch')
    // const RestaruntBranch = restaurantbranch

    const [showFloorModal, setShowFloorModal] = useState(false);
    const [isFloorEditMode, setIsFloorEditMode] = useState(false);
    const [selectedFloorId, setSelectedFloorId] = useState(null);
    const [floorFormData, setFloorFormData] = useState({
        floorname: "",
        description: "",
    });
    const [floorErrors, setFloorErrors] = useState({});
    const [floorDeleteConfirm, setFloorDeleteConfirm] = 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]);

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

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

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

        const body = {
            // ...(isFloorEditMode && { name: selectedFloorId }), // only adds `name` if editing
            floorname: floorFormData?.floorname,
            description: floorFormData?.description,
            restaurantbranch: restaruntBranch
        };
        try {
            if (isFloorEditMode) {
                await client.put(`/Dine360 Floor/${selectedFloorId}`, body);
            } else {
                await client.post(`/Dine360 Floor`, body);
            }
            getFloor();
            resetFloorForm();
        } 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("UniqueValidationError") ||
                error?.response?.data?.message?.includes("UniqueValidationError entry")
            ) {
                alert("Floor with this name already exists. Please use a different name.");
            } else {
                alert("An error occurred. Please try again.");
            }
        }
    };

    const resetFloorForm = () => {
        setFloorFormData({
            floorname: "", description: "",
        });
        setShowFloorModal(false);
        setIsFloorEditMode(false);
        setSelectedFloorId(null);
        setFloorErrors({});
    };

    const handleFloorEdit = (floor) => {
        setIsFloorEditMode(true);
        setSelectedFloorId(floor.name);
        setFloorFormData({
            floorname: floor.floorname || "",
            description: floor.description || "",
        });
        setShowFloorModal(true);
    };

    const handleFloorDelete = async () => {
        try {
            await client.delete(`/Dine360 Floor/${floorDeleteConfirm.id}`);
            setFloorDeleteConfirm({ show: false, id: null });
            getFloor();
        } 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 ");
            }
        }
    };

    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">Floor</h6>
                        <button
                            type="button"
                            className="btn btn-bg-theme radius-8 px-20 py-11"
                            onClick={() => setShowFloorModal(true)}
                        >
                            Create
                        </button>
                    </div>

                    <div className="row gy-3 gx-3 gx-lg-5 gy-lg-5 justify-content-center">
                        {
                            floorData?.lenght === 0 ? (
                                <PageNoData />
                            ) : (
                                <>
                                    {floorData.map((floor, index) => {
                                        const gradientClass = gradientClasses[index % gradientClasses.length];
                                        return (
                                            <div className="col-xxl-3 col-lg-4 col-sm-6" key={floor.name}>
                                                <div className={`card p-3 shadow-2 radius-8 h-100 bg-theme border border-white position-relative`}>

                                                    {/* Top-right action buttons */}
                                                    <div className="position-absolute top-0 end-0 me-1 mt-1 ">
                                                        <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();
                                                                            handleFloorEdit(floor);
                                                                        }}
                                                                    > <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();
                                                                            setFloorDeleteConfirm({ show: true, id: floor.name });
                                                                        }}
                                                                    >
                                                                        <Icon
                                                                            icon='fluent:delete-24-regular'
                                                                            className='menu-icon'
                                                                        />
                                                                        Delete
                                                                    </Link>
                                                                </li>
                                                            </ul>

                                                        </div>

                                                    </div>

                                                    {/* Centered content */}
                                                    <Link href={`/admin/pos/room?restaurantbranch=${restaruntBranch}&floorname=${floor.name}`} className="text-decoration-none text-dark">
                                                        <div className="card-body text-center d-flex flex-column justify-content-center align-items-center p-0 h-100">
                                                            <h6 className="text-lg mb-0">{floor.floorname}</h6>
                                                            <p className="mb-0  text-sm">{floor.description}</p>
                                                        </div>
                                                    </Link>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </>
                            )
                        }

                    </div>

                </div>
            </div>

            {/* Create/Edit Modal */}
            {showFloorModal && (
                <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">
                                    {isFloorEditMode ? "Edit Floor" : "Create Floor"}
                                </h6>
                                <button type="button" className="btn-close" onClick={resetFloorForm}></button>
                            </div>
                            <div className="modal-body">
                                <form onSubmit={handleFloorSubmit}>
                                    <div className="mb-3">
                                        <label className="form-label">Floor Name</label>
                                        <input
                                            type="text"
                                            className={`form-control ${floorErrors.floorname ? "is-invalid" : ""}`}
                                            name="floorname"
                                            value={floorFormData.floorname}
                                            onChange={handleFloorChange}
                                        />
                                        {floorErrors.floorname && (
                                            <div className="invalid-feedback">{floorErrors.floorname}</div>
                                        )}
                                    </div>

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

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

            {/* Delete Confirmation Modal */}
            {floorDeleteConfirm.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={() => setFloorDeleteConfirm({ 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={() => setFloorDeleteConfirm({ show: false, id: null })}
                                    >
                                        Cancel
                                    </button>
                                    <button className="btn btn-danger px-14 py-6 text-sm" onClick={handleFloorDelete}>
                                        Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default FloorComponent;
