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

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
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 AppointmentSettingsPage from './AppointmentSettingsPage';

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

beforeEach(() => {
  get.mockReset();
  useAuthStore.setState({ primaryRole: 'doctor', doctorUuid: 'doc-1', dbUuid: 'doc-1' });
  get.mockImplementation((url: string) => {
    if (url.includes('/doctor/doc-1')) return Promise.resolve({ success: true, data: { data: { address: [] } } });
    if (url.includes('/weekly-schedule')) return Promise.resolve({ success: true, data: {} });
    return Promise.resolve({ success: true, data: {} });
  });
});

describe('AppointmentSettingsPage', () => {
  it('renders the weekly-schedule section inside the settings shell', async () => {
    renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });
    // appears in the shell menu and as the page heading
    expect((await screen.findAllByText('مدیریت نوبت دهی')).length).toBeGreaterThan(1);
    expect(screen.getByText('خرید اشتراک')).toBeInTheDocument(); // shell menu
  });

  it('renders the free-visit price card (moved here from insurance page)', async () => {
    renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });
    expect(await screen.findByText('قیمت ویزیت آزاد')).toBeInTheDocument();
  });

  it('shows the free-visit price card even when no doctor uuid is present', async () => {
    useAuthStore.setState({ primaryRole: 'clinic', doctorUuid: null, dbUuid: null });
    renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });
    expect(await screen.findByText('قیمت ویزیت آزاد')).toBeInTheDocument();
    expect(screen.getByText('این بخش فقط برای پزشک در دسترس است.')).toBeInTheDocument();
  });

  it('پزشک عضو کلینیک بدون مطب شخصی: پیش‌فرض روی کلینیک، بدون پیام «ابتدا آدرس مطب»', async () => {
    get.mockImplementation((url: string) => {
      if (url === '/api/v1/doctor/doc-1')
        return Promise.resolve({ success: true, data: { data: { uuid: 'doc-1', clinics: [{ uuid: 'clinicX', name: 'کلینیک الف' }] } } });
      // مطب شخصی مکانی ندارد → پیش‌فرض باید کلینیک شود
      if (url === '/api/v1/appointment-settings/available-locations/doc-1')
        return Promise.resolve({ success: true, data: { data: [] } });
      if (url.includes('available-locations/doc-1?clinic_uuid=clinicX'))
        return Promise.resolve({ success: true, data: { data: [{ id: '5', uuid: 'addr5', type: 'clinic', clinic_id: '9', clinic_name: 'کلینیک الف' }] } });
      if (url.includes('/weekly-schedule')) return Promise.resolve({ success: true, data: { data: null } });
      return Promise.resolve({ success: true, data: {} });
    });

    renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });

    expect(await screen.findByText('محیط نوبت‌دهی')).toBeInTheDocument();
    await waitFor(() =>
      expect(get).toHaveBeenCalledWith(expect.stringContaining('available-locations/doc-1?clinic_uuid=clinicX')),
    );
    expect(screen.queryByText('ابتدا آدرس مطب را ثبت کنید')).not.toBeInTheDocument();
  });

  it('پزشک بدون کلینیک: انتخابگر محیط نمایش داده نمی‌شود', async () => {
    get.mockImplementation((url: string) => {
      if (url === '/api/v1/doctor/doc-1')
        return Promise.resolve({ success: true, data: { data: { uuid: 'doc-1', clinics: [] } } });
      if (url === '/api/v1/appointment-settings/available-locations/doc-1')
        return Promise.resolve({ success: true, data: { data: [] } });
      if (url.includes('/weekly-schedule')) return Promise.resolve({ success: true, data: { data: null } });
      return Promise.resolve({ success: true, data: {} });
    });

    renderWithProviders(<AppointmentSettingsPage />, { route: '/admin/appointment-settings' });

    await screen.findByText('قیمت ویزیت آزاد');
    await waitFor(() => expect(get).toHaveBeenCalledWith('/api/v1/doctor/doc-1'));
    expect(screen.queryByText('محیط نوبت‌دهی')).not.toBeInTheDocument();
  });
});
