import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import RunAnalysis from "../components/ui/run-analysis/RunAnalysis";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useForm } from "react-hook-form";

jest.mock("next-auth/react", () => ({
  useSession: jest.fn(),
}));

jest.mock("react-hook-form", () => {
  const originalModule = jest.requireActual("react-hook-form");
  return {
    __esModule: true,
    ...originalModule,
    useForm: jest.fn(() => ({
      register: jest.fn(),
      handleSubmit: jest.fn(),
      formState: { errors: {} },
      setValue: jest.fn(),
      getValues: jest.fn(() => ({})),
      clearErrors: jest.fn(),
    })),
  };
});

jest.mock("next/router", () => ({
  useRouter: jest.fn(),
}));

const cityNameOfValue = (cityValue, fullItemValue) => {
  const city = fullItemValue?.name?.find(item => item.city === cityValue);
  return city ? city.city : fullItemValue?.name?.[0]?.zip_code;
};

describe("RunAnalysis Component", () => {
  let setValue;
  let clearErrors;
  beforeEach(() => {
    useSession.mockReturnValue({ data: { user: { image: "test-token" } } });
    useRouter.mockReturnValue({
      route: "/",
      pathname: "/",
      query: {},
      asPath: "/",
      push: jest.fn(),
    });
    setValue = jest.fn();
    clearErrors = jest.fn();
    useForm.mockReturnValue({
      register: jest.fn(),
      handleSubmit: jest.fn(),
      formState: { errors: {} },
      setValue,
      clearErrors,
      getValues: jest.fn(),
    });
  });
  
  test("checks validation errors for empty form submission", async () => {
    render(<RunAnalysis />);
    fireEvent.click(screen.getByText("Run Analysis"));
    await waitFor(() => {
      expect(screen.findByText((content) => content.includes("market value is required"))).resolves.toBeInTheDocument();
      expect(screen.findByText((content) => content.includes("origin or destination value is required"))).resolves.toBeInTheDocument();
    });
  });
  
  it('should update selectedOriginDestination and set value when handleOriginDestinationChange is called', () => {
    const { getByPlaceholderText } = render(
      <RunAnalysis marketOptionValue={[]} setValue={setValue} clearErrors={clearErrors} />
    );
    const originInput = getByPlaceholderText('Origin/Destination');
    fireEvent.change(originInput, { target: { value: 'New York, NY 10001' } });
    expect(setValue).toHaveBeenCalledWith('origin_destination', 'New York, NY 10001');
    expect(clearErrors).toHaveBeenCalledWith('origin_destination');
  });

  it('should return the correct city name when cityNameOfValue is called', () => {
    const cityValue = 'New York';
    const fullItemValue = { name: [{ city: 'New York', state: '', zip_code: '10001' }] };
    const cityName = cityNameOfValue(cityValue, fullItemValue);
    expect(cityName).toBe('New York');
    const cityValueEmpty = '';
    const cityNameEmpty = cityNameOfValue(cityValueEmpty, fullItemValue);
    expect(cityNameEmpty).toBe('10001');
  });
});
