import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import CreateLinkDialog from '@/app/components/profile/CreateLinkDialog';
import EditLinkDialog from '@/app/components/profile/EditLinkDialog';
import type { PlanFeatures } from '@/lib/plans/types';
import type { ProfileLinkItem } from '@/app/components/profile/types';

jest.mock('@/app/components/TemplateSelector', () => {
  function MockTemplateSelector() {
    return <div data-testid="template-selector" />;
  }

  return MockTemplateSelector;
});

jest.mock('@/app/components/UTMBuilder', () => {
  function MockUTMBuilder() {
    return <div data-testid="utm-builder" />;
  }

  return MockUTMBuilder;
});

jest.mock('@/app/components/OGEditor', () => {
  function MockOGEditor() {
    return <div data-testid="og-editor" />;
  }

  return MockOGEditor;
});
jest.mock('@/app/components/ToastProvider', () => ({
  useToast: () => ({
    success: jest.fn(),
    error: jest.fn(),
    info: jest.fn(),
  }),
}));
jest.mock('@/lib/runtime-client-config', () => ({
  getRuntimeClientConfig: () => ({
    domain: 'snap.link',
    timeZone: 'Europe/Moscow',
    projectName: 'SnapLink',
  }),
}));

const PLAN_FEATURES: PlanFeatures = {
  customSlug: true,
  password: true,
  expiresAt: true,
  clickLimit: true,
  telegramClickNotifications: true,
  bulkActions: true,
  csvExport: true,
  pdfExport: true,
  manualOgEditing: true,
};

const BASE_LINK: ProfileLinkItem = {
  id: 'link-1',
  shortUrl: 'https://snap.link/my-link',
  longUrl: 'https://example.com',
  slug: 'my-link',
  clicks: 0,
  title: 'My link',
  description: null,
  ogTitle: null,
  ogDescription: null,
  ogImage: null,
  isActive: true,
  expiresAt: null,
  clickLimit: null,
  telegramClickNotificationsEnabled: false,
  hasPassword: false,
  isFavorite: false,
  folder: null,
  tags: [],
  createdAt: new Date('2026-04-24T00:00:00.000Z').toISOString(),
};

describe('telegram click notifications toggle in link dialogs', () => {
  const originalFetch = global.fetch;

  afterEach(() => {
    global.fetch = originalFetch;
    jest.resetAllMocks();
  });

  it('shows explicit error when enabling in create dialog without configured token', async () => {
    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      json: async () => ({
        clickNotifications: {
          hasBotToken: false,
          featureAvailableByPlan: true,
          canSendToUserNow: false,
        },
      }),
    }) as unknown as typeof fetch;

    render(
      <CreateLinkDialog
        isOpen
        onClose={jest.fn()}
        onCreated={jest.fn()}
        planFeatures={PLAN_FEATURES}
      />,
    );

    await waitFor(() => {
      expect(screen.getByText('Токен бота не настроен. Добавьте токен в настройках профиля.')).toBeInTheDocument();
    });

    fireEvent.click(screen.getByLabelText('Переключить Telegram-уведомления о кликах'));

    expect(screen.getByText('Токен Telegram-бота не настроен. Добавьте его в настройках профиля.')).toBeInTheDocument();
  });

  it('allows enabling toggle in edit dialog when token is configured', async () => {
    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      json: async () => ({
        clickNotifications: {
          hasBotToken: true,
          featureAvailableByPlan: true,
          canSendToUserNow: true,
        },
      }),
    }) as unknown as typeof fetch;

    render(
      <EditLinkDialog
        isOpen
        link={BASE_LINK}
        planFeatures={PLAN_FEATURES}
        onClose={jest.fn()}
        onSaved={jest.fn()}
      />,
    );

    await waitFor(() => {
      expect(screen.getByText('Токен бота настроен.')).toBeInTheDocument();
    });

    const toggle = screen.getByLabelText('Переключить Telegram-уведомления о кликах');
    fireEvent.click(toggle);

    expect(toggle).toHaveAttribute('aria-pressed', 'true');
  });
});
