import {
  PersonalityDataType,
  HorizontalAlignment,
  VerticalAlignment,
  ButtonSize,
  ImageSize,
  TextType,
  ButtonType,
  ImageType,
  SectionType,
  SocialType,
  SocialNetworkType,
  SocialIconSize,
  SocialIconStyle,
  SocialIconPack,
} from "../types/Types";
import { getSortedSectionKeys } from "../store/Store";
import {
  getSocialIconPath,
  hasPngIcon,
  getSocialColor,
  getSocialSvgIcon,
} from "./socialIcons";

export const exportPersonalityToHTML = async (
  data: PersonalityDataType
): Promise<string> => {
  console.log(
    "🔥 [ExportHTML] Starting export with data:",
    JSON.stringify(data, null, 2)
  );
  // Helper functions
  const getHorizontalAlign = (alignment?: HorizontalAlignment) => {
    switch (alignment) {
      case HorizontalAlignment.LEFT:
        return "left";
      case HorizontalAlignment.RIGHT:
        return "right";
      case HorizontalAlignment.CENTER:
      default:
        return "center";
    }
  };

  const getVerticalAlign = (verticalAlignment?: VerticalAlignment) => {
    switch (verticalAlignment) {
      case VerticalAlignment.TOP:
        return "top";
      case VerticalAlignment.BOTTOM:
        return "bottom";
      case VerticalAlignment.MIDDLE:
      default:
        return "middle";
    }
  };

  // Helper function to get text alignment for email
  const getTextAlignment = (alignment?: HorizontalAlignment) => {
    switch (alignment) {
      case HorizontalAlignment.LEFT:
        return "left";
      case HorizontalAlignment.RIGHT:
        return "right";
      case HorizontalAlignment.CENTER:
      default:
        return "center";
    }
  };

  // Render TextRenderer equivalent
  const renderTexts = (texts: TextType[]) => {
    console.log("🔥 [ExportHTML] renderTexts called with:", texts);
    if (!texts || texts.length === 0) {
      console.log("🔥 [ExportHTML] No texts to render");
      return "";
    }

    return texts
      .map(
        (textItem, textIndex) =>
          `<table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
        <tbody>
          <tr>
            <td align="${getTextAlignment(
              textItem.alignment
            )}" style="text-align: ${getTextAlignment(
            textItem.alignment
          )}; color: ${textItem.color || "#000000"}; font-size: ${
            textItem.fontSize || 14
          }px; font-weight: ${
            textItem.fontWeight || 400
          }; line-height: 1.4; padding-bottom: ${
            textIndex < (texts?.length || 0) - 1 ? "4px" : "0"
          };">
              ${textItem.text}
            </td>
          </tr>
        </tbody>
      </table>`
      )
      .join("");
  };

  // Render ButtonRenderer equivalent
  const renderButtons = (buttons: ButtonType[]) => {
    console.log("🔥 [ExportHTML] renderButtons called with:", buttons);
    if (!buttons || buttons.length === 0) {
      console.log("🔥 [ExportHTML] No buttons to render");
      return "";
    }

    return `<table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
      <tbody>
        <tr>
          <td align="${getHorizontalAlign(
            buttons[0]?.alignment
          )}" valign="${getVerticalAlign(
      buttons[0]?.verticalAlignment
    )}" style="width: 100%;">
            <table cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
              <tbody>
                <tr>
                  ${buttons
                    .slice(0, 2)
                    .map(
                      (button, buttonIndex) =>
                        `<td style="padding-right: ${
                          buttonIndex === 0 && buttons.length > 1 ? "4px" : "0"
                        };">
                      <table cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; background-color: ${
                        button.backgroundColor
                      }; border: ${
                          button.isBorder
                            ? `${button.borderSize}px solid ${button.borderColor}`
                            : "none"
                        }; border-radius: 4px;">
                        <tbody>
                          <tr>
                            <td align="center" valign="middle" style="padding: ${
                              button.size === ButtonSize.SMALL
                                ? "2px 4px"
                                : button.size === ButtonSize.MEDIUM
                                ? "4px 8px"
                                : "8px 12px"
                            }; font-size: ${
                          button.size === ButtonSize.SMALL
                            ? "11px"
                            : button.size === ButtonSize.MEDIUM
                            ? "13px"
                            : "15px"
                        }; color: ${
                          button.textColor
                        }; text-decoration: none; white-space: nowrap; max-width: fit-content; overflow: hidden; text-overflow: ellipsis;">
                              <a href="${button.link || "#"}" style="color: ${
                          button.textColor
                        }; text-decoration: none;">
                                ${button.text}
                              </a>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </td>`
                    )
                    .join("")}
                </tr>
              </tbody>
            </table>
          </td>
        </tr>
      </tbody>
    </table>`;
  };

  // Render ImageRenderer equivalent
  const renderImages = (images: ImageType[]) => {
    console.log("🔥 [ExportHTML] renderImages called with:", images);
    if (!images || images.length === 0) {
      console.log("🔥 [ExportHTML] No images to render");
      return "";
    }

    const shouldUseBackgroundImage = (imageSize: ImageSize) => {
      return (
        imageSize === ImageSize.REPEAT ||
        imageSize === ImageSize.REPEAT_X ||
        imageSize === ImageSize.REPEAT_Y
      );
    };

    const getBackgroundStyle = (image: ImageType) => {
      let backgroundRepeat = "no-repeat";

      switch (image.size) {
        case ImageSize.REPEAT:
          backgroundRepeat = "repeat";
          break;
        case ImageSize.REPEAT_X:
          backgroundRepeat = "repeat-x";
          break;
        case ImageSize.REPEAT_Y:
          backgroundRepeat = "repeat-y";
          break;
        default:
          backgroundRepeat = "no-repeat";
          break;
      }

      const horizontal =
        image.alignment === HorizontalAlignment.LEFT
          ? "left"
          : image.alignment === HorizontalAlignment.RIGHT
          ? "right"
          : "center";
      const vertical =
        image.verticalAlignment === VerticalAlignment.TOP
          ? "top"
          : image.verticalAlignment === VerticalAlignment.BOTTOM
          ? "bottom"
          : "center";

      return `background-image: url(${
        image.src
      }); background-position: ${horizontal} ${vertical}; background-repeat: ${backgroundRepeat}; width: ${
        image.width || "100%"
      }; height: ${image.height || "100px"};`;
    };

    const renderImage = (image: ImageType) => {
      if (shouldUseBackgroundImage(image.size)) {
        return `<div style="${getBackgroundStyle(image)}">&nbsp;</div>`;
      }

      if (image.size === ImageSize.CONTAIN) {
        return `<table width="${
          image.width || "100%"
        }" cellpadding="0" cellspacing="0" border="0">
          <tbody>
            <tr>
              <td align="center" valign="middle" style="text-align: right;">
                <img src="${image.src}" alt="${
          image.alt || "تصویر آپلود شده"
        }" width="${image.width || "100%"}" height="${
          image.height || "auto"
        }" style="border: 0;" />
              </td>
            </tr>
          </tbody>
        </table>`;
      }

      return `<img src="${image.src}" alt="${
        image.alt || "تصویر آپلود شده"
      }" width="${image.width || "100%"}" height="${
        image.height || "auto"
      }" style="border: 0;" />`;
    };

    return images
      .map(
        (image, imageIndex) =>
          `<table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tbody>
          <tr>
            <td align="${getHorizontalAlign(
              image.alignment
            )}" valign="${getVerticalAlign(
            image.verticalAlignment
          )}" style="padding-bottom: ${
            imageIndex < images.length - 1 ? "4px" : "0"
          };">
              ${renderImage(image)}
            </td>
          </tr>
        </tbody>
      </table>`
      )
      .join("");
  };

  // Render SocialRenderer equivalent
  const renderSocials = (socials: SocialType[]) => {
    console.log("🔥 [ExportHTML] renderSocials called with:", socials);
    if (!socials || socials.length === 0) {
      console.log("🔥 [ExportHTML] No socials to render");
      return "";
    }

    const getIconSize = (size: SocialIconSize) => {
      switch (size) {
        case SocialIconSize.SMALL:
          return "24px";
        case SocialIconSize.MEDIUM:
          return "32px";
        case SocialIconSize.LARGE:
          return "40px";
        default:
          return "32px";
      }
    };

    const getIconStyle = (social: SocialType) => {
      const size = getIconSize(social.size);
      const baseStyle = `width: ${size}; height: ${size}; display: inline-block; vertical-align: middle; text-align: center; line-height: ${size}; text-decoration: none; color: ${
        social.color || getSocialColor(social.networkType)
      }; margin: 2px;`;

      switch (social.style) {
        case SocialIconStyle.CIRCLE:
          return `${baseStyle} border-radius: 50%;`;
        case SocialIconStyle.SQUARE:
          return `${baseStyle} border-radius: 0;`;
        case SocialIconStyle.ROUNDED:
          return `${baseStyle} border-radius: 8px;`;
        default:
          return baseStyle;
      }
    };

    const getSocialIcon = (
      networkType: SocialNetworkType,
      iconPack?: SocialIconPack
    ) => {
      // Check if PNG icon is available, if so use it
      if (hasPngIcon(networkType, iconPack)) {
        const iconPath = getSocialIconPath(networkType, iconPack);
        const BASE = "https://dmail-admin.danakcorp.com";
        const absolute = iconPath.startsWith("/")
          ? `${BASE}${iconPath}`
          : iconPath;
        const safeUrl = encodeURI(absolute);
        return `<img src="${safeUrl}" alt="${networkType} icon" style="width: 100%; height: 100%; object-fit: contain; display: block;" />`;
      }

      // Use shared SVG function
      return getSocialSvgIcon(networkType, false) as string;
    };

    return `<table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
      <tbody>
        <tr>
          <td align="${getHorizontalAlign(
            socials[0]?.alignment
          )}" valign="${getVerticalAlign(
      socials[0]?.verticalAlignment
    )}" style="padding: 4px 0; text-align: ${getHorizontalAlign(
      socials[0]?.alignment
    )};">
            ${socials
              .map(
                (social) =>
                  `<a href="${social.link || "#"}" style="${getIconStyle(
                    social
                  )} text-decoration: none; display: inline-block;">
                    ${getSocialIcon(social.networkType, social.iconPack)}
                  </a>`
              )
              .join("")}
          </td>
        </tr>
      </tbody>
    </table>`;
  };

  // Helper functions for button alignment (same as in React components)
  const getButtonHorizontalAlign = (button?: {
    alignment?: HorizontalAlignment;
  }) => {
    if (!button || !button.alignment) return "center";
    switch (button.alignment) {
      case HorizontalAlignment.LEFT:
        return "left";
      case HorizontalAlignment.RIGHT:
        return "right";
      case HorizontalAlignment.CENTER:
      default:
        return "center";
    }
  };

  const getButtonVerticalAlign = (button?: {
    verticalAlignment?: VerticalAlignment;
  }) => {
    if (!button || !button.verticalAlignment) return "middle";
    switch (button.verticalAlignment) {
      case VerticalAlignment.TOP:
        return "top";
      case VerticalAlignment.BOTTOM:
        return "bottom";
      case VerticalAlignment.MIDDLE:
      default:
        return "middle";
    }
  };

  // Helper function to generate border style for sections
  const generateBorderStyle = (border?: {
    width?: string;
    color?: string;
    style?: string;
    sides?: string[];
  }) => {
    if (!border || border.style === "none") {
      return "";
    }

    const {
      width = "0px",
      color = "#E5E7EB",
      style = "solid",
      sides = [],
    } = border;

    // اگر width صفر باشد یا تعریف نشده باشد، border نمایش نده
    if (!width || width === "0px") {
      return "";
    }

    if (sides.length === 0 || sides.length === 4) {
      return `border: ${width} ${style} ${color};`;
    }

    // Generate individual border sides
    const borderStyles: string[] = [];
    sides.forEach((side) => {
      borderStyles.push(`border-${side}: ${width} ${style} ${color}`);
    });

    return borderStyles.join("; ") + ";";
  };

  // Render section equivalent (HeaderSection, ContentSection, FooterSection)
  const renderSection = (
    section: SectionType & { name?: string; isContent?: boolean },
    sectionHeight: string
  ) => {
    console.log(`🔥 [ExportHTML] Rendering section:`, {
      columnsCount: section.columnsCount,
      itemsLength: section.items?.length || 0,
      sectionHeight,
      items: section.items,
    });

    if (section.columnsCount > 0) {
      return `<tr style="margin: 0; padding: 0;">
        <td style="margin: 0; padding: 0; vertical-align: top; border-spacing: 0;">
          <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; border-spacing: 0; margin: 0; padding: 0; ${generateBorderStyle(
            section.border
          )}">
            <tbody>
              <tr>
                <td style="padding: ${
                  section.padding || "0px"
                }; margin: 0; border-radius: 24px; vertical-align: top;">
                  <table width="100%" cellpadding="0" cellspacing="0" border="0" style="table-layout: fixed; border-collapse: collapse; border-spacing: 0; margin: 0; padding: 0;">
                    <tbody>
                      <tr>
                        ${Array.from(
                          { length: section.columnsCount },
                          (_, index) => {
                            const item = section.items[index];
                            const hasButtons =
                              item?.buttons && item.buttons.length > 0;
                            const hasTexts =
                              item?.texts && item.texts.length > 0;
                            const hasImages =
                              item?.images && item.images.length > 0;
                            const hasSocials =
                              item?.socials && item.socials.length > 0;

                            console.log(
                              `🔥 [ExportHTML] Item ${index} content check:`,
                              {
                                hasButtons,
                                hasTexts,
                                hasImages,
                                hasSocials,
                                sectionHeight,
                                item: item,
                              }
                            );

                            let result = `<td style="width: ${
                              100 / section.columnsCount
                            }%; height: ${sectionHeight}; background-color: ${
                              item?.backgroundColor || "#ffffff"
                            }; ${
                              item?.backgroundImage
                                ? `background-image: url(${
                                    item.backgroundImage
                                  }); background-size: ${
                                    item?.style?.backgroundSize || "cover"
                                  }; background-repeat: ${
                                    item?.style?.backgroundRepeat || "no-repeat"
                                  }; background-position: ${
                                    item?.style?.backgroundPosition || "center"
                                  };`
                                : ""
                            } padding: 0; vertical-align: top; border-radius: 8px; position: relative;">
                            <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; height: ${sectionHeight};">
                              <tbody>`;

                            // اگر محتوایی وجود دارد (متن، دکمه، تصویر، یا شبکه اجتماعی)
                            if (
                              hasTexts ||
                              hasButtons ||
                              hasImages ||
                              hasSocials
                            ) {
                              // اگر فقط دکمه داریم و متن نداریم
                              if (!hasTexts && hasButtons) {
                                result += `<tr>
                                <td width="100%" height="${sectionHeight}" align="${getButtonHorizontalAlign(
                                  item.buttons[0]
                                )}" valign="${getButtonVerticalAlign(
                                  item.buttons[0]
                                )}" style="padding: 8px; text-align: ${getButtonHorizontalAlign(
                                  item.buttons[0]
                                )}; vertical-align: ${getButtonVerticalAlign(
                                  item.buttons[0]
                                )};">
                                  ${renderImages(item?.images || [])}
                                  ${renderSocials(item?.socials || [])}
                                  ${
                                    section?.isContent
                                      ? '<div style="margin: 0 0 10px 0; text-align: right; color: #888; font-size: 14px;">{{content}}</div>'
                                      : ""
                                  }
                                  ${renderButtons(item.buttons)}
                                </td>
                              </tr>`;
                              } else {
                                // ردیف اصلی برای متن و تصاویر - محاسبه بر اساس height سکشن
                                const sectionHeightNumber = parseInt(
                                  sectionHeight
                                );
                                const mainHeight = hasButtons
                                  ? Math.max(
                                      sectionHeightNumber - 50,
                                      30
                                    ).toString()
                                  : Math.max(
                                      sectionHeightNumber - 25,
                                      30
                                    ).toString();

                                const textAlignment = hasTexts
                                  ? getTextAlignment(item.texts[0]?.alignment)
                                  : "center";
                                const textVerticalAlignment =
                                  hasTexts && item.texts[0]?.verticalAlignment
                                    ? item.texts[0].verticalAlignment === "top"
                                      ? "top"
                                      : item.texts[0].verticalAlignment ===
                                        "bottom"
                                      ? "bottom"
                                      : "middle"
                                    : "middle";
                                result += `<tr>
                              <td width="100%" height="${mainHeight}" align="${textAlignment}" valign="${textVerticalAlignment}" style="padding: 4px; text-align: ${textAlignment}; vertical-align: ${textVerticalAlignment}; font-size: 15px; line-height: 1.8;">
                                ${renderTexts(item?.texts || [])}
                                ${renderImages(item?.images || [])}
                                ${renderSocials(item?.socials || [])}
                                ${
                                  section?.isContent &&
                                  !hasTexts &&
                                  !hasImages &&
                                  !hasSocials
                                    ? '<div style="margin: 0; text-align: right; color: #888; font-size: 14px;">{{content}}</div>'
                                    : ""
                                }
                              </td>
                            </tr>`;

                                // ردیف دکمه‌ها
                                if (hasButtons) {
                                  result += `<tr>
                                <td width="100%" height="27" align="${getButtonHorizontalAlign(
                                  item.buttons[0]
                                )}" valign="${getButtonVerticalAlign(
                                    item.buttons[0]
                                  )}" style="padding: 0 8px 8px 8px; text-align: ${getButtonHorizontalAlign(
                                    item.buttons[0]
                                  )}; vertical-align: ${getButtonVerticalAlign(
                                    item.buttons[0]
                                  )};">
                                  ${renderButtons(item.buttons)}
                                </td>
                              </tr>`;
                                }
                              }
                            } else {
                              // اگر هیچ محتوایی نداریم و content section است
                              console.log(
                                "🔥 [ExportHTML] Empty section detected, isContent:",
                                section?.isContent
                              );
                              if (section?.isContent) {
                                console.log(
                                  "🔥 [ExportHTML] Adding {{content}} placeholder to empty content"
                                );
                                const sectionHeightNumber = parseInt(
                                  sectionHeight
                                );
                                const emptyHeight = Math.max(
                                  sectionHeightNumber - 25,
                                  30
                                );
                                result += `<tr>
                              <td width="100%" height="${emptyHeight}" style="padding: 4px; text-align: right; vertical-align: top; font-size: 15px; line-height: 1.8;">
                                <div style="margin: 0; text-align: right; color: #888; font-size: 14px;">{{content}}</div>
                              </td>
                            </tr>`;
                              } else {
                                console.log(
                                  "🔥 [ExportHTML] Not content section, skipping {{content}}"
                                );
                              }
                            }

                            result += `</tbody>
                            </table>
                          </td>`;

                            // فاصله بین ستون‌ها
                            if (index < section.columnsCount - 1) {
                              result += `<td style="width: 16px;"></td>`;
                            }

                            return result;
                          }
                        ).join("")}
                      </tr>
                    </tbody>
                  </table>
                </td>
              </tr>
            </tbody>
          </table>
        </td>
      </tr>`;
    } else {
      // حالت خالی
      const getEmptyMessage = (
        section: SectionType & { name?: string; isContent?: boolean }
      ) => {
        if (section?.isContent) return "محتوای ایمیل";
        if (section?.name) return section.name;
        return "سکشن خالی";
      };

      const emptyMessage = getEmptyMessage(section);
      const sectionHeightNumber = parseInt(sectionHeight);
      const displayHeight = section?.isContent
        ? Math.max(sectionHeightNumber + 40, 286)
        : sectionHeight;

      return `<tr style="margin: 0; padding: 0;">
        <td style="margin: 0; padding: 0; vertical-align: top; border-spacing: 0;">
          <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; border-spacing: 0; margin: 0; padding: 0; ${generateBorderStyle(
            section.border
          )}">
            <tbody>
              <tr>
                <td style="height: ${displayHeight}; margin: 0; border-radius: 24px; text-align: right; vertical-align: middle; padding: ${
        section.padding || "0px"
      };">
                  <div style="color: #888; font-size: 14px; margin: 0; padding: 0;">
                    ${emptyMessage}
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </td>
      </tr>`;
    }
  };

  // Helper function to determine section height
  const getSectionHeight = (
    sectionKey: string,
    sectionData: PersonalityDataType[string]
  ) => {
    console.log(`🔥 [ExportHTML] Getting height for section: ${sectionKey}`, {
      isContent: sectionData?.isContent,
      customHeight: sectionData?.height,
    });

    // اگر height سفارشی تعریف شده باشد، از آن استفاده کن
    if (sectionData?.height) {
      return sectionData.height;
    }

    // مقدار پیش‌فرض بر اساس نوع سکشن
    if (sectionKey === "content" || sectionData?.isContent) {
      return "246px";
    }
    // header, footer و سکشن‌های جدید همه 123px ارتفاع دارند
    return "123px";
  };

  // Generate complete HTML exactly like Personality.tsx structure
  console.log("🔥 [ExportHTML] Available sections:", Object.keys(data));
  console.log(
    "🔥 [ExportHTML] Full data structure:",
    JSON.stringify(data, null, 2)
  );

  // Get sections sorted by sortNumber
  const sortedSectionKeys = getSortedSectionKeys(data);
  console.log(
    "🔥 [ExportHTML] Sections sorted by sortNumber:",
    sortedSectionKeys
  );

  // Render all sections in sortNumber order
  const sectionsHtml = sortedSectionKeys
    .map((sectionKey) => {
      const sectionData = data[sectionKey];
      const height = getSectionHeight(sectionKey, sectionData);

      console.log(`🔥 [ExportHTML] Processing section: ${sectionKey}`, {
        name: sectionData.name,
        columnsCount: sectionData.columnsCount,
        itemsLength: sectionData.items?.length || 0,
        height: height,
        isContent: sectionData.isContent,
      });

      // Pass the complete section data for rendering with no spacing
      const renderedSection = renderSection(sectionData, height);
      console.log(
        `🔥 [ExportHTML] Section ${sectionKey} rendered, HTML length:`,
        renderedSection.length
      );

      return renderedSection;
    })
    .join("");

  console.log(
    "🔥 [ExportHTML] Total sections rendered:",
    sortedSectionKeys.length
  );
  console.log(
    "🔥 [ExportHTML] Combined sections HTML length:",
    sectionsHtml.length
  );

  const html = `<div style="max-width: 600px; margin: 0 auto; direction: rtl;">
    <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; border-spacing: 0; margin: 0; padding: 0;">
      <tbody>
        ${sectionsHtml}
      </tbody>
    </table>
  </div>`;

  console.log("🔥 [ExportHTML] Final HTML generated (length):", html.length);
  console.log(
    "🔥 [ExportHTML] HTML contains {{content}}:",
    html.includes("{{content}}")
  );

  // نمایش قسمت‌هایی از HTML که شامل content است
  const contentMatch = html.match(/<div[^>]*>{{content}}<\/div>/g);
  if (contentMatch) {
    console.log(
      "🔥 [ExportHTML] Found {{content}} placeholders:",
      contentMatch
    );
  } else {
    console.log("🔥 [ExportHTML] NO {{content}} placeholders found in HTML!");
  }

  return html;
};

export const copyHTMLToClipboard = async (html: string): Promise<boolean> => {
  try {
    await navigator.clipboard.writeText(html);
    return true;
  } catch (error) {
    console.error("Failed to copy HTML to clipboard:", error);
    return false;
  }
};
