import { render, screen, fireEvent } from "@testing-library/react";
import { useGetCustomerProfilePicture } from "@/apps/new-ui/services/Customer";
import { useNavigate } from "react-router-dom";
import LoyaltyCustomers from "@/apps/new-ui/pages/rose-assistant/+components/LoyaltyCustomers";
jest.mock("../src/apps/new-ui/Utils/env.ts", () => ({
  ENV: {
    API_URL: "https://api.test",
  },
}));
// ---------------------------
// MOCKS
// ---------------------------
jest.mock("@/apps/new-ui/services/Customer", () => ({
  useGetCustomerProfilePicture: jest.fn(),
}));

jest.mock("@/apps/new-ui/components/AnimatedTooltip", () => ({
  AnimatedTooltip: () => <div data-testid="tooltip" />,
}));

jest.mock("@/apps/new-ui/components/CustomeComponents/MessageButton", () => {
  return () => <div data-testid="message-btn" />;
});

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

// جلوگیری از خطای تصویرها
jest.mock("@/apps/new-ui/assets/profilePhoto.svg", () => "mock-photo");

describe("LoyaltyCustomers Component", () => {
  const mockNavigate = jest.fn();

  const mockData = {
    loyal_customers_last_30_days: [
      {
        customer_name: "علی رضایی",
        customer_phone_number: "09120000001",
        visits: 5,
      },
      {
        customer_name: "بی‌نهایت طولانی طولانی طولانی",
        customer_phone_number: "09120000002",
        visits: 4,
      },
    ],
  };

  beforeEach(() => {
    jest.clearAllMocks();
    localStorage.clear();
    (useNavigate as jest.Mock).mockReturnValue(mockNavigate);

    (useGetCustomerProfilePicture as jest.Mock).mockReturnValue({
      mutateAsync: jest.fn().mockResolvedValue({
        data: {
          "09120000001": {
            customer_type: "VIP",
            profile_picture: null,
          },
          "09120000002": {
            customer_type: "NORMAL",
            profile_picture: null,
          },
        },
      }),
    });
  });

  // ------------------------------------------------------------
  test("renders loyal customers count + tooltip + message buttons", () => {
    render(<LoyaltyCustomers data={mockData} />);

    // تعداد مشتریان وفادار
    expect(screen.getByText("2")).toBeInTheDocument();

    // Tooltip render
    expect(screen.getByTestId("tooltip")).toBeInTheDocument();

    // Message button for each row in modal (later)
  });

  // ------------------------------------------------------------
  test("opens modal when clicking 'دیدن همه‌ی مشتریان وفادار'", () => {
    render(<LoyaltyCustomers data={mockData} />);

    fireEvent.click(screen.getByText("دیدن همه‌ی مشتریان وفادار"));

    expect(screen.getByText("2 مشتری وفادار")).toBeInTheDocument();
  });

  // ------------------------------------------------------------
  test("filters customers when typing in search input", () => {
    render(<LoyaltyCustomers data={mockData} />);

    fireEvent.click(screen.getByText("دیدن همه‌ی مشتریان وفادار"));

    const search = screen.getByPlaceholderText("جستجو مشتری");

    // تایپ غیر مطابق → 0 نتیجه
    fireEvent.change(search, { target: { value: "zzz" } });

    expect(screen.getByText(/هیچ مشتری‌ای با/i)).toBeInTheDocument();

    // تایپ مطابق
    fireEvent.change(search, { target: { value: "علی" } });

    expect(screen.getByText("علی رضایی")).toBeInTheDocument();
  });

  // ------------------------------------------------------------
  test("send message button stores filtered customers in localStorage and navigates", () => {
    render(<LoyaltyCustomers data={mockData} />);

    fireEvent.click(screen.getByText("دیدن همه‌ی مشتریان وفادار"));

    const sendBtn = screen.getByText("ارسال پیام");

    // دکمه فعال است چون دو مشتری داریم
    expect(sendBtn).not.toBeDisabled();

    fireEvent.click(sendBtn);

    const saved = JSON.parse(localStorage.getItem("loyalty-members") || "[]");

    expect(saved.length).toBe(2);
    expect(mockNavigate).toHaveBeenCalledWith("/sms-kadeh?tab=3");
  });

  // ------------------------------------------------------------
  test("closes modal when clicking backdrop", () => {
    render(<LoyaltyCustomers data={mockData} />);

    fireEvent.click(screen.getByText("دیدن همه‌ی مشتریان وفادار"));

    // Modal visible
    expect(screen.getByText("2 مشتری وفادار")).toBeInTheDocument();

    // Click backdrop
    fireEvent.click(document.querySelector(".fixed.inset-0")!);

    expect(screen.queryByText("2 مشتری وفادار")).not.toBeInTheDocument();
  });
});
