import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { useGetUserInfo } from "@/apps/new-ui/services/User";
import { useGetUserCards } from "@/apps/new-ui/services/Card";
import { useGetLinkShortnerUrl } from "@/apps/new-ui/services/Explore";
import Information from "@/apps/new-ui/pages/sms-kade/+components/Information";

// mock modal children
jest.mock("../src/apps/new-ui/Utils/env.ts", () => ({
  ENV: {
    API_URL: "https://api.test",
  },
}));

jest.mock(
  "@/apps/new-ui/pages/sms-kade/+components/SelectSMSContent",
  () => () => <div data-testid="select-sms-content">SMS CONTENT</div>,
);

jest.mock(
  "@/apps/new-ui/pages/sms-kade/+components/SubmitSMSContext.tsx",
  () =>
    ({ onConfirm }: any) => (
      <div data-testid="submit-sms-context">
        <button onClick={onConfirm}>confirm-submit</button>
      </div>
    ),
);
jest.mock(
  "@/apps/new-ui/pages/sms-kade/+components/CustomerCardSMS",
  () => () => <div data-testid="customer-card-sms" />,
);

jest.mock(
  "@/apps/new-ui/pages/sms-kade/+components/BusinessCardModal.tsx",
  () => (props: any) => {
    if (!props.open) return null;

    return (
      <div data-testid="business-card-modal">
        <button
          data-testid="modal-confirm"
          onClick={() =>
            props.onConfirm({
              id: 1,
              name: "Test Card",
              link_shorten: "https://card",
            })
          }
        >
          confirm-card
        </button>

        <button data-testid="modal-close" onClick={props.onClose}>
          close
        </button>
      </div>
    );
  },
);

// mock delete button
jest.mock(
  "@/apps/new-ui/components/CustomeComponents/DeleteButton",
  () => (props: any) => (
    <button data-testid="delete-btn" onClick={props.onclick}>
      delete
    </button>
  ),
);

// mock SubscriptionWrapper (فقط دیو می‌کنیم)
jest.mock(
  "@/apps/new-ui/components/SubscriptionWrapper",
  () => (props: any) => <div>{props.children}</div>,
);

/* mock services */
jest.mock("@/apps/new-ui/services/User.ts", () => ({
  useGetUserInfo: jest.fn(),
}));

jest.mock("@/apps/new-ui/services/Card", () => ({
  useGetUserCards: jest.fn(),
}));

jest.mock("@/apps/new-ui/services/Explore", () => ({
  useGetLinkShortnerUrl: jest.fn(),
}));

const mockUser = {
  current_user: {
    user_id: 10,
    phone_number: "09120000000",
    name: "Test Artist",
  },
  user_abilities_list: [
    {}, //0
    { active: true }, //1
    {},
    {},
    {},
    {}, // 2,3,4,5
    { active: false }, //6 پرسنلی نیست
  ],
};

const mockCards = {
  artist_cards: [
    { id: 1, name: "Artist Card", link_shorten: "https://artist-card" },
  ],
  salon_cards: [],
};

const mockShortner = {
  URL: "https://salona.io",
};

describe("Information component", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    localStorage.clear();

    (useGetUserInfo as jest.Mock).mockReturnValue({
      data: mockUser,
      isLoading: false,
    });

    (useGetUserCards as jest.Mock).mockReturnValue({
      data: mockCards,
    });

    (useGetLinkShortnerUrl as jest.Mock).mockReturnValue({
      data: mockShortner,
    });

    localStorage.setItem("selectedCustomersCount", "3");
  });

  const renderUI = () => render(<Information />);

  // -------------------------------------
  it("renders base UI elements", () => {
    renderUI();

    expect(screen.getByText("محتوای پیام")).toBeInTheDocument();
    expect(screen.getByText("(3)")).toBeInTheDocument();
  });

  // -------------------------------------
  it("opens SMS content modal", () => {
    renderUI();

    fireEvent.click(screen.getByText("انتخاب محتوای پیام"));

    expect(screen.getByTestId("select-sms-content")).toBeInTheDocument();
  });

  // -------------------------------------
  it("selects SMS content then shows formatted text", async () => {
    localStorage.setItem("selectedTextSMS", "سلام {artist}");

    renderUI();

    expect(screen.getByText("سلام Test Artist")).toBeInTheDocument();
  });

  // -------------------------------------
  it("selects business card correctly", async () => {
    localStorage.setItem("selectedTextSMS", "hi {business_card}");

    renderUI();

    fireEvent.click(screen.getByText("لینک کارت ویزیت قرار گیرد"));

    const modal = screen.getByTestId("business-card-modal");
    expect(modal).toBeInTheDocument();

    fireEvent.click(screen.getByTestId("modal-confirm"));

    await waitFor(() => {
      expect(screen.getByText("Test Card")).toBeInTheDocument();
      expect(screen.getByText("https://card")).toBeInTheDocument();
    });

    expect(localStorage.getItem("sms_selectedBusinessCard")).toContain(
      "Test Card",
    );
  });

  // -------------------------------------
  it("selects schedule link correctly", () => {
    localStorage.setItem("selectedTextSMS", "link: {schedule_link}");

    renderUI();

    fireEvent.click(screen.getByText("لینک جدول زمانی قرار گیرد"));

    expect(screen.getByText("لینک جدول زمانی")).toBeInTheDocument();
    expect(screen.getByText("https://salona.io/10")).toBeInTheDocument();
  });

  // -------------------------------------
  it("delete selected business card", async () => {
    localStorage.setItem("selectedTextSMS", "x");

    localStorage.setItem(
      "sms_selectedBusinessCard",
      JSON.stringify(mockCards.artist_cards[0]),
    );
    renderUI();

    fireEvent.click(screen.getByTestId("delete-btn"));

    await waitFor(() => {
      expect(localStorage.getItem("sms_selectedBusinessCard")).toBeNull();
    });
  });

  // -------------------------------------
  it("opens and closes submit modal", async () => {
    localStorage.setItem("selectedTextSMS", "test");

    renderUI();

    fireEvent.click(screen.getByText("ارسال پیامک"));

    expect(screen.getByTestId("submit-sms-context")).toBeInTheDocument();

    fireEvent.click(screen.getByText("confirm-submit"));

    await waitFor(() => {
      // بعد از confirm همه کلیدها پاک می‌شود
      expect(localStorage.getItem("sms_selectedBusinessCard")).toBeNull();
      expect(localStorage.getItem("sms_includePhoneNumber")).toBeNull();
    });
  });
});
