import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../../theme';

const useUserSearchMock = jest.fn();
jest.mock('@/services/admin', () => ({ useUserSearch: (...args: unknown[]) => useUserSearchMock(...args) }));
jest.mock('@/services/search', () => ({ useDebouncedValue: (value: unknown) => value }));

import UserPicker from './UserPicker';
import type { AdminUserSummary } from '@/services/admin/types';

const MARYAM: AdminUserSummary = { id: 2, displayName: 'مریم احمدی', maskedPhone: '0912•••0002', roles: ['admin'] };

describe('<UserPicker/>', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);

  beforeEach(() => {
    useUserSearchMock.mockReset();
    useUserSearchMock.mockReturnValue({ data: [MARYAM], isFetching: false });
  });

  it('renders the label and, once opened, an option with name + masked phone + id', async () => {
    const user = userEvent.setup();
    wrap(<UserPicker value={null} onChange={jest.fn()} label="کاربر" />);
    const input = screen.getByLabelText('کاربر');
    await user.click(input);
    expect(await screen.findByText('مریم احمدی')).toBeInTheDocument();
    expect(screen.getByText('0912•••0002 · #2')).toBeInTheDocument();
  });

  it('calls onChange with the selected user on pick', async () => {
    const onChange = jest.fn();
    const user = userEvent.setup();
    wrap(<UserPicker value={null} onChange={onChange} label="کاربر" />);
    await user.click(screen.getByLabelText('کاربر'));
    await user.click(await screen.findByText('مریم احمدی'));
    expect(onChange).toHaveBeenCalledWith(MARYAM);
  });

  it('passes the typed query + roleFilter through to useUserSearch', async () => {
    const user = userEvent.setup();
    wrap(<UserPicker value={null} onChange={jest.fn()} label="پرستار" roleFilter="nurse" />);
    await user.type(screen.getByLabelText('پرستار'), 'زهرا');
    await waitFor(() => expect(useUserSearchMock).toHaveBeenLastCalledWith('زهرا', 'nurse'));
  });
});
