import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import { jest } from "@jest/globals";
import InputFactory from "../pages/GlobalConfig/InputFactory.js";
import "@testing-library/jest-dom/extend-expect";

describe("InputFactory", () => {
  const baseField = {
    Id: "1",
    Label: "Test Label",
    ProValue: "",
    ProKey: "testKey",
    Editable: true,
    HelpText: "Helper text",
  };

  const fieldTypes = [
    { type: "text", placeholder: "Enter text" },
    { type: "number", placeholder: "Enter number" },
    { type: "email", placeholder: "Enter email" },
    { type: "phone", placeholder: "Enter phone" },
    { type: "textarea", placeholder: "Enter details" },
    { type: "date", placeholder: "Select date" },
    { type: "select" }, // no placeholder
    { type: "checkbox", proValue: "false" }, // checkbox expects boolean-like string
    { type: "radio" }, // no placeholder
  ];

  fieldTypes.forEach(({ type, placeholder, proValue }) => {
    it(`renders ${type} input correctly`, () => {
      render(
        <InputFactory
          field={{
            ...baseField,
            Type: type,
            Placeholder: placeholder || "",
            Options: JSON.stringify(["One", "Two"]), // for select/radio/list - must be JSON string
            ProValue: proValue !== undefined ? proValue : baseField.ProValue,
          }}
          disabled={false}
          error={false}
          helperText={baseField.HelpText}
          onChange={jest.fn()}
        />
      );

      if (placeholder) {
        expect(
          screen.getByPlaceholderText(new RegExp(placeholder, "i"))
        ).toBeInTheDocument();
      } else if (type === "select") {
        expect(screen.getByRole("combobox")).toBeInTheDocument();
      } else if (type === "radio") {
        expect(screen.getByRole("radiogroup")).toBeInTheDocument();
      } else if (type === "checkbox") {
        expect(screen.getByRole("checkbox")).toBeInTheDocument();
      } else {
        expect(screen.getByText(/Test Label/i)).toBeInTheDocument();
      }
    });
  });

  it("returns null for unsupported field type", () => {
    const { container } = render(
      <InputFactory
        field={{ ...baseField, Type: "unknown", ProKey: "testKey" }}
        disabled={false}
        error={false}
        helperText="Should not render"
        onChange={jest.fn()}
      />
    );
    expect(container.firstChild).toBeNull();
  });
});
