import { render, screen, fireEvent } from "@testing-library/react";
import { useDeleteCustomer } from "@/apps/new-ui/services/Customer";
import { showWarningAlert } from "@/apps/new-ui/components/CustomAlert";
import { useNavigate } from "react-router-dom";
import CustomerCards from "@/apps/new-ui/pages/CustomerClub/+components/CustomerCards";
import { useGetUserInfo } from "@/apps/new-ui/services/User";

jest.mock("@/apps/new-ui/pages/CustomerClub/index.css", () => ({}));


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

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

jest.mock(
  "@/apps/new-ui/pages/CustomerClub/+components/ClusterCustomer",
  () => ({
    __esModule: true,
    default: () => <div data-testid="cluster-mock">Cluster Info</div>,
  }),
);

// Mock کردن وابستگی‌ها
jest.mock("@/apps/new-ui/services/Customer", () => ({
  useDeleteCustomer: jest.fn(() => ({ mutate: jest.fn() })),
}));

jest.mock("@/apps/new-ui/components/CustomAlert", () => ({
  showWarningAlert: jest.fn(),
}));

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useNavigate: jest.fn(),
}));

const mockUserInfo = {
  user_abilities_list: [
    { active: false },
    { active: false },
    { active: false },
    { active: false },
    { active: true }, // index 4 -> برای نمایش ClusterCustomer
    { active: false },
    { active: false },
  ],
};

// Mock کردن import.meta.env
beforeAll(() => {
  (global as any).import = {
    meta: { env: { VITE_APP_API_URL: "https://api.test" } },
  };
});

describe("CustomerCards Component", () => {
  const navigateMock = jest.fn();
  const deleteMock = jest.fn();

  // beforeEach(() => {
  //   jest.clearAllMocks();
  //   (useNavigate as jest.Mock).mockReturnValue(navigateMock);
  //   (useDeleteCustomer as jest.Mock).mockReturnValue({ mutate: deleteMock });
  // });
  beforeEach(() => {
    jest.clearAllMocks();
    (useNavigate as jest.Mock).mockReturnValue(navigateMock);
    (useDeleteCustomer as jest.Mock).mockReturnValue({ mutate: deleteMock });
    (useGetUserInfo as jest.Mock).mockReturnValue({ data: mockUserInfo });
  });

  // تابع کمکی برای پیدا کردن دکمه سه‌نقطه
  const getToggleBtn = (container: HTMLElement) => {
    return container.querySelector("button svg.lucide-ellipsis-vertical")
      ?.parentElement as HTMLButtonElement;
  };

  it("renders skeleton loaders when loading", () => {
    const { container } = render(<CustomerCards isLoading={true} />);
    const skeletons = container.querySelectorAll(".animate-pulse");
    expect(skeletons.length).toBeGreaterThan(0);
  });

  it("renders customer list", () => {
    render(
      <CustomerCards
        data={[
          {
            id: 1,
            name: "سارا",
            phone_number: "09350000000",
            customer_type: "Silver",
            profile_picture: "",
            score: 40,
          },
        ]}
      />,
    );
    expect(screen.getByText("سارا")).toBeInTheDocument();
  });

  it("opens and closes dropdown menu", () => {
    const { container } = render(
      <CustomerCards
        data={[
          {
            id: 3,
            name: "سارا",
            phone_number: "09350000000",
            customer_type: "Silver",
            profile_picture: "",
            score: 40,
          },
        ]}
      />,
    );

    const toggleBtn = getToggleBtn(container);
    fireEvent.click(toggleBtn);
    expect(screen.getByText("ویرایش")).toBeInTheDocument();

    fireEvent.click(toggleBtn);
    expect(screen.queryByText("ویرایش")).not.toBeInTheDocument();
  });

  it("calls delete flow when clicking delete", () => {
    const { container } = render(
      <CustomerCards
        data={[
          {
            id: 4,
            name: "رضا",
            phone_number: "09120000000",
            customer_type: "Silver",
            profile_picture: "",
            score: 50,
          },
        ]}
      />,
    );

    fireEvent.click(getToggleBtn(container));
    fireEvent.click(screen.getByText("حذف"));
    expect(showWarningAlert).toHaveBeenCalled();
  });

  it("navigates when clicking edit", () => {
    const { container } = render(
      <CustomerCards
        data={[
          {
            id: 5,
            name: "امیر",
            phone_number: "09121234567",
            customer_type: "Silver",
            profile_picture: "",
            score: 70,
          },
        ]}
      />,
    );

    fireEvent.click(getToggleBtn(container));
    fireEvent.click(screen.getByText("ویرایش"));
    expect(navigateMock).toHaveBeenCalled();
  });
});
