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

let mockState: any;

beforeEach(() => {
  const baseProjectConfig: ProjectConfig = {
    title: "폼 블록 스타일 테스트",
    slug: "editor-form-style-test",
    canvasPreset: "full",
    canvasWidthPx: 1024,
    canvasBgColorHex: "#0f172a",
    bodyBgColorHex: "#020617",
  } as ProjectConfig;

  mockState = {
    blocks: [] as Block[],
    projectConfig: baseProjectConfig,
    selectedBlockId: null as string | null,
    selectedListItemId: null as string | null,
    undo: vi.fn(),
    redo: vi.fn(),
    removeBlock: vi.fn(),
    duplicateBlock: vi.fn(),
    selectBlock: vi.fn(),
    selectListItem: 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(),
    replaceBlocks: vi.fn(),
    reorderBlocks: vi.fn(),
    moveBlock: vi.fn(),
  };
});

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 hexToRgb(hex: string) {
  const clean = hex.replace("#", "");
  const int = parseInt(clean, 16);
  const r = (int >> 16) & 255;
  const g = (int >> 8) & 255;
  const b = int & 255;
  return `rgb(${r}, ${g}, ${b})`;
}

describe("EditorPage - 폼 블록 스타일", () => {
  it("formInput: textColorCustom / fillColorCustom / strokeColorCustom / widthPx / borderRadius 가 에디터 렌더에 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "form_input_1",
        type: "formInput",
        props: {
          label: "폼 입력",
          inputType: "text",
          textColorCustom: "#ff0000",
          fillColorCustom: "#123456",
          strokeColorCustom: "#654321",
          widthMode: "fixed",
          widthPx: 240,
          borderRadius: "full",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "form_input_1";

    render(<EditorPage />);

    const field = screen.getByTestId("form-input-field") as HTMLElement;

    expect(field.style.color).toBe(hexToRgb("#ff0000"));
    expect(field.style.backgroundColor).toBe(hexToRgb("#123456"));
    expect(field.style.borderColor).toBe(hexToRgb("#654321"));
    expect(field.style.width).toBe("240px");
    // borderRadius=full → 9999px 로 적용
    expect(field.style.borderRadius).toBe("9999px");
  });

  it("formSelect: textColorCustom / fillColorCustom / strokeColorCustom / widthPx / borderRadius 가 에디터 렌더에 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "form_select_1",
        type: "formSelect",
        props: {
          label: "폼 셀렉트",
          textColorCustom: "#ff0000",
          fillColorCustom: "#123456",
          strokeColorCustom: "#654321",
          widthMode: "fixed",
          widthPx: 260,
          borderRadius: "lg",
          options: [
            { label: "A", value: "a" },
            { label: "B", value: "b" },
          ],
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "form_select_1";

    render(<EditorPage />);

    const select = screen.getByLabelText("폼 셀렉트") as HTMLSelectElement;
    const wrapper = select.parentElement as HTMLElement; // style 이 적용된 div

    expect(wrapper.style.color).toBe(hexToRgb("#ff0000"));
    expect(wrapper.style.backgroundColor).toBe(hexToRgb("#123456"));
    expect(wrapper.style.borderColor).toBe(hexToRgb("#654321"));
    expect(wrapper.style.width).toBe("260px");
    expect(wrapper.style.borderRadius).toBe("9999px"); // lg → 9999 (에디터 구현 기준)
  });

  it("formRadio: textColorCustom / fillColorCustom / strokeColorCustom / widthPx / borderRadius 가 에디터 렌더에 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "form_radio_1",
        type: "formRadio",
        props: {
          formFieldName: "radio-group",
          groupLabel: "라디오 그룹",
          textColorCustom: "#ff0000",
          fillColorCustom: "#123456",
          strokeColorCustom: "#654321",
          widthMode: "fixed",
          widthPx: 280,
          borderRadius: "lg",
          options: [
            { label: "옵션 A", value: "a" },
            { label: "옵션 B", value: "b" },
          ],
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "form_radio_1";

    render(<EditorPage />);

    const label = screen.getByText("라디오 그룹");
    const container = label.nextElementSibling as HTMLElement; // style 이 적용된 div

    expect(container).toBeTruthy();
    expect(container.style.color).toBe(hexToRgb("#ff0000"));
    expect(container.style.backgroundColor).toBe(hexToRgb("#123456"));
    expect(container.style.borderColor).toBe(hexToRgb("#654321"));
    expect(container.style.width).toBe("280px");
    expect(container.style.borderRadius).toBe("9999px");
  });

  it("formCheckbox: textColorCustom / fillColorCustom / strokeColorCustom / widthPx / borderRadius 가 에디터 렌더에 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "form_checkbox_1",
        type: "formCheckbox",
        props: {
          formFieldName: "check-group",
          groupLabel: "체크 그룹",
          textColorCustom: "#ff0000",
          fillColorCustom: "#123456",
          strokeColorCustom: "#654321",
          widthMode: "fixed",
          widthPx: 300,
          borderRadius: "lg",
          options: [
            { label: "체크 1", value: "c1" },
            { label: "체크 2", value: "c2" },
          ],
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "form_checkbox_1";

    render(<EditorPage />);

    // "체크 그룹" 텍스트를 포함하는 가장 가까운 컨테이너를 찾아 스타일을 검사한다.
    const label = screen.getByText("체크 그룹");
    const groupContainer = label.closest("div") as HTMLElement;

    expect(groupContainer.style.color).toBe(hexToRgb("#ff0000"));
    expect(groupContainer.style.backgroundColor).toBe(hexToRgb("#123456"));
    expect(groupContainer.style.borderColor).toBe(hexToRgb("#654321"));
    expect(groupContainer.style.width).toBe("300px");
    expect(groupContainer.style.borderRadius).toBe("9999px");
  });
});
