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

const SidesPageInner = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const sidesCategoryName = decodeURIComponent(searchParams.get("sidescategoryname"));

    const [showModal, setShowModal] = useState(false);
    const [editMode, setEditMode] = useState(false);
    const [editingRoomId, setEditingRoomId] = useState(null);
    const [roomData, setRoomData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [formData, setFormData] = useState({
        sidename: "",
        description: "",
        price: "",
        item_image: null,
    });
    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(() => {
        if (sidesCategoryName) {
            getSideData();
        }
    }, [sidesCategoryName]);

    const getSideData = async () => {
        try {
            setLoading(true);
            setError(null);
            const roomRes = await client.get(
                `/Dine360%20Food%20Sides?fields=[%22*%22]&limit_page_length=100&filters=[["sidecategoryid","=","${sidesCategoryName}"]]`
            );
            setRoomData(roomRes?.data?.data || []);
        } catch (error) {
            console.error("Error fetching data:", error);
            setError(error?.message || "Failed to fetch side data");
        } finally {
            setLoading(false);
        }
    };

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

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

        if (!formData.sidename.trim()) newErrors.sidename = "Side Name is required";
        if (!formData.description.trim()) newErrors.description = "Description is required";
        if (!formData.price) newErrors.price = "Price is required";

        if (!editMode && !formData.item_image) {
            newErrors.item_image = "Item image is required";
        }

        setErrors(newErrors);
        if (Object.keys(newErrors).length > 0) return;

        const body = {
            sidename: formData.sidename,
            description: formData.description,
            price: parseFloat(formData.price),
            sidecategoryid: sidesCategoryName,
            restaurantbranch: restaruntBranch,
        };

        try {
            let itemId;

            if (editMode) {
                itemId = editingRoomId;

                // Step 2: Upload new image if updated
                if (formData.item_image?.startsWith("data:image")) {
                    const uploadPath = await uploadImage(formData.item_image, "Dine360 Food Sides", itemId);
                    body.item_image = uploadPath;
                }

                // Step 3: Update
                await client.put(`/Dine360%20Food%20Sides/${itemId}`, body);
            } else {
                // Step 1: Create without image
                const res = await client.post(`/Dine360%20Food%20Sides`, body);
                itemId = res?.data?.data?.name;

                // Step 2: Upload image
                if (formData.item_image) {
                    const uploadPath = await uploadImage(formData.item_image, "Dine360 Food Sides", itemId);

                    // Step 3: Update with image
                    await client.put(`/Dine360%20Food%20Sides/${itemId}`, { item_image: uploadPath });
                }
            }

            getSideData();
            resetForm();
        } catch (error) {
            console.error("❌ Submission error:", error);
            const backendError = error?.response?.data?.exception || "";

            if (backendError.includes("Data too long for column 'item_image'")) {
                setErrors((prev) => ({
                    ...prev,
                    item_image: "Data too long for column 'item_image'",
                }));
            } else if (error?.response?.status === 500) {
                alert("Server error occurred. Please try again later.");
            } else {
                alert("Submission failed. Please try again.");
            }
        }
    };

    const uploadImage = async (base64Data, doctype, docname) => {
        const blob = await (await fetch(base64Data)).blob();
        const form = new FormData();
        form.append("file", blob, "side.jpg");
        form.append("is_private", "0");
        form.append("doctype", doctype);
        form.append("docname", docname);

        const res = await fetch(`${ImageBase}/api/method/upload_file`, {
            method: "POST",
            headers: {
                "Authorization": "token 482beca79d9c005:b8778f51fcca82b",
                // ❌ Don't set Content-Type when using FormData — let the browser set it
            },
            body: form,
        });

        const result = await res.json();

        if (!result.message?.file_url) throw new Error("Upload failed");
        return result.message.file_url;
    };


    const handleEdit = (room) => {
        setFormData({
            sidename: room.sidename || "",
            description: room.description || "",
            price: room.price || "",
            item_image: room.item_image || null,
        });
        setEditingRoomId(room.name);
        setEditMode(true);
        setShowModal(true);
    };

    const handleDelete = async () => {
        try {
            await client.delete(`/Dine360%20Food%20Sides/${deleteConfirm?.id}`);
            setDeleteConfirm({ show: false, id: null });
            getSideData();
        } catch (error) {
            alert("Error deleting. It might be linked to other data.");
        }
    };

    const resetForm = () => {
        setFormData({
            sidename: "",
            description: "",
            price: "",
            item_image: null,
        });
        setErrors({});
        setEditMode(false);
        setEditingRoomId(null);
        setShowModal(false);
    };

    return (
        <div className="container-fluid" style={{ marginBottom: "100px" }}>
            {/* Header + Create Button */}
            <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">Sides</h6>
                        <button className="btn btn-bg-theme radius-8 px-20 py-11" onClick={() => setShowModal(true)}>
                            Create
                        </button>
                    </div>

                    {/* Grid */}
                    <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" data-bs-toggle="dropdown">
                                                        <Icon icon="entypo:dots-three-vertical" />
                                                    </button>
                                                    <ul className="dropdown-menu">
                                                        <li>
                                                            <Link href="#" className="dropdown-item" onClick={(e) => {
                                                                e.preventDefault();
                                                                handleEdit(room);
                                                            }}>
                                                                <Icon icon="lucide:edit" /> Edit
                                                            </Link>
                                                        </li>
                                                        <li>
                                                            <Link href="#" className="dropdown-item" onClick={(e) => {
                                                                e.preventDefault();
                                                                setDeleteConfirm({ show: true, id: room.name });
                                                            }}>
                                                                <Icon icon="fluent:delete-24-regular" /> Delete
                                                            </Link>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div className="card-body text-center p-0">
                                                <h6 className="text-lg mt-0 mb-0">{room?.sidename}</h6>
                                                <p className="mb-0 text-sm">{room?.description}</p>
                                            </div>
                                        </div>
                                    </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">{editMode ? "Edit Side" : "Create Side"}</h6>
                                <button type="button" className="btn-close" onClick={resetForm}></button>
                            </div>
                            <div className="modal-body">
                                <form onSubmit={handleSubmit}>
                                    {/* Form fields */}
                                    <div className="mb-3">
                                        <label className="form-label">Side Name</label>
                                        <input type="text" className={`form-control ${errors.sidename ? "is-invalid" : ""}`} name="sidename" value={formData.sidename} onChange={handleChange} />
                                        {errors.sidename && <div className="invalid-feedback">{errors.sidename}</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}></textarea>
                                        {errors.description && <div className="invalid-feedback">{errors.description}</div>}
                                    </div>

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

                                    <div className="mb-3">
                                        <label className="form-label">Item Image</label>
                                        <div className="d-flex align-items-center gap-3">
                                            <input type="file" accept="image/*" className={`form-control ${errors.item_image ? "is-invalid" : ""}`} style={{ maxWidth: "350px" }} onChange={(e) => {
                                                const file = e.target.files[0];
                                                if (!file) return;

                                                if (!file.type.startsWith("image/")) {
                                                    setErrors(prev => ({ ...prev, item_image: "Only image files are allowed." }));
                                                    return;
                                                }

                                                if (file.size / (1024 * 1024) > 1) {
                                                    setErrors(prev => ({ ...prev, item_image: "Max size 1MB" }));
                                                    return;
                                                }

                                                const reader = new FileReader();
                                                reader.onloadend = () => {
                                                    setFormData(prev => ({ ...prev, item_image: reader.result }));
                                                    setErrors(prev => ({ ...prev, item_image: null }));
                                                };
                                                reader.readAsDataURL(file);
                                            }} />
                                            {formData.item_image && (
                                                <div style={{ position: "relative", width: "60px", height: "60px" }}>
                                                    <img src={formData.item_image} alt="preview" className="img-thumbnail" style={{ objectFit: "cover" }} />
                                                    <button type="button" className="btn btn-sm btn-danger position-absolute top-0 end-0 p-1 pt-0 pb-0" onClick={() => setFormData(prev => ({ ...prev, item_image: null }))}>×</button>
                                                </div>
                                            )}
                                        </div>
                                        {errors.item_image && <div className="invalid-feedback d-block">{errors.item_image}</div>}
                                    </div>

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

            {/* Delete 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>Are you sure you want to delete this item?</p>
                                <div className="d-flex justify-content-end gap-2 mt-1">
                                    <button className="btn btn-outline-danger" onClick={() => setDeleteConfirm({ show: false, id: null })}>Cancel</button>
                                    <button className="btn btn-danger" onClick={handleDelete}>Delete</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

const SidesPage = () => (
    <MasterLayout>
        <Breadcrumb title="Sides Management" />
        <Suspense fallback={<PageLoader />}>
            <SidesPageInner />
        </Suspense>
    </MasterLayout>
);

export default SidesPage;
