import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';

vi.mock('../lib/api', () => ({
  api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
  ApiError: class extends Error {},
}));

import { api } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import ReserveAppointmentsPage from './ReserveAppointmentsPage';

const get = api.get as ReturnType<typeof vi.fn>;

beforeEach(() => {
  get.mockReset();
  useAuthStore.setState({ primaryRole: 'doctor', dbUuid: 'doc1' } as any);
  get.mockImplementation((url: string) => {
    if (url.startsWith('/api/v1/my/appointments?reserve=1')) return Promise.resolve({
      success: true,
      data: [{
        uuid: 'r1', patient_name: 'دنیا خلیلی', patient_mobile: '09165401233',
        doctor_uuid: 'doc1', doctor_name: 'دکتر احمدی',
        slot_start: 1735639200, slot_end: 1735639200,
        appointment_date: '2024-12-31', appointment_time: '00:00', end_time: '00:00',
        status: 'pending', version: 1, created_at: '', is_reserve: true,
        service_item: { uuid: 'i1', name: 'لیزر توتال' }, staff: { uuid: 's1', full_name: 'سحر ایمانی' },
      }],
      meta: { totalRecords: 1, totalPages: 1, currentPage: 1 },
    });
    return Promise.resolve({ success: true, data: [] });
  });
});

describe('ReserveAppointmentsPage (نوبت های رزرو شده)', () => {
  it('lists reserve entries with the design columns', async () => {
    renderWithProviders(<ReserveAppointmentsPage />);
    expect(screen.getByText('نوبت های رزرو شده')).toBeInTheDocument();
    expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
    expect(screen.getByText('لیزر توتال')).toBeInTheDocument();
    expect(screen.getByText('سحر ایمانی')).toBeInTheDocument();
    expect(screen.getByText('تاریخ')).toBeInTheDocument();
    // fetched with the reserve flag
    expect(get.mock.calls.some(([u]) => String(u).includes('reserve=1'))).toBe(true);
  });

  it('row menu offers only the three reserve actions', async () => {
    renderWithProviders(<ReserveAppointmentsPage />);
    await screen.findByText('دنیا خلیلی');
    fireEvent.click(screen.getByRole('button', { name: 'عملیات' }));
    expect(screen.getByText('مشاهده')).toBeInTheDocument();
    expect(screen.getByText('ویرایش')).toBeInTheDocument();
    expect(screen.getByText('انتقال به لیست نوبت ها')).toBeInTheDocument();
    expect(screen.queryByText('جایگزینی نوبت')).toBeNull();
  });

  it('opens the reserve create drawer from «نوبت رزرو»', async () => {
    renderWithProviders(<ReserveAppointmentsPage />);
    await screen.findByText('دنیا خلیلی');
    fireEvent.click(screen.getByRole('button', { name: /نوبت رزرو$/ }));
    expect(await screen.findByText('اضافه کردن نوبت رزرو')).toBeInTheDocument();
  });
});
