import { create } from "zustand";
import { v4 as uuidv4 } from "uuid";
import { Block, BlockType, Template, TemplateVariable } from "../types/blocks";

interface EmailBuilderStore {
  // Template state
  template: Template;
  selectedBlockId: string | null;
  isPreviewMode: boolean;

  // Actions
  setTemplate: (template: Template) => void;

  // Block management
  addBlock: (type: BlockType, position?: number) => void;
  updateBlock: (id: string, updates: Partial<Block>) => void;
  removeBlock: (id: string) => void;
  moveBlock: (fromIndex: number, toIndex: number) => void;
  selectBlock: (id: string | null) => void;

  // Template management
  updateTemplateName: (name: string) => void;
  updateTemplateSettings: (settings: Partial<Template["settings"]>) => void;

  // Variables
  addVariable: (variable: Omit<TemplateVariable, "key">) => void;
  updateVariable: (key: string, updates: Partial<TemplateVariable>) => void;
  removeVariable: (key: string) => void;

  // Preview
  togglePreview: () => void;

  // Export
  exportTemplate: () => Template;
  importTemplate: (template: Template) => void;

  // Reset
  resetTemplate: () => void;
}

const defaultTemplate: Template = {
  id: uuidv4(),
  name: "قالب جدید",
  description: "",
  blocks: [],
  variables: [],
  settings: {
    width: 600,
    backgroundColor: "#ffffff",
    fontFamily: "Vazir, Arial, sans-serif",
    rtl: true,
  },
};

const createDefaultBlock = (type: BlockType): Block => {
  const baseId = uuidv4();

  switch (type) {
    case BlockType.TEXT:
      return {
        id: baseId,
        type: BlockType.TEXT,
        data: {
          content: "متن نمونه - برای ویرایش کلیک کنید",
          variables: [],
        },
        style: {
          fontSize: 14,
          fontWeight: "normal",
          color: "#000000",
          textAlign: "right",
          lineHeight: 1.5,
          fontFamily: "Vazir, Arial, sans-serif",
          padding: { top: 8, right: 16, bottom: 8, left: 16 },
          margin: { top: 0, right: 0, bottom: 0, left: 0 },
        },
      };

    case BlockType.BUTTON:
      return {
        id: baseId,
        type: BlockType.BUTTON,
        data: {
          text: "کلیک کنید",
          url: "https://example.com",
          variables: [],
        },
        style: {
          backgroundColor: "#0038FF",
          textColor: "#ffffff",
          fontSize: 14,
          fontWeight: "bold",
          width: "auto",
          textAlign: "center",
          borderRadius: 6,
          padding: { top: 12, right: 24, bottom: 12, left: 24 },
          margin: { top: 8, right: 0, bottom: 8, left: 0 },
        },
      };

    case BlockType.IMAGE:
      return {
        id: baseId,
        type: BlockType.IMAGE,
        data: {
          src: "https://via.placeholder.com/400x200?text=تصویر+نمونه",
          alt: "تصویر نمونه",
          url: "",
          variables: [],
        },
        style: {
          width: "100%",
          height: "auto",
          objectFit: "cover",
          textAlign: "center",
          borderRadius: 8,
          margin: { top: 8, right: 0, bottom: 8, left: 0 },
        },
      };

    case BlockType.SPACER:
      return {
        id: baseId,
        type: BlockType.SPACER,
        data: {} as Record<string, never>,
        style: {
          height: 24,
          margin: { top: 0, right: 0, bottom: 0, left: 0 },
        },
      };

    case BlockType.CONTAINER:
      return {
        id: baseId,
        type: BlockType.CONTAINER,
        data: {
          children: [],
        },
        style: {
          backgroundColor: "#f8f9fa",
          borderRadius: 8,
          padding: { top: 16, right: 16, bottom: 16, left: 16 },
          margin: { top: 8, right: 0, bottom: 8, left: 0 },
          direction: "column",
          justifyContent: "flex-start",
          alignItems: "flex-start",
        },
      };

    default:
      throw new Error(`Unknown block type: ${type}`);
  }
};

export const useEmailBuilderStore = create<EmailBuilderStore>((set, get) => ({
  template: defaultTemplate,
  selectedBlockId: null,
  isPreviewMode: false,

  setTemplate: (template) => set({ template }),

  addBlock: (type, position) =>
    set((state) => {
      const newBlock = createDefaultBlock(type);
      const blocks = [...state.template.blocks];

      if (position !== undefined) {
        blocks.splice(position, 0, newBlock);
      } else {
        blocks.push(newBlock);
      }

      return {
        template: {
          ...state.template,
          blocks,
        },
        selectedBlockId: newBlock.id,
      };
    }),

  updateBlock: (id, updates) =>
    set((state) => {
      const blocks = state.template.blocks.map((block) =>
        block.id === id ? ({ ...block, ...updates } as Block) : block
      );

      return {
        template: {
          ...state.template,
          blocks,
        },
      };
    }),

  removeBlock: (id) =>
    set((state) => {
      const blocks = state.template.blocks.filter((block) => block.id !== id);

      return {
        template: {
          ...state.template,
          blocks,
        },
        selectedBlockId:
          state.selectedBlockId === id ? null : state.selectedBlockId,
      };
    }),

  moveBlock: (fromIndex, toIndex) =>
    set((state) => {
      const blocks = [...state.template.blocks];
      const [movedBlock] = blocks.splice(fromIndex, 1);
      blocks.splice(toIndex, 0, movedBlock);

      return {
        template: {
          ...state.template,
          blocks,
        },
      };
    }),

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

  updateTemplateName: (name) =>
    set((state) => ({
      template: {
        ...state.template,
        name,
      },
    })),

  updateTemplateSettings: (settings) =>
    set((state) => ({
      template: {
        ...state.template,
        settings: {
          ...state.template.settings,
          ...settings,
        },
      },
    })),

  addVariable: (variable) =>
    set((state) => {
      const key = variable.description.toLowerCase().replace(/\s+/g, "_");
      const newVariable: TemplateVariable = {
        ...variable,
        key,
      };

      return {
        template: {
          ...state.template,
          variables: [...state.template.variables, newVariable],
        },
      };
    }),

  updateVariable: (key, updates) =>
    set((state) => {
      const variables = state.template.variables.map((variable) =>
        variable.key === key ? { ...variable, ...updates } : variable
      );

      return {
        template: {
          ...state.template,
          variables,
        },
      };
    }),

  removeVariable: (key) =>
    set((state) => {
      const variables = state.template.variables.filter(
        (variable) => variable.key !== key
      );

      return {
        template: {
          ...state.template,
          variables,
        },
      };
    }),

  togglePreview: () =>
    set((state) => ({
      isPreviewMode: !state.isPreviewMode,
      selectedBlockId: null,
    })),

  exportTemplate: () => {
    return get().template;
  },

  importTemplate: (template) =>
    set({
      template,
      selectedBlockId: null,
      isPreviewMode: false,
    }),

  resetTemplate: () =>
    set({
      template: {
        ...defaultTemplate,
        id: uuidv4(),
      },
      selectedBlockId: null,
      isPreviewMode: false,
    }),
}));
