export const convertToMarkdown = (editorData) => {
  let markdown = "";

  if (!editorData) return markdown;

  const convertHtmlToMarkdown = (html) => {
    let text = html;

    // Convert links: <a href="url">text</a> -> [text](url)
    text = text.replace(/<a href="([^"]*)"[^>]*>([^<]*)<\/a>/g, "[$2]($1)");

    // Convert bold: <b>text</b> -> **text**
    text = text.replace(/<b>([^<]*)<\/b>/g, "**$1**");

    // Convert italic: <i>text</i> -> *text*
    text = text.replace(/<i>([^<]*)<\/i>/g, "*$1*");

    // Convert code: <code>text</code> -> `text`
    text = text.replace(/<code>([^<]*)<\/code>/g, "`$1`");

    // Convert non-breaking spaces
    text = text.replace(/&nbsp;/g, " ");

    // Remove any remaining HTML tags
    text = text.replace(/<[^>]*>/g, "");

    return text;
  };

  editorData.blocks.forEach((block) => {
    switch (block.type) {
      case "header":
        const level = "#".repeat(block.data.level);
        const headerText = convertHtmlToMarkdown(block.data.text);
        markdown += `${level} ${headerText}\n\n`;
        break;

      case "paragraph":
        const paragraphText = convertHtmlToMarkdown(block.data.text);
        markdown += `${paragraphText}\n\n`;
        break;

      case "list":
        const renderListItems = (items, depth = 0) => {
          let listMd = "";
          items.forEach((item) => {
            const indent = "  ".repeat(depth);
            const prefix = block.data.style === "ordered" ? "1." : "-";
            const content = typeof item === "string" ? item : item.content;
            const convertedContent = convertHtmlToMarkdown(content);
            listMd += `${indent}${prefix} ${convertedContent}\n`;

            if (item.items && item.items.length > 0) {
              listMd += renderListItems(item.items, depth + 1);
            }
          });
          return listMd;
        };

        markdown += renderListItems(block.data.items);
        markdown += "\n";
        break;

      case "quote":
        const quoteText = convertHtmlToMarkdown(block.data.text);
        markdown += `> ${quoteText}\n`;
        if (block.data.caption) {
          const captionText = convertHtmlToMarkdown(block.data.caption);
          markdown += `> \n> — ${captionText}\n`;
        }
        markdown += "\n";
        break;

      case "code":
        markdown += `\`\`\`\n${block.data.code}\n\`\`\`\n\n`;
        break;

      case "delimiter":
        markdown += `---\n\n`;
        break;

      case "image":
        const alt = block.data.caption || "image";
        markdown += `![${alt}](${block.data.file.url})\n`;
        markdown += "\n";
        break;

      default:
        break;
    }
  });

  return markdown.trim();
};
