import React from "react";
import { render, act } from "@testing-library/react-native";
import { Touchable } from "../../Touchable";

const mockUseIsRTL = jest.fn();

jest.mock("@applicaster/zapp-react-native-utils/localizationUtils", () => ({
  useIsRTL: mockUseIsRTL,
}));

const mockUseFocusManager = jest.fn();

jest.mock("@applicaster/zapp-react-native-utils/focusManager", () => ({
  useFocusManager: mockUseFocusManager,
}));

const mockUsePrevious = jest.fn();

jest.mock("@applicaster/zapp-react-native-utils/reactHooks/utils", () => ({
  usePrevious: mockUsePrevious,
}));

const { Focusable } = require("../index.android");

describe("Focusable", () => {
  const mockFocusManager = {
    isFocused: jest.fn(),
    onDisableFocusChange: jest.fn(),
    registerFocusable: jest.fn(),
    focusedId: "test-id",
  };

  beforeEach(() => {
    jest.clearAllMocks();
    mockUseIsRTL.mockReturnValue(false);
    mockUseFocusManager.mockReturnValue(mockFocusManager);
    mockUsePrevious.mockReturnValue(false);
  });

  it("updates disableFocus state when disableFocus prop changes", () => {
    const unregister = jest.fn();
    mockFocusManager.registerFocusable.mockReturnValue(unregister);

    const { rerender } = render(
      <Focusable id="test-id" disableFocus={false}>
        <Touchable testID="touchable" />
      </Focusable>
    );

    rerender(
      <Focusable id="test-id" disableFocus={true}>
        <Touchable testID="touchable" />
      </Focusable>
    );

    expect(mockFocusManager.onDisableFocusChange).toHaveBeenCalledWith(
      "test-id"
    );
  });

  it("calls focusManager.registerFocusable on mount and unregisters on unmount", () => {
    const unregister = jest.fn();
    mockFocusManager.registerFocusable.mockReturnValue(unregister);

    const { unmount } = render(
      <Focusable id="test-id">
        <Touchable testID="touchable" />
      </Focusable>
    );

    expect(mockFocusManager.registerFocusable).toHaveBeenCalled();
    act(() => unmount());
    expect(unregister).toHaveBeenCalled();
  });
});
