"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 SidesCategoryComponent = ({ sidesCategoryData, getSidesCategory }) => {

    const router = useRouter()
    const params = useParams();
    const [showSidesCategoryModal, setShowSidesCategoryModal] = useState(false);
    const [isSidesCategoryEditMode, setIsSidesCategoryEditMode] = useState(false);
    const [selectedSidesCategoryId, setSelectedSidesCategoryId] = useState(null);
    const [sidesCategoryFormData, setSidesCategoryFormData] = useState({
        sidesCategoryname: "",
        description: "",
    });
    const [sidesCategoryErrors, setSidesCategoryErrors] = useState({});
    const [sidesCategoryDeleteConfirm, setSidesCategoryDeleteConfirm] = 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 handleSidesCategoryChange = (e) => {
        const { name, value } = e.target;
        setSidesCategoryFormData((prev) => ({ ...prev, [name]: value }));
    };

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

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

        const body = {
            // ...(isSidesCategoryEditMode && { name: selectedFloorId }), // only adds `name` if editing
            sidecategoryname: sidesCategoryFormData?.sidesCategoryname,
            description: sidesCategoryFormData?.description,
            restaurantbranch: restaruntBranch
        };
        try {
            if (isSidesCategoryEditMode) {
                await client.put(`/Dine360%20Food%20Sides%20Category/${selectedSidesCategoryId}`, body);
            } else {
                await client.post(`/Dine360%20Food%20Sides%20Category`, body);
            }
            getSidesCategory();
            resetForm();
        } catch (error) {
            if (
                error?.response?.data?.exception?.includes("DuplicateEntryError") ||
                error?.response?.data?.message?.includes("Duplicate entry")
            ) {
                alert("SidesCategory 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("SidesCategory with this name already exists. Please use a different name.");
            } else {
                alert("An error occurred. Please try again.");
            }
        }
    };

    const resetForm = () => {
        setSidesCategoryFormData({
            sidesCategoryname: "", description: "",
        });
        setShowSidesCategoryModal(false);
        setIsSidesCategoryEditMode(false);
        setSelectedSidesCategoryId(null);
        setSidesCategoryErrors({});
    };

    const handleEdit = (sidesCategory) => {
        setIsSidesCategoryEditMode(true);
        setSelectedSidesCategoryId(sidesCategory.name);
        setSidesCategoryFormData({
            sidesCategoryname: sidesCategory.sidecategoryname || "",
            description: sidesCategory.description || "",
        });
        setShowSidesCategoryModal(true);
    };

    const handleDelete = async () => {
        try {
            await client.delete(`/Dine360%20Food%20Sides%20Category/${sidesCategoryDeleteConfirm.id}`);
            setSidesCategoryDeleteConfirm({ show: false, id: null });
            getSidesCategory();
        } catch (error) {
            if (
                error?.response?.data?.exception?.includes("DuplicateEntryError") ||
                error?.response?.data?.message?.includes("Duplicate entry")
            ) {
                alert("SidesCategory 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 SidesCategory 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">SidesCategory</h6>
                        <button
                            type="button"
                            className="btn btn-bg-theme radius-8 px-20 py-11"
                            onClick={() => setShowSidesCategoryModal(true)}
                        >
                            Create
                        </button>
                    </div>

                    <div className="row gy-3 gx-3 gx-lg-5 gy-lg-5 justify-content-center">
                        {
                            sidesCategoryData?.lenght === 0 ? (
                                <PageNoData />
                            ) : (
                                <>
                                    {sidesCategoryData.map((sidesCategory, index) => {
                                        const gradientClass = gradientClasses[index % gradientClasses.length];
                                        return (
                                            <div className="col-xxl-3 col-lg-4 col-sm-6" key={sidesCategory.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();
                                                                            handleEdit(sidesCategory);
                                                                        }}
                                                                    > <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();
                                                                            setSidesCategoryDeleteConfirm({ show: true, id: sidesCategory.name });
                                                                        }}
                                                                    >
                                                                        <Icon
                                                                            icon='fluent:delete-24-regular'
                                                                            className='menu-icon'
                                                                        />
                                                                        Delete
                                                                    </Link>
                                                                </li>
                                                            </ul>

                                                        </div>

                                                    </div>

                                                    {/* Centered content */}
                                                    <Link href={`/admin/pos/sides?restaurantbranch=${restaruntBranch}&sidescategoryname=${sidesCategory.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">{sidesCategory.sidecategoryname}</h6>
                                                            <p className="mb-0  text-sm">{sidesCategory.description}</p>
                                                        </div>
                                                    </Link>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </>
                            )
                        }

                    </div>

                </div>
            </div>

            {/* Create/Edit Modal */}
            {showSidesCategoryModal && (
                <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">
                                    {isSidesCategoryEditMode ? "Edit SidesCategory" : "Create SidesCategory"}
                                </h6>
                                <button type="button" className="btn-close" onClick={resetForm}></button>
                            </div>
                            <div className="modal-body">
                                <form onSubmit={handleSidesCategorySubmit}>
                                    <div className="mb-3">
                                        <label className="form-label">SidesCategory Name</label>
                                        <input
                                            type="text"
                                            className={`form-control ${sidesCategoryErrors.sidesCategoryname ? "is-invalid" : ""}`}
                                            name="sidesCategoryname"
                                            value={sidesCategoryFormData.sidesCategoryname}
                                            onChange={handleSidesCategoryChange}
                                        />
                                        {sidesCategoryErrors.sidesCategoryname && (
                                            <div className="invalid-feedback">{sidesCategoryErrors.sidesCategoryname}</div>
                                        )}
                                    </div>

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

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

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

            {/* Delete Confirmation Modal */}
            {sidesCategoryDeleteConfirm.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={() => setSidesCategoryDeleteConfirm({ show: false, id: null })}
                                    ></button>
                                </div>
                                <p className="m-0">Are you sure you want to delete this sidesCategory?</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={() => setSidesCategoryDeleteConfirm({ 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>
            )}
        </div>
    );
};

export default SidesCategoryComponent;
