import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
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 {},
}));

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));

import { api } from '../lib/api';
import ServiceSegmentsTab from './ServiceSegmentsTab';

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

const SEGMENTS = [
  {
    sequence: 1,
    name: 'آماده‌سازی',
    duration_minutes: 10,
    duration_source: 'fixed',
    patient_present: true,
    mergeable: true,
    requirements: [],
  },
];

function mockApi(segments = SEGMENTS) {
  get.mockImplementation((url: string) => {
    if (url.includes('resource-types')) return Promise.resolve({ data: [] });
    return Promise.resolve({ data: { segments } });
  });
  put.mockResolvedValue({ data: { segments } });
}

describe('ServiceSegmentsTab', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockApi();
  });

  it('loads the service segments it was given', async () => {
    renderWithProviders(<ServiceSegmentsTab serviceUuid="s-1" canEdit />);

    expect(await screen.findByDisplayValue('آماده‌سازی')).toBeInTheDocument();
  });

  /** ⭐ ویرایشگر باید همان چیزی را بفرستد که کاربر می‌بیند، نه یک شکل تازه. */
  it('sends the edited segments back on save', async () => {
    const user = userEvent.setup();

    renderWithProviders(<ServiceSegmentsTab serviceUuid="s-1" canEdit />);

    const name = await screen.findByDisplayValue('آماده‌سازی');
    await user.clear(name);
    await user.type(name, 'ضدعفونی');

    await user.click(screen.getByRole('button', { name: /ذخیرهٔ بخش‌ها/ }));

    await waitFor(() => expect(put).toHaveBeenCalled());

    const [url, body] = put.mock.calls[0];
    expect(url).toBe('/api/v1/service-item/s-1/segments');
    expect(body.segments[0].name).toBe('ضدعفونی');
  });

  /** بدون اجازهٔ ویرایش، فرم فقط خواندنی است — دکمهٔ ذخیره اصلاً نباید باشد. */
  it('renders read-only without the edit permission', async () => {
    renderWithProviders(<ServiceSegmentsTab serviceUuid="s-1" canEdit={false} />);

    const name = await screen.findByDisplayValue('آماده‌سازی');

    expect(name).toBeDisabled();
    expect(screen.queryByRole('button', { name: /ذخیرهٔ بخش‌ها/ })).toBeNull();
  });
});
