import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, 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 TagsSettingsPage from './TagsSettingsPage';

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

beforeEach(() => {
  get.mockReset(); post.mockReset();
  get.mockResolvedValue({ success: true, data: [
    { uuid: 't1', name: 'فوری', color: '#FF0000', active: true },
    { uuid: 't2', name: 'پیگیری', color: '#00AA00', active: false },
  ] });
  post.mockResolvedValue({ success: true, data: { uuid: 't3', name: 'جدید', color: '#5559CE', active: true } });
});

describe('TagsSettingsPage', () => {
  it('lists tenant tags in the settings shell', async () => {
    renderWithProviders(<TagsSettingsPage />, { route: '/admin/tags-settings' });
    expect(await screen.findByText('فوری')).toBeInTheDocument();
    expect(screen.getByText('پیگیری')).toBeInTheDocument();
    expect(screen.getByText('خرید اشتراک')).toBeInTheDocument(); // shell menu
  });

  it('creates a tag through the modal', async () => {
    renderWithProviders(<TagsSettingsPage />, { route: '/admin/tags-settings' });
    await screen.findByText('فوری');

    fireEvent.click(screen.getByRole('button', { name: /برچسب جدید/ }));
    fireEvent.change(screen.getByPlaceholderText('نام برچسب را وارد کنید'), { target: { value: 'اورژانس' } });
    fireEvent.click(screen.getByRole('button', { name: 'ثبت برچسب' }));

    await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/tenant-tag', expect.objectContaining({
      name: 'اورژانس', color: '#d61600', active: true,
    })));
  });

  it('sends the picked preset color and inactive status on create', async () => {
    renderWithProviders(<TagsSettingsPage />, { route: '/admin/tags-settings' });
    await screen.findByText('فوری');

    fireEvent.click(screen.getByRole('button', { name: /برچسب جدید/ }));
    fireEvent.change(screen.getByPlaceholderText('نام برچسب را وارد کنید'), { target: { value: 'بدهکار' } });
    fireEvent.click(screen.getByRole('button', { name: 'رنگ #0088ff' }));
    fireEvent.click(screen.getByRole('checkbox', { name: 'وضعیت برچسب' })); // toggle off (default active)
    fireEvent.click(screen.getByRole('button', { name: 'ثبت برچسب' }));

    await waitFor(() => expect(post).toHaveBeenCalledWith('/api/v1/tenant-tag', expect.objectContaining({
      name: 'بدهکار', color: '#0088ff', active: false,
    })));
  });
});
