"use client";
import { useEffect, useState } from "react";

// Mapping constants provided by the client — numeric codes -> human-friendly keys
const BookingSubSource: Record<number, string> = {
    2: "Expedia",
    328: "Expedia",
};

const CHANNELS: Record<number, string> = {
    100: "DIRECT",
    101: "OTA",
    102: "OFFLINE_AGENT",
    103: "GDS",
    104: "CORPORATE",
    105: "BOOKING_ENGINE",
    106: "META",
};

const SUB_CHANNELS: Record<number, string> = {
    111: "AGENT_CONNEKT",
    110: "DJUBO_DIRECT",
    109: "WEBSITE",
    108: "TRIVAGO",
    107: "GOOGLE_ENGINE_ARI",
    106: "GOOGLE_ENGINE_META",
    105: "TRIP_ADVISOR_CPA",
    104: "TRIP_ADVISOR_CPC",
    103: "TRIP_ADVISOR",
    102: "DIRECT_EMAIL",
    101: "DIRECT_PHONE",
    100: "DIRECT_WALK_IN",
};

const STAY_STATUS: Record<number, string> = {
    0: "NO_STAY",
    1: "CHECK_IN",
    2: "CHECK_OUT",
    3: "BOTH_CHECK_IN_OUT",
    4: "CHECK_OUT_AND_RELEASED_ROOM_NIGHTS",
};

const PAYMENT_CODES: Record<number, string> = {
    0: "PAYMENT_FUNDING_UNKNOWN",
    1: "PAYMENT_FUNDING_NET_BANKING",
    2: "PAYMENT_FUNDING_DEBIT_CARD",
    3: "PAYMENT_FUNDING_CREDIT_CARD",
    4: "PAYMENT_FUNDING_COD",
    5: "PAYMENT_FUNDING_CASH_CARD",
    6: "PAYMENT_FUNDING_EMI",
    7: "PAYMENT_FUNDING_IVR",
    8: "PAYMENT_FUNDING_UPI",
    9: "PAYMENT_FUNDING_ALIPAY",
    10: "PAYMENT_FUNDING_WECHAT",
    11: "PAYMENT_FUNDING_GCASH",
    12: "PAYMENT_FUNDING_HELLO_MONEY",
    13: "PAYMENT_FUNDING_UNION_PAY",
    14: "PAYMENT_FUNDING_HOME_CREDIT",
    15: "PAYMENT_FUNDING_QR_PH",
};

const BOOKING_STATUS: Record<number, string> = {
    1: "CONFIRMED",
    2: "ON_HOLD",
    3: "CANCELLED",
    4: "NO_SHOW",
    5: "ACTIVE",
    6: "INACTIVE",
};

const MEAL_PLAN: Record<number, string> = {
    1: "EP",
    2: "CP",
    3: "MAP",
    4: "AP",
    5: "MAPI",
    6: "API",
};

// Reverse maps for string -> numeric support
const BOOKING_STATUS_REVERSE: Record<string, number> = {
    confirmed: 1,
    confirm: 1,
    "on hold": 2,
    hold: 2,
    cancelled: 3,
    canceled: 3,
    cancel: 3,
};

const MEAL_PLAN_REVERSE: Record<string, number> = {
    EP: 1,
    CP: 2,
    MAP: 3,
    AP: 4,
    MAPI: 5,
    API: 6,
};

/**
 * Attempt to parse numeric-like values from a set of candidate keys.
 * FIXED: now tolerates strings with commas/currency symbols and strips non-numeric characters.
 */
function getNumeric(item: any, ...keys: string[]) {
    for (const k of keys) {
        if (!item || !(k in item)) continue;
        const raw = item[k];
        if (raw === null || raw === undefined || raw === "") continue;
        // Accept numbers or numeric-like strings (strip non-numeric except . and -)
        if (typeof raw === "number") {
            if (!Number.isNaN(raw)) return raw;
            continue;
        }
        const cleaned = String(raw).replace(/[^0-9.-]/g, "");
        if (cleaned === "") continue;
        const n = Number(cleaned);
        if (!Number.isNaN(n)) return n;
    }
    return undefined;
}

/**
 * Retrieve first non-empty string candidate.
 */
function getString(item: any, ...keys: string[]) {
    for (const k of keys) {
        if (!item || !(k in item)) continue;
        const v = item[k];
        if (v === null || v === undefined) continue;
        const s = String(v).trim();
        if (s !== "") return s;
    }
    return undefined;
}

export function useActiveVillaBookings() {
    const [bookings, setBookings] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<Error | null>(null);

    useEffect(() => {
        async function fetchBookings() {
            try {
                const SCRIPT_URL =
                    "https://script.google.com/macros/s/AKfycbzzu8kft6pqinOA3QOku8A56Vb-0pTGkkP2V6PRiTV3EBD05oJ185bwtbsAC9WgynJH7Q/exec";
                const res = await fetch(SCRIPT_URL);
                if (!res.ok) throw new Error("Failed to fetch villa bookings");

                const data = await res.json();

                const formatted = data.map((item: any, index: number) => {
                    // read numeric codes from common candidate keys
                    let channelCode = getNumeric(
                        item,
                        "Channel Code",
                        "Channel",
                        "channel",
                        "channel_code",
                        "Source Code",
                        "Source Code Number",
                        "Channel Id",
                        "Channel ID",
                        // some payloads provide channel as `Booking source` (numeric code)
                        "Booking source",
                        "booking source",
                    );
                    // Preserve original channel code for later decisions
                    const originalChannelCode = channelCode;
                    // Merge DIRECT (100) into OFFLINE_AGENT (102) so direct bookings
                    // appear under the offline booking card in the Booking Source section.
                    if (channelCode === 100) {
                        channelCode = 102;
                    }
                    const subChannelCode = getNumeric(
                        item,
                        "Sub Channel",
                        "Sub-Channel",
                        "SubChannel",
                        "sub_channel",
                        "Sub Channel Code",
                        "Sub Channel Id",
                    );
                    const stayStatusCode = getNumeric(item, "Stay Status", "Stay Status Code", "stay_status");
                    const paymentCode = getNumeric(
                        item,
                        "Payment Code",
                        "Payment Method Code",
                        "Payment Funding Code",
                        "Payment Funding",
                        "payment_code",
                        "PaymentMethod",
                        "Payment Type",
                    );

                    // ===== MEAL PLAN: support numeric OR string like "EP" =====
                    let mealPlanCode = getNumeric(item, "Meal Plan Code", "Meal Plan Type", "MealPlanCode", "MealPlan");
                    if (typeof mealPlanCode === "undefined") {
                        const mpRaw = getString(item, "Meal Plan Type", "Meal Plan", "Meal Plans", "MealPlan");
                        if (mpRaw) {
                            const key = String(mpRaw).toUpperCase().trim();
                            if (MEAL_PLAN_REVERSE[key] !== undefined) {
                                mealPlanCode = MEAL_PLAN_REVERSE[key];
                            }
                        }
                    }

                    // Room Category fix → sometimes number / array / empty
                    let roomCategory = item["Room Category"];
                    if (Array.isArray(roomCategory)) {
                        roomCategory = roomCategory.join(", ");
                    }
                    roomCategory = String(roomCategory || "N/A");

                    // ===== BOOKING STATUS: support numeric OR string like "Confirmed" =====
                    let bookingStatus = getNumeric(item, "Booking Status", "booking_status", "BookingStatus");
                    if (typeof bookingStatus === "undefined") {
                        const bsRaw = getString(item, "Booking Status", "Status", "BookingStatus");
                        if (bsRaw) {
                            const key = String(bsRaw).toLowerCase().trim();
                            if (BOOKING_STATUS_REVERSE[key] !== undefined) {
                                bookingStatus = BOOKING_STATUS_REVERSE[key];
                            }
                        }
                    }
                    // If still undefined, leave undefined (later logic handles default)
                    const bookingStatusName = bookingStatus !== undefined ? BOOKING_STATUS[bookingStatus] || String(bookingStatus) : undefined;

                    const channelName = channelCode !== undefined
                        ? CHANNELS[channelCode] || String(item["Source"] || item["Booking Source"] || item["Booking source"] || item["booking source"] || channelCode)
                        : String(item["Source"] || item["Booking Source"] || item["Booking source"] || item["booking source"] || "API Import");
                    const subChannelName = subChannelCode !== undefined ? SUB_CHANNELS[subChannelCode] || String(subChannelCode) : String(item["Sub Channel"] || item["Sub-Channel"] || "");
                    const stayStatusName = stayStatusCode !== undefined ? STAY_STATUS[stayStatusCode] || String(stayStatusCode) : undefined;
                    const paymentName = paymentCode !== undefined ? PAYMENT_CODES[paymentCode] || String(paymentCode) : String(item["Payment Method"] || item["Payment"] || "");
                    const mealPlanName = mealPlanCode !== undefined ? MEAL_PLAN[mealPlanCode] || String(item["Meal Plan Type"] || mealPlanCode) : String(item["Meal Plan Type"] || "");

                    // Compute a final `source` value compatible with other hooks/components.
                    // Some parts of the UI expect offline/direct bookings to be labelled
                    // exactly "Direct Booking" (see `page.tsx` filter). If the original
                    // incoming code was 100 (DIRECT) or the normalized code is 102
                    // (OFFLINE_AGENT), expose `source` as "Direct Booking" so the card
                    // and counts render correctly.
                    let finalSource: string;
                    if (originalChannelCode === 100 || channelCode === 102) {
                        finalSource = "Direct Booking";
                    } else if (originalChannelCode === 105 || channelCode === 105) {
                        // Treat Booking Engine (105) as Online Booking Engine for UI filters
                        finalSource = "Online Booking Engine";
                    } else {
                        finalSource = String(
                            (channelCode !== undefined ? CHANNELS[channelCode] : undefined) ||
                            item["Source"] ||
                            item["Booking Source"] ||
                            item["Booking source"] ||
                            item["booking source"] ||
                            "API Import",
                        );
                    }

                    let status = "pending";
                    let paymentProgress = "pending";

                    // ===== Amended: robust invoice and paid percentage calculation =====
                    const invoiceAmountRaw = getNumeric(item, "Invoice Amount", "InvoiceAmount", "Invoice Amount(INR)", "Net Payable(A)") ?? getNumeric(item, "Amount", "Total Amount");
                    const invoiceAmountForCalc = typeof invoiceAmountRaw === "undefined" ? 0 : invoiceAmountRaw;

                    const paidAmountRaw = getNumeric(item, "Amount Paid", "Received Amount", "Amount Collected", "Paid Amount", "Total Payments", "Total Payments Received");
                    const paidAmountForCalc = typeof paidAmountRaw === "undefined" ? 0 : paidAmountRaw;
                    const rawBooker =
                        getString(
                            item,
                            "Name of the Booker",
                            "Booking Taken By",
                            "Last Modified By"
                        ) || "";


                    // avoid division by zero: if invoice is zero, treat paidPercentage specially
                    let paidPercentage = 0;
                    if (invoiceAmountForCalc === 0) {
                        paidPercentage = paidAmountForCalc > 0 ? 100 : 0;
                    } else {
                        paidPercentage = Math.round((Number(paidAmountForCalc) / Number(invoiceAmountForCalc)) * 100) || 0;
                    }

                    paymentProgress = (paidPercentage >= 100 || invoiceAmountForCalc === 0) ? "paid" : (paidPercentage > 0 ? "partial" : "pending");


                    // Based on your data: 1 = confirmed, 2 = pending/hold, 3 = cancelled

                    if (bookingStatus === 3) {
                        status = "cancelled"; // use consistent spelling expected by UI
                    } else if (bookingStatus === 1) {
                        status = "confirmed";
                    } else if (bookingStatus === 2) {
                        status = "hold";
                    } else if (bookingStatus === 4) {
                        status = "No Show";
                    }
                    else if (bookingStatus === 0) {
                        status = "pending";
                    } else if (typeof bookingStatus === "undefined") {
                        // If bookingStatus was not provided, try to infer from textual fields
                        const bsText = (getString(item, "Booking Status") || "").toString().toLowerCase();
                        if (bsText.includes("cancel")) status = "cancelled";
                        else if (bsText.includes("confirm")) status = "confirmed";
                        else if (bsText.includes("no show")) status = "No Show";
                        else status = "pending";
                    }

                    const uniqueId = getString(
                        item,
                        "Unique Id",
                        "UniqueID",
                        "Unique ID",
                        "Unique_Id",
                        "UniqueIdNumber",
                        "Unique Id Number",
                        "Unique",
                        "Unique Identifier",
                    );

                    const roomCharges = getNumeric(
                        item,
                        "Total Room Price",
                        "Room Charges",
                        "Room Charge",
                        "RoomCharges",
                        "room_charges",
                        "Room Tariff",
                        "Room Tariff Amount",
                        "Room Price",
                    );
                    const addonsAmount = getNumeric(
                        item,
                        "Add Ons Price",
                        "Total Addon Price",
                        "Addons",
                        "Add Ons",
                        "Addon Amount",
                        "Add-on Amount",
                        "Addon Charges",
                        "Add-on Charges",
                    );
                    const outletPriceAmount = getNumeric(
                        item,
                        "Outlet Price",
                        "Outlet Revenue",
                        "Stay Date Outlet Revenue",
                        "OutletPrice",
                        "outlet_price",
                    );
                    // ===== DISCOUNT: ensure positive discount amount for calculations =====
                    let discountAmount = getNumeric(item, "Total Discount Price", "Discount", "Discount Amount", "DiscountAmount") ?? 0;
                    discountAmount = Math.abs(Number(discountAmount || 0));

                    const subTotalAmount = getNumeric(item, "SubTotal", "Sub Total", "Subtotal", "sub_total");
                    const taxesAmount = getNumeric(item, "Total Tax", "Taxes", "Tax Amount", "Taxes Amount", "Tax", "GST", "GST Amount");
                    const paymentsAmount = getNumeric(item, "Payments", "Payment Amount", "Payments Amount") ?? paidAmountForCalc;
                    const netPaymentsByGuest = getNumeric(
                        item,
                        "Net Payments by Guest",
                        "Net Payment by Guest",
                        "Net payments by guest",
                        "Net Paid by Guest",
                    );
                    const netPayableAtHotel = getNumeric(
                        item,
                        "Net Payable At Hotel",
                        "Net Payable at Hotel",
                        "Net payable at hotel",
                        "Net Payable",
                        "Pay At Hotel Amount",
                    );

                    // ===== netPayable and final totals: subtract discount, add addons & taxes =====
                    const room = Number(roomCharges || 0);
                    const addons = Number(addonsAmount || 0);
                    const taxes = Number(taxesAmount || 0);

                    // If invoice amount provided, respect it as final payable, else compute using components.
                    const computedInvoice = typeof invoiceAmountForCalc !== "undefined" && invoiceAmountForCalc !== 0
                        ? Number(invoiceAmountForCalc)
                        : Math.max(0, Math.round(room - discountAmount + addons + taxes));

                    const netPayable = computedInvoice; // final payable considered as invoice
                    const finalTotalAmount = computedInvoice; // consistent naming (invoice already includes addons/taxes/discount)

                    return {
                        // attach mapped code/name pairs so UI can use consistent fields
                        channelCode,
                        channelName,
                        subChannelCode,
                        subChannelName,
                        stayStatusCode,
                        stayStatusName,
                        paymentCode,
                        paymentName,
                        bookingStatusCode: bookingStatus,
                        bookingStatusName,
                        // preserve original numeric channel code for auditing
                        originalChannelCode,
                        mealPlanCode,
                        mealPlanName,
                        bookingSubSource: String(item["Source Type"] || "") in BookingSubSource
                            ? BookingSubSource[String(item["Source Type"] || "") as unknown as number]
                            : String(item["Source Type"] || ""),

                        // original/derived fields
                        // Ensure `id` is unique across the array by appending the map `index`.
                        // This prevents React key collisions when different records share the same
                        // reported booking id or unique id (some payloads omit Unique Id).
                        id: String((uniqueId || item["Booking ID"] || "") + "-" + index),
                        bookingId: String(uniqueId || item["Booking ID"] || ""),
                        reservationNo: String(
                            item["Reservation No"] ||
                            item["Reservation Number"] ||
                            item["Reservation"] ||
                            ""
                        ),
                        bookingType: String(item["Booking Type"] || item["Type"] || ""),
                        guestName: String(item["Name of Client"] || ""),
                        bookerName: rawBooker,
                        checkIn: item["Arrival Date"] || "",
                        checkOut: item["Departure Date"] || "",
                        villaType: "Villa Raag",
                        villaNumber: String(item["Room No."] || "N/A"),
                        roomName: roomCategory,
                        roomRaw: String(item["Room Name"] || item["Room No."] || roomCategory),
                        plan: String(item["Meal Plan Type"] || ""),
                        // Prefer explicit amount fields, fallback to common keys
                        amount: Number(item["Invoice Amount"] || 0),
                        receivedAmount: Number(item["Total Payments"] || 0),
                        totalRoomCost: roomCharges,
                        addonsTotal: addonsAmount,
                        outletRevenue: outletPriceAmount !== undefined ? Number(outletPriceAmount) : undefined,
                        discountTotal: discountAmount,
                        netPayable: Number(item["Net Payable(A)"] || 0),
                        finalTotalAmount: finalTotalAmount,
                        taxesAmount,
                        paymentsAmount,
                        netPaymentsByGuest,
                        netPayableAtHotel,
                        complimentary: (() => {
                            const raw =
                                item["Complimentary Status"] ??
                                item["Complimentary"] ??
                                item["Complementary"] ??
                                item["Complementry"];

                            // true / false directly
                            if (raw === true || raw === false) return raw;

                            // string handling
                            if (typeof raw === "string") {
                                const v = raw.trim().toLowerCase();

                                if (v === "") return null;          // ⭐ IMPORTANT FIX
                                if (["yes", "true", "1"].includes(v)) return true;
                                if (["no", "false", "0"].includes(v)) return false;
                            }

                            // unknown / not provided
                            return null;
                        })(),

                        approvedTillDate: "",
                        status,
                        // If Booking Taken By is blank from API, show blank (don't default to "Villa Team").
                        assignedTo: String(item["Booking Taken By"] || item["Booker Email"] || "").split("@")[0],
                        team: "sales",
                        createdDate: item["Booking Date and Time"] || "",
                        lastUpdated: item["Last Edit Date"] || "",
                        // prefer finalSource (normalized for UI expectations)
                        source: finalSource,
                        paymentStatus: paymentProgress,
                        salesTeamStatus: bookingStatus === 3 ? "completed" : bookingStatus === 1 ? "in_progress" : "pending",
                        accountsVerifyStatus: bookingStatus === 3 ? "payment_verified" : "pending",
                        frontOfficeStatus: bookingStatus === 3 ? "pms_verified_done" : "pending",
                        paymentSettlementStatus: bookingStatus === 3 ? "full_payment_received" : (paymentProgress === "paid" ? "full_payment_received" : "pending"),
                        mobile: String(item["Mobile"] || ""),
                        email: String(item["Guest Email"] || ""),
                        PaymentCollectionHistoryLink: String(item["Payment Collection History Link"] || ""),
                        InvoiceHistoryLink: String(item["Invoice History Url"] || ""),
                        // compute received percentage similar to team page: always numeric (0..100)

                        receivedPercentage: Number(
                            item.receivedPercentage ??
                            (invoiceAmountForCalc === 0 ? (paidAmountForCalc > 0 ? 100 : 0) : Math.round((Number(paidAmountForCalc || 0) / Number(invoiceAmountForCalc || 1)) * 100))
                        ),
                        invoiceNumber: String(
                            item["Invoice Number"] ||
                            item["Invoice No."] ||
                            item["Invoice No"] ||
                            item["Invoice ID"] ||
                            item["Bill No"] ||
                            ""
                        ),
                        invoiceUrl: String(
                            item["Invoice Url"] ||
                            item["Invoice URL"] ||
                            item["InvoiceLink"] ||
                            item["Invoice Link"] ||
                            ""
                        ),
                        cancellationRemarks: String(
                            item["Cancellation Remarks"] ||
                            item["Cancellation Remark"] ||
                            item["Cancellation Note"] ||
                            item["Cancel Remarks"] ||
                            item["Remarks"] ||
                            ""
                        ),


                        // Keep salesperson empty if API doesn't provide a value
                        salesperson: String(item["Booking Taken By"] || ""),
                        contactNumber: String(item["Mobile"] || ""),
                        totalAmount: String(item["Invoice Amount"] || item["Amount"] || "0"),
                        paidAmount: String(item["Amount Received"] || item["Received Amount"] || item["Amount Collected"] || "0"),
                        // paymentStatus : "",
                        // Additional fields for table display
                        country: String(item["Country"] || ""),
                        // Calculate discount percentage from Discount Amount and Invoice Amount
                        // Assumes Invoice Amount is final amount after discount, so original = invoice + discount
                        discountPercent: (() => {
                            const discountAmt = Number(Math.abs(getNumeric(item, "Discount Amount", "Discount", "DiscountAmount") || 0));
                            const invoiceAmt = Number(invoiceAmountForCalc || getNumeric(item, "Invoice Amount", "Amount", "Total Amount") || 0);
                            if (discountAmt > 0) {
                                const originalAmount = invoiceAmt + discountAmt;
                                if (originalAmount > 0) {
                                    return Math.round((discountAmt / originalAmount) * 100);
                                }
                            }
                            return undefined;
                        })(),
                        // Map total pax from Number of Adults (and children if available)
                        totalPax: (() => {
                            const adults = Number(
                                item["Total Pax"] ||
                                item["Number of Adults"] ||
                                item["Adults"] ||
                                item["Adult"] ||
                                item["Pax Adults"] ||
                                0
                            );

                            const children = Number(
                                item["Number of Children"] ||
                                item["Children"] ||
                                item["Child"] ||
                                item["Kids"] ||
                                item["Pax Children"] ||
                                0
                            );

                            return adults + children;
                        })(),

                        // Map Pay At Hotel field
                        payAtHotel: (() => {
                            const value = item["Pay At Hotel"];
                            if (value === true || value === false) return value;
                            if (typeof value === "string") {
                                const lower = value.toLowerCase();
                                if (lower === "yes" || lower === "true" || lower === "1") return true;
                                if (lower === "no" || lower === "false" || lower === "0") return false;
                            }
                            return undefined;
                        })(),
                        // Map Last Modified On (alias for lastUpdated)
                        lastModifiedOn: item["Last Edit Date"] || item["Last Modified Date"] || item["Last Modified On"] || "",
                        lastModifiedBy: item["Last Modified By"] || "",
                        noOfRooms: item["No. of Rooms"] || item["Number of Rooms"] || "",
                        // cancellationRemarks: item["Cancellation Remark"] ||  "",
                        invoiceNo: String(
                            item["Invoice Number"] ||
                            item["Invoice No."] ||
                            item["Invoice No"] ||
                            item["Invoice ID"] ||
                            item["Bill No"] ||
                            ""
                        ),
                    };
                }).map((b: any) => {
                    // normalize numeric fields
                    b.amount = Number(b.amount || 0)
                    b.receivedAmount = Number(b.receivedAmount || 0)

                    // If amount is zero: make sure we don't claim 100% or any percent — treat as N/A
                    if (b.amount === 0) {
                        // Preserve confirmed/cancelled statuses even when amount is missing.
                        const isConfirmed = b.status === "confirmed"
                        const isCancelled = b.status === "cancelled"

                        if (!isConfirmed && !isCancelled) {
                            b.status = "pending"
                            b.paymentStatus = "pending"
                            b.salesTeamStatus = "pending"
                            b.paymentSettlementStatus = "pending"
                        }
                        b.receivedPercentage = null
                        return b
                    }

                    // For non-zero amounts, set payment progress strictly from status per your request:
                    // - confirmed => 100%
                    // - pending/hold/payment_pending/on_hold/auto_release/cancelled => 0%

                    const zeroProgressStatuses = ["pending", "hold", "payment_pending", "on_hold", "auto_release"]
                    if (b.status === "confirmed") {
                        // b.receivedPercentage = 100
                        // ensure receivedAmount reflects full payment for confirmed bookings if data missing
                        // if (!b.receivedAmount || b.receivedAmount === 0) b.receivedAmount = Number(b.amount || 0)
                    } else if (b.status === "cancelled") {
                        // b.receivedPercentage = 0
                        // keep receivedAmount as-is (usually 0)
                    } else if (zeroProgressStatuses.includes(b.status)) {
                        // b.receivedPercentage = 0
                    } else {
                        // fallback: if a percentage was computed earlier, keep it; otherwise default to 0
                        if (b.receivedPercentage === null || typeof b.receivedPercentage === "undefined") {
                            b.receivedPercentage = 0
                        }
                    }

                    return b
                });

                setBookings(formatted);
            } catch (err: any) {
                setError(err);
            } finally {
                setLoading(false);
            }
        }

        fetchBookings();
    }, []);

    return { bookings, loading, error, setBookings };
}
