import { Template, Block, BlockType, ExportOptions } from "../types/blocks";

// Default export options
const defaultExportOptions: ExportOptions = {
  format: "html",
  includeCSS: true,
  optimizeForEmailClients: true,
  rtlSupport: true,
  minify: false,
};

// Convert blocks to HTML
const renderBlockToHTML = (block: Block): string => {
  switch (block.type) {
    case BlockType.TEXT:
      return `
        <tr>
          <td style="
            font-size: ${block.style.fontSize}px;
            font-weight: ${block.style.fontWeight};
            color: ${block.style.color};
            text-align: ${block.style.textAlign};
            line-height: ${block.style.lineHeight};
            font-family: ${block.style.fontFamily || "Arial, sans-serif"};
            padding: ${block.style.padding?.top || 8}px ${
        block.style.padding?.right || 16
      }px ${block.style.padding?.bottom || 8}px ${
        block.style.padding?.left || 16
      }px;
            margin: ${block.style.margin?.top || 0}px ${
        block.style.margin?.right || 0
      }px ${block.style.margin?.bottom || 0}px ${
        block.style.margin?.left || 0
      }px;
            background-color: ${block.style.backgroundColor || "transparent"};
            border-radius: ${block.style.borderRadius || 0}px;
          ">
            ${block.data.content}
          </td>
        </tr>
      `;

    case BlockType.BUTTON:
      return `
        <tr>
          <td style="text-align: ${block.style.textAlign}; padding: ${
        block.style.margin?.top || 8
      }px 0;">
            <table cellpadding="0" cellspacing="0" border="0" style="display: inline-block;">
              <tr>
                <td style="
                  background-color: ${block.style.backgroundColor};
                  border-radius: ${block.style.borderRadius || 6}px;
                  padding: ${block.style.padding?.top || 12}px ${
        block.style.padding?.right || 24
      }px ${block.style.padding?.bottom || 12}px ${
        block.style.padding?.left || 24
      }px;
                ">
                  <a href="${block.data.url}" style="
                    color: ${block.style.textColor};
                    text-decoration: none;
                    font-size: ${block.style.fontSize}px;
                    font-weight: ${block.style.fontWeight};
                    display: inline-block;
                  ">
                    ${block.data.text}
                  </a>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      `;

    case BlockType.IMAGE: {
      const imageHTML = `
        <img src="${block.data.src}" 
             alt="${block.data.alt}" 
             style="
               width: ${
                 typeof block.style.width === "number"
                   ? block.style.width + "px"
                   : block.style.width
               };
               height: ${
                 typeof block.style.height === "number"
                   ? block.style.height + "px"
                   : block.style.height
               };
               object-fit: ${block.style.objectFit};
               border-radius: ${block.style.borderRadius || 0}px;
               display: block;
               max-width: 100%;
             " />
      `;

      return `
        <tr>
          <td style="
            text-align: ${block.style.textAlign};
            padding: ${block.style.margin?.top || 8}px 0;
          ">
            ${
              block.data.url
                ? `<a href="${block.data.url}">${imageHTML}</a>`
                : imageHTML
            }
          </td>
        </tr>
      `;
    }

    case BlockType.SPACER:
      return `
        <tr>
          <td style="
            height: ${block.style.height}px;
            line-height: ${block.style.height}px;
            font-size: 1px;
          ">
            &nbsp;
          </td>
        </tr>
      `;

    case BlockType.CONTAINER:
      // TODO: Implement container rendering
      return `
        <tr>
          <td style="
            background-color: ${block.style.backgroundColor || "#f8f9fa"};
            border-radius: ${block.style.borderRadius || 8}px;
            padding: ${block.style.padding?.top || 16}px ${
        block.style.padding?.right || 16
      }px ${block.style.padding?.bottom || 16}px ${
        block.style.padding?.left || 16
      }px;
            margin: ${block.style.margin?.top || 8}px 0;
          ">
            <!-- Container content would go here -->
          </td>
        </tr>
      `;

    default:
      return "";
  }
};

// Generate CSS for email clients
const generateEmailCSS = (options: ExportOptions): string => {
  if (!options.includeCSS) return "";

  return `
    <style type="text/css">
      /* Email Client Resets */
      body, table, td, p, a, li, blockquote {
        -webkit-text-size-adjust: 100%;
        -ms-text-size-adjust: 100%;
      }
      
      table, td {
        mso-table-lspace: 0pt;
        mso-table-rspace: 0pt;
      }
      
      img {
        -ms-interpolation-mode: bicubic;
        border: 0;
        outline: none;
        text-decoration: none;
      }
      
      /* RTL Support */
      ${
        options.rtlSupport
          ? `
        .rtl-content {
          direction: rtl;
          text-align: right;
        }
      `
          : ""
      }
      
      /* Responsive */
      @media only screen and (max-width: 600px) {
        .email-container {
          width: 100% !important;
          max-width: 600px !important;
        }
        
        .mobile-hide {
          display: none !important;
        }
        
        .mobile-center {
          text-align: center !important;
        }
      }
    </style>
  `;
};

// Main export function
export const exportToHTML = (
  template: Template,
  options: Partial<ExportOptions> = {}
): string => {
  const finalOptions = { ...defaultExportOptions, ...options };

  const css = generateEmailCSS(finalOptions);
  const bodyHTML = template.blocks
    .map((block) => renderBlockToHTML(block))
    .join("");

  const html = `
<!DOCTYPE html>
<html lang="${finalOptions.rtlSupport ? "fa" : "en"}" dir="${
    finalOptions.rtlSupport ? "rtl" : "ltr"
  }">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="x-apple-disable-message-reformatting">
  <title>${template.name}</title>
  ${css}
</head>
<body style="
  margin: 0;
  padding: 0;
  background-color: #f4f4f4;
  font-family: ${template.settings.fontFamily};
  direction: ${template.settings.rtl ? "rtl" : "ltr"};
">
  <!--[if mso | IE]>
  <table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td align="center">
  <![endif]-->
  
  <table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="margin: 0; padding: 0;">
    <tr>
      <td align="center" style="padding: 20px 0;">
        <table class="email-container ${
          finalOptions.rtlSupport ? "rtl-content" : ""
        }" 
               role="presentation" 
               cellpadding="0" 
               cellspacing="0" 
               border="0" 
               width="${template.settings.width}" 
               style="
                 max-width: ${template.settings.width}px;
                 background-color: ${template.settings.backgroundColor};
                 border-radius: 8px;
                 box-shadow: 0 2px 4px rgba(0,0,0,0.1);
               ">
          ${bodyHTML}
        </table>
      </td>
    </tr>
  </table>
  
  <!--[if mso | IE]>
      </td>
    </tr>
  </table>
  <![endif]-->
</body>
</html>
  `;

  if (finalOptions.minify) {
    return html.replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
  }

  return html;
};

// Export JSON
export const exportToJSON = (template: Template): string => {
  return JSON.stringify(template, null, 2);
};

// Download file helper
export const downloadFile = (
  content: string,
  filename: string,
  mimeType: string = "text/plain"
) => {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};
