import { create } from "zustand";

export type BlockType =
  | "button"
  | "image"
  | "text"
  | "divider"
  | "two-column"
  | "spacer"
  | "social"
  | "video"
  | "html-snippet";

export interface ButtonBlockContent {
  text: string;
  url: string;
  backgroundColor: string;
  textColor: string;
  borderRadius: number;
  align: "left" | "center" | "right";
  paddingY: number;
  paddingX: number;
  fontSize: number;
  fullWidth?: boolean;
  uppercase?: boolean;
  letterSpacing?: number;
}

export interface ImageBlockContent {
  src: string;
  alt: string;
  width: string;
  height: string;
  align: "left" | "center" | "right";
  linkUrl?: string;
  borderRadius?: number;
  shadow?: boolean;
}

export interface TextBlockContent {
  content: string;
  fontSize: number;
  color: string;
  align: "left" | "center" | "right" | "justify";
  fontWeight: "normal" | "medium" | "semibold" | "bold";
  lineHeight?: number;
  backgroundColor?: string;
  letterSpacing?: number;
}

export interface DividerBlockContent {
  color: string;
  height: number;
  style: "solid" | "dashed" | "dotted";
  paddingY: number;
  widthPercent?: number;
}

export interface TwoColumnBlockContent {
  leftBlocks: EditorBlock[];
  rightBlocks: EditorBlock[];
  gap: number;
  ratio: "50-50" | "60-40" | "40-60";
}

export interface SpacerBlockContent {
  height: number;
}

export type SocialPlatform = "facebook" | "instagram" | "twitter" | "linkedin" | "youtube" | "tiktok";

export interface SocialLink {
  platform: SocialPlatform;
  url: string;
}

export interface SocialBlockContent {
  links: SocialLink[];
  align: "left" | "center" | "right";
  iconSize: number;
  iconColor: string;
  iconShape: "circle" | "square";
}

export interface VideoBlockContent {
  thumbnailSrc: string;
  videoUrl: string;
  alt: string;
  width: string;
  borderRadius: number;
  align: "left" | "center" | "right";
}

export interface HtmlSnippetBlockContent {
  html: string;
}

export type BlockContent =
  | ButtonBlockContent
  | ImageBlockContent
  | TextBlockContent
  | DividerBlockContent
  | TwoColumnBlockContent
  | SpacerBlockContent
  | SocialBlockContent
  | VideoBlockContent
  | HtmlSnippetBlockContent;

export const SOCIAL_PLATFORM_META: Record<SocialPlatform, { label: string; color: string }> = {
  facebook: { label: "f", color: "#1877F2" },
  instagram: { label: "IG", color: "#E4405F" },
  twitter: { label: "X", color: "#0F172A" },
  linkedin: { label: "in", color: "#0A66C2" },
  youtube: { label: "YT", color: "#FF0000" },
  tiktok: { label: "TT", color: "#000000" },
};

export interface EditorBlock {
  id: string;
  type: BlockType;
  content: unknown;
}

interface EditorState {
  // Campaign Meta State
  title: string;
  subject: string;
  senderId: string;
  htmlBody: string;

  // Visual Builder State
  blocks: EditorBlock[];
  selectedBlockId: string | null;
  activeTab: "blocks" | "styles" | "html";
  previewDevice: "desktop" | "mobile";
  editorMode: "blocks" | "custom-html";

  // Image Modal State
  isImageModalOpen: boolean;
  pendingImageBlockId: string | null;

  // Actions
  setTitle: (title: string) => void;
  setSubject: (subject: string) => void;
  setSenderId: (senderId: string) => void;
  setHtmlBody: (htmlBody: string) => void;
  setPreviewDevice: (device: "desktop" | "mobile") => void;
  setActiveTab: (tab: "blocks" | "styles" | "html") => void;
  setEditorMode: (mode: "blocks" | "custom-html") => void;

  selectBlock: (id: string | null) => void;
  addBlock: (type: BlockType, targetParentId?: string, targetColumn?: "left" | "right") => string;
  updateBlock: (id: string, content: Partial<BlockContent>) => void;
  removeBlock: (id: string) => void;
  moveBlock: (id: string, direction: "up" | "down") => void;
  duplicateBlock: (id: string) => void;

  importHtml: (rawHtml: string) => void;
  exportHtml: () => string;

  openImageModal: (blockId?: string) => void;
  closeImageModal: () => void;
}

// Initial Default Blocks for active campaign look & feel
const initialBlocks: EditorBlock[] = [
  {
    id: "block-header-text",
    type: "text",
    content: {
      content: "Bem-vindo à nossa Nova Coleção Especial! ✨",
      fontSize: 22,
      color: "#1e293b",
      align: "center",
      fontWeight: "bold",
      lineHeight: 1.3,
    } as TextBlockContent,
  },
  {
    id: "block-hero-image",
    type: "image",
    content: {
      src: "https://images.unsplash.com/photo-1557804506-669a67965ba0?auto=format&fit=crop&w=1200&q=80",
      alt: "Banner da campanha",
      width: "100%",
      height: "260px",
      align: "center",
      borderRadius: 12,
    } as ImageBlockContent,
  },
  {
    id: "block-body-text",
    type: "text",
    content: {
      content:
        "Estamos animados para compartilhar com você nossas mais recentes novidades e recursos automatizados. Clique no botão abaixo para conferir em primeira mão e aproveitar a condição exclusiva.",
      fontSize: 15,
      color: "#475569",
      align: "center",
      fontWeight: "normal",
      lineHeight: 1.6,
    } as TextBlockContent,
  },
  {
    id: "block-cta-button",
    type: "button",
    content: {
      text: "Garantir Acesso Exclusivo",
      url: "https://suaempresa.com.br/promocao",
      backgroundColor: "#2563eb",
      textColor: "#ffffff",
      borderRadius: 8,
      align: "center",
      paddingY: 12,
      paddingX: 28,
      fontSize: 16,
    } as ButtonBlockContent,
  },
  {
    id: "block-divider-1",
    type: "divider",
    content: {
      color: "#e2e8f0",
      height: 1,
      style: "solid",
      paddingY: 16,
    } as DividerBlockContent,
  },
];

function generateHtmlFromBlockList(blocks: EditorBlock[]): string {
  const blockHtmls = blocks.map((b) => {
    switch (b.type) {
      case "button": {
        const c = b.content as ButtonBlockContent;
        const widthStyle = c.fullWidth ? "display: block; width: 100%; box-sizing: border-box;" : "display: inline-block;";
        return `
          <div style="text-align: ${c.align}; margin: ${c.paddingY}px 0;">
            <a href="${c.url || "#"}" target="_blank" style="${widthStyle} background-color: ${c.backgroundColor}; color: ${c.textColor}; padding: ${c.paddingY}px ${c.paddingX}px; border-radius: ${c.borderRadius}px; text-decoration: none; font-weight: 600; font-size: ${c.fontSize}px; text-align: center; text-transform: ${c.uppercase ? "uppercase" : "none"}; letter-spacing: ${c.letterSpacing || 0}px;">
              ${c.text}
            </a>
          </div>
        `;
      }
      case "image": {
        const c = b.content as ImageBlockContent;
        const shadowStyle = c.shadow ? "box-shadow: 0 8px 24px rgba(0,0,0,0.15);" : "";
        const imgTag = `<img src="${c.src}" alt="${c.alt || ""}" style="max-width: 100%; width: ${c.width || "100%"}; height: ${c.height || "auto"}; border-radius: ${c.borderRadius || 0}px; object-fit: cover; display: inline-block; ${shadowStyle}" />`;
        return `
          <div style="text-align: ${c.align}; margin: 12px 0;">
            ${c.linkUrl ? `<a href="${c.linkUrl}" target="_blank">${imgTag}</a>` : imgTag}
          </div>
        `;
      }
      case "text": {
        const c = b.content as TextBlockContent;
        const bgStyle = c.backgroundColor ? `background-color: ${c.backgroundColor}; padding: 14px 16px; border-radius: 8px;` : "";
        return `
          <div style="text-align: ${c.align}; color: ${c.color}; font-size: ${c.fontSize}px; font-weight: ${c.fontWeight}; line-height: ${c.lineHeight || 1.5}; letter-spacing: ${c.letterSpacing || 0}px; margin: 10px 0; ${bgStyle}">
            ${c.content}
          </div>
        `;
      }
      case "divider": {
        const c = b.content as DividerBlockContent;
        return `
          <div style="padding: ${c.paddingY}px 0; text-align: center;">
            <hr style="border: none; border-top: ${c.height}px ${c.style} ${c.color}; width: ${c.widthPercent || 100}%; margin: 0 auto;" />
          </div>
        `;
      }
      case "two-column": {
        const c = b.content as TwoColumnBlockContent;
        const leftHtml = generateHtmlFromBlockList(c.leftBlocks || []);
        const rightHtml = generateHtmlFromBlockList(c.rightBlocks || []);
        return `
          <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin: 14px 0;">
            <tr>
              <td width="50%" valign="top" style="padding-right: ${c.gap / 2}px;">
                ${leftHtml}
              </td>
              <td width="50%" valign="top" style="padding-left: ${c.gap / 2}px;">
                ${rightHtml}
              </td>
            </tr>
          </table>
        `;
      }
      case "spacer": {
        const c = b.content as SpacerBlockContent;
        return `<div style="height: ${c.height}px; line-height: ${c.height}px; font-size: 1px;">&nbsp;</div>`;
      }
      case "social": {
        const c = b.content as SocialBlockContent;
        const radius = c.iconShape === "circle" ? "50%" : "8px";
        const icons = (c.links || [])
          .map((link) => {
            const meta = SOCIAL_PLATFORM_META[link.platform];
            return `
              <a href="${link.url || "#"}" target="_blank" style="display: inline-block; width: ${c.iconSize}px; height: ${c.iconSize}px; line-height: ${c.iconSize}px; background-color: ${c.iconColor || meta.color}; color: #ffffff; border-radius: ${radius}; text-align: center; text-decoration: none; font-size: ${Math.round(c.iconSize * 0.4)}px; font-weight: 700; margin: 0 6px;">
                ${meta.label}
              </a>
            `;
          })
          .join("");
        return `<div style="text-align: ${c.align}; margin: 14px 0;">${icons}</div>`;
      }
      case "video": {
        const c = b.content as VideoBlockContent;
        return `
          <div style="text-align: ${c.align}; margin: 12px 0;">
            <a href="${c.videoUrl || "#"}" target="_blank" style="position: relative; display: inline-block; text-decoration: none; max-width: 100%;">
              <img src="${c.thumbnailSrc}" alt="${c.alt || "Vídeo"}" style="max-width: 100%; width: ${c.width || "100%"}; border-radius: ${c.borderRadius || 0}px; display: block;" />
              <span style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 56px; height: 56px; background: rgba(0,0,0,0.6); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                <span style="display: inline-block; width: 0; height: 0; border-top: 10px solid transparent; border-bottom: 10px solid transparent; border-left: 16px solid #fff; margin-left: 4px;"></span>
              </span>
            </a>
          </div>
        `;
      }
      case "html-snippet": {
        const c = b.content as HtmlSnippetBlockContent;
        return c.html || "";
      }
      default:
        return "";
    }
  });

  return `
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>E-mail Marketing</title>
</head>
<body style="margin:0; padding:20px; background-color:#f4f5f7; font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">
    <tr>
      <td align="center">
        <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" style="max-width:600px; width:100%; background-color:#ffffff; border-radius:12px; padding:32px; box-shadow:0 4px 12px rgba(0,0,0,0.05);">
          <tr>
            <td>
              ${blockHtmls.join("")}
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
  `.trim();
}

export const useCampaignEditorStore = create<EditorState>((set, get) => ({
  title: "Lançamento Nova Coleção Exclusiva",
  subject: "Descubra nossas novidades em primeira mão 🔥",
  senderId: "",
  htmlBody: generateHtmlFromBlockList(initialBlocks),

  blocks: initialBlocks,
  selectedBlockId: "block-cta-button",
  activeTab: "blocks",
  previewDevice: "desktop",
  editorMode: "blocks",

  isImageModalOpen: false,
  pendingImageBlockId: null,

  setTitle: (title) => set({ title }),
  setSubject: (subject) => set({ subject }),
  setSenderId: (senderId) => set({ senderId }),
  setHtmlBody: (htmlBody) => set({ htmlBody }),
  setPreviewDevice: (previewDevice) => set({ previewDevice }),
  setActiveTab: (activeTab) => set({ activeTab }),
  setEditorMode: (editorMode) => set({ editorMode }),

  selectBlock: (selectedBlockId) => set({ selectedBlockId }),

  addBlock: (type, targetParentId, targetColumn) => {
    const newId = `block-${Date.now()}`;
    let newBlockContent: unknown = {};

    switch (type) {
      case "button":
        newBlockContent = {
          text: "Clique Aqui",
          url: "https://",
          backgroundColor: "#2563eb",
          textColor: "#ffffff",
          borderRadius: 8,
          align: "center",
          paddingY: 10,
          paddingX: 24,
          fontSize: 15,
        } as ButtonBlockContent;
        break;
      case "image":
        newBlockContent = {
          src: "https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&w=800&q=80",
          alt: "Imagem",
          width: "100%",
          height: "200px",
          align: "center",
          borderRadius: 8,
        } as ImageBlockContent;
        break;
      case "text":
        newBlockContent = {
          content: "Digite o texto do seu e-mail aqui...",
          fontSize: 16,
          color: "#334155",
          align: "left",
          fontWeight: "normal",
          lineHeight: 1.5,
        } as TextBlockContent;
        break;
      case "divider":
        newBlockContent = {
          color: "#e2e8f0",
          height: 1,
          style: "solid",
          paddingY: 12,
        } as DividerBlockContent;
        break;
      case "spacer":
        newBlockContent = {
          height: 24,
        } as SpacerBlockContent;
        break;
      case "social":
        newBlockContent = {
          links: [
            { platform: "facebook", url: "https://facebook.com" },
            { platform: "instagram", url: "https://instagram.com" },
            { platform: "linkedin", url: "https://linkedin.com" },
          ],
          align: "center",
          iconSize: 36,
          iconColor: "",
          iconShape: "circle",
        } as SocialBlockContent;
        break;
      case "video":
        newBlockContent = {
          thumbnailSrc: "https://images.unsplash.com/photo-1611162617213-7d7a39e9b1d7?auto=format&fit=crop&w=800&q=80",
          videoUrl: "https://",
          alt: "Vídeo da campanha",
          width: "100%",
          borderRadius: 12,
          align: "center",
        } as VideoBlockContent;
        break;
      case "html-snippet":
        newBlockContent = {
          html: "<div style=\"padding:12px;color:#475569;font-size:13px;\">Cole aqui seu HTML personalizado...</div>",
        } as HtmlSnippetBlockContent;
        break;
      case "two-column":
        newBlockContent = {
          leftBlocks: [
            {
              id: `block-${Date.now()}-col1`,
              type: "text",
              content: {
                content: "Coluna Esquerda: adicione seu conteúdo aqui.",
                fontSize: 14,
                color: "#475569",
                align: "left",
                fontWeight: "normal",
              },
            },
          ],
          rightBlocks: [
            {
              id: `block-${Date.now()}-col2`,
              type: "button",
              content: {
                text: "Saiba mais",
                url: "#",
                backgroundColor: "#0f172a",
                textColor: "#ffffff",
                borderRadius: 6,
                align: "center",
                paddingY: 8,
                paddingX: 16,
                fontSize: 14,
              },
            },
          ],
          gap: 16,
          ratio: "50-50",
        } as TwoColumnBlockContent;
        break;
    }

    const newBlock: EditorBlock = {
      id: newId,
      type,
      content: newBlockContent,
    };

    set((state) => {
      let updatedBlocks = [...state.blocks];

      if (targetParentId && targetColumn) {
        updatedBlocks = updatedBlocks.map((b) => {
          if (b.id === targetParentId && b.type === "two-column") {
            const tc = b.content as TwoColumnBlockContent;
            return {
              ...b,
              content: {
                ...tc,
                [targetColumn === "left" ? "leftBlocks" : "rightBlocks"]: [
                  ...(targetColumn === "left" ? tc.leftBlocks : tc.rightBlocks),
                  newBlock,
                ],
              },
            };
          }
          return b;
        });
      } else {
        updatedBlocks.push(newBlock);
      }

      const generated = generateHtmlFromBlockList(updatedBlocks);
      return {
        blocks: updatedBlocks,
        selectedBlockId: newId,
        activeTab: "styles",
        editorMode: "blocks",
        htmlBody: generated,
      };
    });

    return newId;
  },

  updateBlock: (id, partialContent) => {
    set((state) => {
      const updateList = (list: EditorBlock[]): EditorBlock[] => {
        return list.map((b) => {
          if (b.id === id) {
            return {
              ...b,
              content: { ...(b.content as object), ...partialContent },
            };
          }
          if (b.type === "two-column") {
            const tc = b.content as TwoColumnBlockContent;
            return {
              ...b,
              content: {
                ...tc,
                leftBlocks: updateList(tc.leftBlocks || []),
                rightBlocks: updateList(tc.rightBlocks || []),
              },
            };
          }
          return b;
        });
      };

      const updatedBlocks = updateList(state.blocks);
      const generated = generateHtmlFromBlockList(updatedBlocks);

      return {
        blocks: updatedBlocks,
        htmlBody: generated,
      };
    });
  },

  removeBlock: (id) => {
    set((state) => {
      const removeList = (list: EditorBlock[]): EditorBlock[] => {
        return list
          .filter((b) => b.id !== id)
          .map((b) => {
            if (b.type === "two-column") {
              const tc = b.content as TwoColumnBlockContent;
              return {
                ...b,
                content: {
                  ...tc,
                  leftBlocks: removeList(tc.leftBlocks || []),
                  rightBlocks: removeList(tc.rightBlocks || []),
                },
              };
            }
            return b;
          });
      };

      const updatedBlocks = removeList(state.blocks);
      const generated = generateHtmlFromBlockList(updatedBlocks);
      const nextSelected = state.selectedBlockId === id ? null : state.selectedBlockId;

      return {
        blocks: updatedBlocks,
        selectedBlockId: nextSelected,
        htmlBody: generated,
      };
    });
  },

  moveBlock: (id, direction) => {
    set((state) => {
      const index = state.blocks.findIndex((b) => b.id === id);
      if (index === -1) return state;

      const targetIndex = direction === "up" ? index - 1 : index + 1;
      if (targetIndex < 0 || targetIndex >= state.blocks.length) return state;

      const updatedBlocks = [...state.blocks];
      const [moved] = updatedBlocks.splice(index, 1);
      updatedBlocks.splice(targetIndex, 0, moved);

      const generated = generateHtmlFromBlockList(updatedBlocks);
      return {
        blocks: updatedBlocks,
        htmlBody: generated,
      };
    });
  },

  duplicateBlock: (id) => {
    set((state) => {
      const index = state.blocks.findIndex((b) => b.id === id);
      if (index === -1) return state;

      const source = state.blocks[index];
      const duplicated: EditorBlock = {
        id: `block-${Date.now()}`,
        type: source.type,
        content: JSON.parse(JSON.stringify(source.content)),
      };

      const updatedBlocks = [...state.blocks];
      updatedBlocks.splice(index + 1, 0, duplicated);

      const generated = generateHtmlFromBlockList(updatedBlocks);
      return {
        blocks: updatedBlocks,
        selectedBlockId: duplicated.id,
        htmlBody: generated,
      };
    });
  },

  importHtml: (rawHtml) => {
    set({ htmlBody: rawHtml, editorMode: "custom-html" });
  },

  exportHtml: () => {
    return get().htmlBody;
  },

  openImageModal: (pendingImageBlockId) => {
    set({ isImageModalOpen: true, pendingImageBlockId: pendingImageBlockId || null });
  },

  closeImageModal: () => {
    set({ isImageModalOpen: false, pendingImageBlockId: null });
  },
}));
