import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { render, screen, fireEvent, cleanup, within } from "@testing-library/react";
import EditorPage from "@/app/editor/page";
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";

// EditorPage JSON 내보내기/불러오기 TDD
// - "JSON 내보내기" 클릭 시 blocks + projectConfig 를 포함한 JSON 을 에디터 상태 영역에 출력해야 한다.
// - "JSON 적용하기" 클릭 시 blocks + projectConfig 형태의 JSON 을 파싱해 replaceBlocks + updateProjectConfig 로 반영해야 한다.
// - 잘못된 JSON 이거나 구조가 맞지 않으면 replaceBlocks / updateProjectConfig 를 호출하지 않아야 한다.

let mockState: any;

beforeEach(() => {
  const baseProjectConfig: ProjectConfig = {
    title: "JSON Export/Import 테스트",
    slug: "json-export-import-test",
    canvasPreset: "full",
  } as ProjectConfig;

  mockState = {
    blocks: [
      {
        id: "blk_1",
        type: "text",
        props: {
          text: "JSON 테스트 블록",
          align: "left",
          size: "base",
        },
      },
    ] as Block[],
    projectConfig: baseProjectConfig,
    selectedBlockId: null as string | null,
    selectedListItemId: null as string | null,
    // EditorPage 가 참조하는 액션들: 기본적으로 no-op mock 으로 채운다.
    undo: vi.fn(),
    redo: vi.fn(),
    removeBlock: vi.fn(),
    duplicateBlock: vi.fn(),
    selectBlock: vi.fn(),
    selectListItem: vi.fn(),
    replaceBlocks: vi.fn(),
    reorderBlocks: vi.fn(),
    moveBlock: vi.fn(),
    addTextBlock: vi.fn(),
    addButtonBlock: vi.fn(),
    addImageBlock: vi.fn(),
    addDividerBlock: vi.fn(),
    addListBlock: vi.fn(),
    addSectionBlock: vi.fn(),
    addFormBlock: vi.fn(),
    addFormInputBlock: vi.fn(),
    addFormSelectBlock: vi.fn(),
    addFormCheckboxBlock: vi.fn(),
    addFormRadioBlock: vi.fn(),
    addHeroTemplateSection: vi.fn(),
    addFeaturesTemplateSection: vi.fn(),
    addCtaTemplateSection: vi.fn(),
    addFaqTemplateSection: vi.fn(),
    addPricingTemplateSection: vi.fn(),
    addTestimonialsTemplateSection: vi.fn(),
    addBlogTemplateSection: vi.fn(),
    addTeamTemplateSection: vi.fn(),
    addFooterTemplateSection: vi.fn(),
    updateBlock: vi.fn(),
    updateProjectConfig: vi.fn(),
  };

  window.localStorage.clear();
});

afterEach(() => {
  cleanup();
});

vi.mock("@/features/editor/state/editorStore", () => {
  const useEditorStore = (selector: (state: any) => any) => selector(mockState);
  (useEditorStore as any).getState = () => mockState;

  return {
    __esModule: true,
    useEditorStore,
  };
});

vi.mock("next/link", () => {
  return {
    __esModule: true,
    default: ({ href, children }: any) => <a href={href}>{children}</a>,
  };
});

vi.mock("next/navigation", () => {
  return {
    __esModule: true,
    useRouter: () => ({
      push: vi.fn(),
    }),
    useSearchParams: () => ({
      get: () => null,
    }),
  };
});

function openJsonModal() {
  const menuButton = screen.getByText("메뉴");
  fireEvent.click(menuButton);

  const jsonMenuItem = screen.getByText("JSON 내보내기/불러오기");
  fireEvent.click(jsonMenuItem);

  const modalTitle = screen.getByText("JSON Export / Import");
  const jsonModal = (modalTitle.parentElement?.parentElement ?? document.body) as HTMLElement;
  return jsonModal;
}

describe("EditorPage - JSON 내보내기/불러오기", () => {
  it("JSON 내보내기 클릭 시 blocks + projectConfig 구조의 JSON 이 에디터 상태 영역에 출력되어야 한다", () => {
    render(<EditorPage />);

    const jsonModal = openJsonModal();

    const exportLabel = within(jsonModal).getByText("에디터 상태 JSON").closest("label") as HTMLElement;
    const exportTextarea = within(exportLabel).getByRole("textbox") as HTMLTextAreaElement;

    // 초기에는 비어 있어야 한다.
    expect(exportTextarea.value).toBe("");

    const exportButton = within(jsonModal).getByText("JSON 내보내기");
    fireEvent.click(exportButton);

    const value = exportTextarea.value;
    expect(value.trim().length).toBeGreaterThan(0);

    const parsed = JSON.parse(value);
    expect(Array.isArray(parsed.blocks)).toBe(true);
    expect(parsed.blocks[0].id).toBe("blk_1");
    expect(parsed.projectConfig.slug).toBe("json-export-import-test");
  });

  it("JSON 적용하기 클릭 시 blocks + projectConfig 구조의 JSON 으로 replaceBlocks 와 updateProjectConfig 를 호출해야 한다", () => {
    render(<EditorPage />);

    const jsonModal = openJsonModal();

    const importLabel = within(jsonModal).getByText("JSON에서 불러오기").closest("label") as HTMLElement;
    const importTextarea = within(importLabel).getByRole("textbox") as HTMLTextAreaElement;

    const importedBlocks: Block[] = [
      {
        id: "imported_1",
        type: "text",
        props: {
          text: "가져온 블록",
          align: "center",
          size: "lg",
        },
      } as any,
    ];

    const importedConfig: ProjectConfig = {
      title: "가져온 프로젝트",
      slug: "imported-slug",
      canvasPreset: "full",
    } as ProjectConfig;

    const payload = {
      blocks: importedBlocks,
      projectConfig: importedConfig,
    };

    fireEvent.change(importTextarea, { target: { value: JSON.stringify(payload) } });

    // 초기 마운트 시 호출됐을 수 있는 기록은 무시한다.
    mockState.replaceBlocks.mockReset();
    mockState.updateProjectConfig.mockReset();

    const applyButton = within(importLabel).getByText("JSON 적용하기");
    fireEvent.click(applyButton);

    expect(mockState.replaceBlocks).toHaveBeenCalledTimes(1);
    expect(mockState.replaceBlocks).toHaveBeenCalledWith(importedBlocks as any);

    expect(mockState.updateProjectConfig).toHaveBeenCalledTimes(1);
    expect(mockState.updateProjectConfig).toHaveBeenCalledWith(importedConfig as ProjectConfig);
  });

  it("잘못된 JSON 은 무시되어야 하며 replaceBlocks/updateProjectConfig 를 호출하면 안 된다", () => {
    render(<EditorPage />);

    const jsonModal = openJsonModal();

    const importLabel = within(jsonModal).getByText("JSON에서 불러오기").closest("label") as HTMLElement;
    const importTextarea = within(importLabel).getByRole("textbox") as HTMLTextAreaElement;

    fireEvent.change(importTextarea, { target: { value: "{ this-is: not-valid-json" } });

    mockState.replaceBlocks.mockReset();
    mockState.updateProjectConfig.mockReset();

    const applyButton = within(importLabel).getByText("JSON 적용하기");
    fireEvent.click(applyButton);

    expect(mockState.replaceBlocks).not.toHaveBeenCalled();
    expect(mockState.updateProjectConfig).not.toHaveBeenCalled();
  });
});
