import { render, screen, fireEvent } from "@testing-library/react";
import { useGetAllCustomers } from "@/apps/new-ui/services/Customer";
import { MemoryRouter } from "react-router-dom";
import CustomerCard from "@/apps/new-ui/components/AppointmentComponents/CustomerCard";

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

// mock portal و componentهای خارجی
jest.mock("react-dom", () => ({
  ...jest.requireActual("react-dom"),
  createPortal: (node: any) => node,
}));

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

jest.mock("@/apps/new-ui/components/AppointmentComponents/AddCustomer", () => {
  return ({ onclick }: any) => (
    <div data-testid="add-customer">
      <button data-testid="add-customer-done" onClick={onclick}>
        done
      </button>
    </div>
  );
});

jest.mock("@/utils/axios-interceptor", () => ({
  appointmentClient: {
    get: jest.fn(),
    post: jest.fn(),
    put: jest.fn(),
    delete: jest.fn(),
  },
}));

jest.mock("@/apps/new-ui/components/VoiceSearchInput", () => {
  return ({ value, onChange, disabled }: any) => (
    <input
      data-testid="search-input"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      disabled={disabled}
    />
  );
});

jest.mock("@/apps/new-ui/services/Customer");

describe("CustomerCard", () => {
  const mockDispatch = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    localStorage.clear();
  });

  const setup = (mockData: any) => {
    (useGetAllCustomers as jest.Mock).mockReturnValue(mockData);

    return render(
      <MemoryRouter>
        <CustomerCard dispatchEvent={mockDispatch} />
      </MemoryRouter>,
    );
  };

  it("renders loading state", () => {
    setup({ isLoading: true });

    expect(screen.getByText("در حال بارگذاری...")).toBeInTheDocument();
  });

  it("renders error state", () => {
    setup({ isError: true });

    expect(
      screen.getByText("خطا در دریافت اطلاعات مشتریان"),
    ).toBeInTheDocument();
  });

  it("renders empty state", () => {
    setup({ data: { customers: [] } });

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

  it("renders customer list", () => {
    setup({
      data: {
        customers: [
          { id: 1, name: "Ali", phone_number: "0912", customer_type: "NORMAL" },
        ],
      },
    });

    expect(screen.getByText("Ali")).toBeInTheDocument();
    expect(screen.getByText("0912")).toBeInTheDocument();
  });

  it("search works", () => {
    setup({
      data: {
        customers: [
          { id: 1, name: "Ali", phone_number: "0912" },
          { id: 2, name: "Sara", phone_number: "0912333" },
        ],
      },
    });

    const input = screen.getByTestId("search-input");
    fireEvent.change(input, { target: { value: "sar" } });

    expect(screen.queryByText("Ali")).not.toBeInTheDocument();
    expect(screen.getByText("Sara")).toBeInTheDocument();
  });

  it("selects and deselects a customer", () => {
    setup({
      data: {
        customers: [{ id: 1, name: "Ali", phone_number: "0912" }],
      },
    });

    const item = screen.getByText("Ali");

    // select
    fireEvent.click(item);
    expect(localStorage.getItem("selectedCustomerId")).toBe("1");

    // deselect
    fireEvent.click(item);
    expect(localStorage.getItem("selectedCustomerId")).toBe(null);
  });

  it("opens the add customer modal", () => {
    setup({
      data: { customers: [{ id: 1, name: "Ali", phone_number: "09" }] },
    });

    const addBtn = screen.getByRole("button", { name: "" }); // آیکون است
    fireEvent.click(addBtn);

    expect(mockDispatch).toHaveBeenCalledWith("OPEN");
    expect(screen.getByTestId("add-customer")).toBeInTheDocument();
  });

  it("closes modal via add-customer done", () => {
    setup({
      data: { customers: [{ id: 1, name: "Ali", phone_number: "09" }] },
    });

    const addBtn = screen.getByRole("button", { name: "" });
    fireEvent.click(addBtn);

    fireEvent.click(screen.getByTestId("add-customer-done"));

    expect(mockDispatch).toHaveBeenCalledWith("CLOSE");
  });

  it("closes modal with ESC key", () => {
    setup({
      data: { customers: [{ id: 1, name: "Ali", phone_number: "09" }] },
    });

    fireEvent.click(screen.getByRole("button", { name: "" }));

    fireEvent.keyDown(document, { key: "Escape" });

    expect(mockDispatch).toHaveBeenCalledWith("CLOSE");
  });
});
