import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import dayjs from "dayjs";



export const setThemeColor = () => {
    if (typeof window !== "undefined") {
        const color = localStorage.getItem("colorCode") || "#007bff";

        // Set --theme-color
        document.documentElement.style.setProperty("--theme-color", color);

        // Set Bootstrap primary override
        document.documentElement.style.setProperty("--bs-primary", color);

        // Convert HEX to RGB
        const rgb = hexToRGB(color);
        console.log("rgb", rgb)
        if (rgb) {
            document.documentElement.style.setProperty("--theme-color-rgb", rgb);
        }
    }
};

function hexToRGB(hex) {
    hex = hex.replace("#", "");
    if (hex.length === 3) {
        hex = hex.split("").map(c => c + c).join("");
    }

    const bigint = parseInt(hex, 16);
    const r = (bigint >> 16) & 255;
    const g = (bigint >> 8) & 255;
    const b = bigint & 255;

    return `${r}, ${g}, ${b}`;
}


export const showAlert = ({ type, message }, setState) => {
    if (!type || !message) {
        throw new Error("Both 'type' and 'message' are required for showAlert");
    }

    if (type !== "Success" && type !== "Failure") {
        throw new Error("Alert type must be either 'Success' or 'Failure'");
    }

    setState({ type, message });

    // Auto-dismiss after 3 seconds (optional)
    setTimeout(() => {
        setState({ type: "", message: "" });
    }, 3000);
};


export const formatTime = (timeStr) => {
    const [hours, minutes] = timeStr.split(':');
    return `${hours.padStart(2, '0')}:${minutes}`;
};

export const format12HoursTime = (timeStr) => {
    const [hours, minutes] = timeStr.split(':').map(Number);
    const date = new Date();
    date.setHours(hours);
    date.setMinutes(minutes);

    const formatted = date.toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
        hour12: true,
    });

    return formatted;
};


// Define status styles
export const statusStyles = {
    "Available": "bg-success-focus text-success-500",
    "Reserved": "bg-primary-100 text-primary-500",
    "Booked": "bg-warning-focus text-warning-500",
    "Cancelled": "bg-danger-focus text-danger-500",
    "Order Completed": "bg-info-focus text-info-500"
};



export const exportReservationToExcel = (data, fileName = "reservation-list") => {
  if (!data || data.length === 0) {
    alert("No data to export.");
    return;
  }

  const formattedData = data.map((item) => ({
    Name: item?.customer_name || "",
    Phone: item?.phonenumber || "",
    Email: item?.email || "",
    Date: item?.reservation_date ? dayjs(item?.reservation_date).format("YYYY-MM-DD") : "",
    Table: item?.table_assigned || "",
    PartySize: item?.partysize || "",
    TimeSlot: formatTime(item?.timeslot),
    Status: item?.status || "",
  }));

  const worksheet = XLSX.utils.json_to_sheet(formattedData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Reservations");

  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });

  saveAs(blob, `${fileName}.xlsx`);
};
