import { renderWithProviders } from "@/lib/rendering";
import { ProductEditor } from "@/components/ProductEditor";
import { act, fireEvent, screen } from "@testing-library/react-native";
import { selectProducts } from "@/features/product/productSlice";
import { LumberProduct, Product } from "@/lib/product";

describe("ProductEditor", () => {
  const productName = "Flooring";
  const mockProduct: LumberProduct = {
    attributes: {
      name: productName,
    },
    pricePerUnit: 10,
    dimensions: {
      l: 40,
      u: "ft",
    },
    type: "lumber",
  };
  it("renders correctly", async () => {
    const { store } = renderWithProviders(<ProductEditor />, {
      products: [mockProduct],
    });

    const state1 = store.getState();

    let products = selectProducts(state1);

    expect(products).toHaveLength(1);

    // Check if the product names are rendered
    expect(
      screen.getByText(products[0].attributes.name as string)
    ).toBeTruthy();

    // Start to edit a product
    fireEvent.press(screen.getByText(productName));

    // Change properties of the product to make sure it's updated in the store

    act(() => {
      fireEvent.changeText(screen.getByLabelText("length"), "16");
    });
    products = selectProducts(store.getState());
    expect(products[0].dimensions.l).toBe(16);
    act(() => {
      fireEvent.changeText(screen.getByLabelText("width"), "32");
    });
    products = selectProducts(store.getState());

    expect(products[0].dimensions.w).toBe(32);

    fireEvent.press(screen.getByLabelText("delete product"));
    products = selectProducts(store.getState());
    expect(products.length).toBe(0);
  });
});
