import React from "react";
import { pdf } from "@react-pdf/renderer";

// Helper function to get business_id reliably
export const getBusinessId = () => {
  if (typeof window === "undefined") return null;
  const fromWindow = window?.setting?.business_id;
  const fromStorage = localStorage.getItem("business_id");
  const value = fromWindow ?? fromStorage;
  // Convert to number if it's a string
  if (value !== null && value !== undefined) {
    const num = Number(value);
    return Number.isNaN(num) ? value : num;
  }
  return null;
};

// Helper function to check if business_id is in array
export const isBusinessIdIn = (ids) => {
  const businessId = getBusinessId();
  if (businessId === null) return false;
  // Ensure both are numbers for comparison
  const businessIdNum = Number(businessId);
  return (
    Array.isArray(ids) &&
    ids.some((id) => Number(id) === businessIdNum)
  );
};

// Helper to check if a feature is enabled using window.businessFeatures
// Usage everywhere in React: import { can } from "@/Utils/helper"; if (can("color")) { ... }
export const can = (featureKey, action = 'show') => {
  if (typeof window === "undefined") return true;

  const features = window.businessFeatures || [];
  if (!Array.isArray(features)) return true;

  const feature = features.find(f => f?.feature_key === featureKey);

  // Key not in list → show by default (opt-in only for known keys)
  if (!feature) return action === "hide" ? false : true;

  if (action === "hide") return !feature.enabled;

  // Key found → show only when enabled
  return !!feature.enabled;
};


// Helper function to get discount_percent from window.setting
export const getDiscountPercent = () => {
  if (typeof window === "undefined") return 0;
  return window.setting?.discount_percent || 0;
};

// Date Convert
export const convertDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

export const renderPDF = (doc, filename = "report.pdf") => {
  // Validate input
  if (!doc) {
    console.error("No PDF document provided to renderPDF");
    alert("Error: Could not render PDF document");
    return;
  }

  // Check if output method exists
  if (typeof doc.output !== 'function') {
    console.error("Invalid PDF document - missing output method");
    alert("Error: Could not render PDF document");
    return;
  }

  try {
    // Check if setProperties is available before calling it
    if (typeof doc.setProperties === 'function') {
      try {
        doc.setProperties({ title: filename }); // set PDF document title
      } catch (error) {
        console.error("Error setting PDF properties:", error);
      }
    }

    const blob = doc.output("blob");
    const blobUrl = URL.createObjectURL(blob);

    // Device check (basic)
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if (!isMobile) {
      // DESKTOP: Render in new window with preview + download button
      const htmlContent = `
          <html>
            <head>
              <title>${filename}</title>
              <style>
                body { margin: 0; height: 100vh; display: flex; flex-direction: column; }
                #toolbar { position: fixed; top: 15px; right: 90px; z-index: 1000; }
                #downloadBtn {
                  font-size: 12px; padding: 6px 12px; cursor: pointer; background-color: #007bff;
                  border: none; color: white; border-radius: 4px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                  transition: background-color 0.3s ease;
                }
                #downloadBtn:hover { background-color: #0056b3; }
                iframe { flex-grow: 1; width: 100vw; height: 100vh; border: none; }
              </style>
            </head>
            <body>
              <div id="toolbar">
                <button id="downloadBtn" title="Download PDF">Download</button>
              </div>
              <iframe src="${blobUrl}" type="application/pdf"></iframe>
              <script>
                document.getElementById('downloadBtn').addEventListener('click', () => {
                  const a = document.createElement('a');
                  a.href = '${blobUrl}';
                  a.download = '${filename}';
                  document.body.appendChild(a);
                  a.click();
                  document.body.removeChild(a);
                });
              </script>
            </body>
          </html>
        `;
      const newWindow = window.open();
      if (!newWindow) {
        alert("Popup blocked. Please allow popups.");
        return;
      }
      newWindow.document.write(htmlContent);
      newWindow.document.close();
    } else {
      // MOBILE: Direct download, with fallback to Google Docs Viewer for preview
      // Try to download, otherwise open in Google Docs Viewer (works on most mobile browsers)
      try {
        const a = document.createElement("a");
        a.href = blobUrl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        // If download fails, open in Google Docs Viewer (some browsers block download from blob)
        const gdocsUrl = `https://docs.google.com/viewer?url=${encodeURIComponent(
          blobUrl
        )}`;
        window.open(gdocsUrl, "_blank");
      }
      // Optionally show a toast/instruction to user: "If download doesn't start, check your browser downloads or try from a computer."
      alert(
        "If the download does not start, please check your browser downloads or try from a computer."
      );
    }
  } catch (error) {
    console.error("Error rendering PDF:", error);
    alert("Error rendering PDF. Please try again.");
  }
};


export const priceCalculation = (index, watch) => {
  const qty = +watch(`list.${index}.quantity`) || 0;

  const price =
    +watch(`list.${index}.unit_price`) ||
    +watch(`list.${index}.price`) ||
    0;
  const vat = +watch(`list.${index}.vat`) || 0;
  const tax = +watch(`list.${index}.tax`) || 0;
  const discount = +watch(`list.${index}.discount`) || 0;

  const subtotal = qty * price;
  const calcVat = (subtotal * vat) / 100;
  const calcTax = (subtotal * tax) / 100;
  const calcDiscount = (subtotal * discount) / 100;

  let total = subtotal + calcVat + calcTax - calcDiscount;
  return total;
};

// Helper function to render table image with fallback
export const renderTableImage = (imagePath, options = {}) => {
  const {
    width = 35,
    height = 35,
    alt = "image",
    placeholder = "https://www.primefaces.org/wp-content/uploads/2020/05/placeholder.png",
    style = {},
  } = options;

  const imageUrl = imagePath
    ? `${window.location.origin}/upload/${imagePath}`
    : placeholder;

  return React.createElement("img", {
    alt: alt,
    src: imageUrl,
    onError: (e) => (e.target.src = placeholder),

    style: {
      verticalAlign: "middle",
      objectFit: "cover",
      borderRadius: "4px",
      width: '35px',
      height: '35px',
      ...style,
    },
  });
};


