import domtoimage from "dom-to-image";

/**
 * تبدیل تصاویر خارجی به data URL برای حل مشکل CORS
 */
const convertImagesToDataUrl = async (element: HTMLElement): Promise<void> => {
  const images = element.querySelectorAll("img");
  const promises = Array.from(images).map(async (img) => {
    try {
      // فقط تصاویر خارجی را پردازش کن
      if (
        !img.src.startsWith(window.location.origin) &&
        !img.src.startsWith("data:")
      ) {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        if (ctx) {
          // ایجاد image جدید با crossOrigin
          const tempImg = new Image();
          tempImg.crossOrigin = "anonymous";

          await new Promise((resolve) => {
            tempImg.onload = () => {
              canvas.width = tempImg.width;
              canvas.height = tempImg.height;
              ctx.drawImage(tempImg, 0, 0);

              try {
                const dataUrl = canvas.toDataURL("image/png");
                img.src = dataUrl;
                resolve(void 0);
              } catch (error) {
                // اگر نتوانست تبدیل کند، URL اصلی را حفظ کن
                console.warn("نمی‌توان تصویر را تبدیل کرد:", img.src, error);
                resolve(void 0);
              }
            };

            tempImg.onerror = () => {
              console.warn("نمی‌توان تصویر را بارگذاری کرد:", img.src);
              resolve(void 0);
            };

            tempImg.src = img.src;
          });
        }
      }
    } catch (error) {
      console.warn("خطا در تبدیل تصویر:", img.src, error);
    }
  });

  await Promise.allSettled(promises);
};

/**
 * گرفتن اسکرین‌شات با dom-to-image و برگرداندن فایل برای آپلود
 */
export const captureScreenshotAsFile = async (
  templateName: string
): Promise<File | null> => {
  try {
    console.log("📸 Starting screenshot capture for upload...");

    const element = await findAndValidateElement();
    if (!element) {
      console.error("❌ Element not found");
      return null;
    }

    // آماده‌سازی element
    const htmlElement = element as HTMLElement;
    const originalTransform = htmlElement.style.transform;
    const originalPosition = htmlElement.style.position;

    htmlElement.style.transform = "scale(1)";
    htmlElement.style.position = "relative";

    // تبدیل تصاویر خارجی به data URL
    console.log("🔄 Converting external images to data URLs...");
    await convertImagesToDataUrl(htmlElement);

    // صبر برای render کامل
    await new Promise((resolve) => setTimeout(resolve, 1500));

    const options = {
      quality: 1,
      bgcolor: "#ffffff",
      width: element.offsetWidth,
      height: element.offsetHeight,
      style: {
        transform: "scale(1)",
        transformOrigin: "top left",
      },
      // تنظیمات CORS برای تصاویر خارجی
      filter: (node: Node) => {
        // اگر node یک img element است، crossOrigin را چک کن
        if (node.nodeName === "IMG") {
          const img = node as HTMLImageElement;
          // تنظیم crossOrigin برای تصاویر که از دامین خارجی هستند
          if (img.src && !img.src.startsWith(window.location.origin)) {
            img.crossOrigin = "anonymous";
          }
        }
        return true;
      },
      // امکان استفاده از تصاویر که CORS ندارند
      allowTaint: true,
      useCORS: true,
    };

    let dataUrl: string;

    try {
      console.log("📸 Attempting screenshot with enhanced options...");
      dataUrl = await domtoimage.toPng(element, options);
    } catch (error) {
      console.warn("⚠️ Enhanced method failed, trying fallback...", error);

      // Fallback: استفاده از تنظیمات ساده‌تر
      const fallbackOptions = {
        quality: 0.8,
        bgcolor: "#ffffff",
        width: element.offsetWidth,
        height: element.offsetHeight,
        // حذف filter و تنظیمات پیچیده
        imagePlaceholder:
          "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
      };

      try {
        dataUrl = await domtoimage.toPng(element, fallbackOptions);
        console.log("✅ Fallback method succeeded");
      } catch (fallbackError) {
        console.error("❌ Both methods failed:", fallbackError);
        throw fallbackError;
      }
    }

    // بازگردانی استایل‌های اصلی
    htmlElement.style.transform = originalTransform;
    htmlElement.style.position = originalPosition;

    // تبدیل dataURL به File
    const response = await fetch(dataUrl);
    const blob = await response.blob();
    const file = new File([blob], `${templateName}-template.png`, {
      type: "image/png",
    });

    console.log("✅ Screenshot file created successfully:", file);
    return file;
  } catch (error) {
    console.error("❌ Screenshot capture failed:", error);
    return null;
  }
};

/**
 * تابع اصلی - استفاده از dom-to-image و برگرداندن فایل
 */
export const capturePersonalityScreenshot = async (
  templateName: string
): Promise<File | null> => {
  console.log("🎯 Starting screenshot capture...");

  try {
    const screenshotFile = await captureScreenshotAsFile(templateName);
    if (screenshotFile) {
      console.log("✅ Screenshot captured successfully");
      return screenshotFile;
    } else {
      console.error("❌ Screenshot capture failed");
      return null;
    }
  } catch (error) {
    console.error("❌ Screenshot error:", error);
    return null;
  }
};

/**
 * پیدا کردن و بررسی element
 */
const findAndValidateElement = async (): Promise<HTMLElement | null> => {
  console.log("🔍 Looking for personality element...");

  const selectors = [
    ".personality-template",
    '[class*="personality-template"]',
    ".flex-1.bg-white.rounded-4xl.p-8",
    ".bg-white.rounded-4xl.p-8",
    'div[class*="bg-white"][class*="rounded-4xl"]',
  ];

  for (let i = 0; i < selectors.length; i++) {
    const selector = selectors[i];
    console.log(`🔍 Trying selector ${i + 1}/${selectors.length}: ${selector}`);

    const elements = document.querySelectorAll(selector);
    console.log(`   Found ${elements.length} elements`);

    for (let j = 0; j < elements.length; j++) {
      const element = elements[j] as HTMLElement;

      const rect = element.getBoundingClientRect();
      const isVisible = rect.width > 0 && rect.height > 0;
      const hasContent = element.innerHTML.trim().length > 0;

      console.log(`   Element ${j + 1}:`, {
        visible: isVisible,
        hasContent,
        dimensions: `${rect.width}x${rect.height}`,
        className: element.className.slice(0, 50) + "...",
      });

      if (isVisible && hasContent) {
        console.log(`✅ Found valid element with selector: ${selector}`);
        return element;
      }
    }
  }

  console.log("❌ No valid elements found");
  return null;
};

/**
 * تابع debug برای بررسی element
 */
export const debugPersonalityElement = () => {
  console.log("🔍 === DEBUG: Personality Element Detection ===");

  const selectors = [
    ".personality-template",
    '[class*="personality-template"]',
    ".flex-1.bg-white.rounded-4xl.p-8",
    ".bg-white.rounded-4xl",
    "table",
  ];

  let foundElements = 0;

  selectors.forEach((selector, index) => {
    const elements = document.querySelectorAll(selector);
    console.log(`${index + 1}. "${selector}": ${elements.length} elements`);

    elements.forEach((el, elIndex) => {
      const htmlEl = el as HTMLElement;
      const rect = htmlEl.getBoundingClientRect();

      console.log(`   [${elIndex + 1}]`, {
        visible: rect.width > 0 && rect.height > 0,
        size: `${rect.width}x${rect.height}`,
        hasContent: htmlEl.innerHTML.trim().length > 0,
        className: htmlEl.className.slice(0, 40) + "...",
      });

      if (rect.width > 0 && rect.height > 0) {
        foundElements++;
      }
    });
  });

  console.log(`📊 Summary: ${foundElements} visible elements found`);
  console.log("=========================================");

  return {
    found: foundElements > 0,
    totalElements: foundElements,
  };
};
