import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { QuestionField } from "@/lib/schema-adapter";
import { QuestionPhone } from "./question-phone";

afterEach(() => {
  cleanup();
});

vi.mock("@/translations/provider", () => ({
  useI18n: () => ({
    dictionary: {
      "Select country": "انتخاب کشور",
      Close: "بستن",
      Confirm: "تایید",
    },
    locale: "fa",
  }),
}));

vi.mock("./question-answer-storage", () => ({
  useQuestionAnswers: () => ({
    getAnswerValue: () => null,
    setAnswerValue: vi.fn(),
    isLoading: false,
  }),
}));

describe("QuestionPhone Component", () => {
  const mockQuestion = {
    id: "personal_contact_number",
    title: "شماره تماس شخصی",
    type: "phone",
    extras: {
      placeHolder: "+98 9123456789",
    },
  } as QuestionField;

  it("renders phone input and opens sheet on country code click", async () => {
    render(<QuestionPhone question={mockQuestion} countryCode="+98" />);

    const countryButton = screen.getByRole("button", { name: /\+98/i });
    expect(countryButton).toBeInTheDocument();

    fireEvent.click(countryButton);

    const dialog = screen.getByRole("dialog");
    expect(dialog).toBeInTheDocument();
    expect(screen.getByText("انتخاب کشور")).toBeInTheDocument();

    // Close button exists in header
    const closeBtn = screen.getByLabelText("Close");
    expect(closeBtn).toBeInTheDocument();

    // Search input is present with translated placeholder
    const searchInput = screen.getByPlaceholderText("جستجو...");
    expect(searchInput).toBeInTheDocument();
  });

  it("filters countries when searching and selects a country", async () => {
    const { container } = render(
      <QuestionPhone question={mockQuestion} countryCode="+44" />,
    );

    const triggerButton = container.querySelector("button")!;
    fireEvent.click(triggerButton);

    const searchInput = screen.getByPlaceholderText("جستجو...");
    fireEvent.change(searchInput, { target: { value: "ایران" } });

    // Option should be rendered
    const iranOption = screen.getByRole("button", { name: /ایران/i });
    expect(iranOption).toBeInTheDocument();

    fireEvent.click(iranOption);

    // After selection, dialog closes
    await waitFor(() => {
      expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
    });
  });
});
