import { fireEvent, render, screen } from '@testing-library/react';
import PlanSummaryCard from '@/app/components/PlanSummaryCard';
import PeriodSelector from '@/app/components/PeriodSelector';
import LinkEditModal from '@/app/components/LinkEditModal';
import LinkActions from '@/app/components/LinkActions';
import { ToastProvider } from '@/app/components/ToastProvider';
import type { PlanFeatures, PlanLimits, PlanUsage } from '@/lib/plans/types';

const FREE_FEATURES: PlanFeatures = {
  customSlug: false,
  password: false,
  expiresAt: false,
  clickLimit: false,
  telegramClickNotifications: false,
  bulkActions: false,
  csvExport: false,
  pdfExport: false,
  manualOgEditing: false,
};

const EMPTY_LIMITS: PlanLimits = {
  maxActiveLinks: 75,
  maxMonthlyNewLinks: 200,
  maxFolders: 15,
  maxTags: 100,
  maxUtmTemplates: 10,
};

const EMPTY_USAGE: PlanUsage = {
  activeLinks: 10,
  newLinksThisMonth: 15,
  folders: 2,
  tags: 5,
  utmTemplates: 1,
};

const BASE_LINK = {
  id: 'link-1',
  shortUrl: 'https://snap.link/l/test',
  longUrl: 'https://example.com',
  title: 'Test link',
  description: 'Desc',
  ogTitle: null,
  ogDescription: null,
  ogImage: null,
  hasPassword: false,
};

function renderWithToast(ui: React.ReactElement) {
  return render(<ToastProvider>{ui}</ToastProvider>);
}

describe('profile plan UI', () => {
  it('renders plan summary with plan/usage data', () => {
    render(
      <PlanSummaryCard
        plan="MINIMAL"
        limits={EMPTY_LIMITS}
        usage={EMPTY_USAGE}
        availableAnalyticsPeriods={[7, 30]}
        planMeta={{
          id: 'MINIMAL',
          label: 'MINIMAL',
          audience: 'Активный персональный пользователь',
          price: { monthlyUsdCents: 149, yearlyUsdCents: 1430, yearlyDiscountPercent: 20 },
        }}
        billingSource="PURCHASE"
        expiresAt="2026-05-18T12:30:00.000Z"
        hasActiveOverride={false}
      />
    );

    expect(screen.getByText('Текущий тариф')).toBeInTheDocument();
    expect(screen.getByText('MINIMAL · $1.49/month')).toBeInTheDocument();
    expect(screen.getByText('Источник: Оплачен')).toBeInTheDocument();
    expect(screen.getByText(/Активен до:/)).toBeInTheDocument();
    expect(screen.getByText('Активные ссылки')).toBeInTheDocument();
    expect(screen.getByText('10/75')).toBeInTheDocument();
    expect(screen.getByText('Периоды аналитики: 7 дн, 30 дн')).toBeInTheDocument();

    // «Продлить» намеренно убран: платный тариф не требует отдельного CTA на
    // продление — только «Сменить тариф» на страницу тарифов.
    expect(screen.queryByRole('link', { name: 'Продлить' })).not.toBeInTheDocument();
    expect(screen.getByRole('link', { name: 'Сменить тариф' })).toHaveAttribute('href', '/profile/pricing');
  });

  it('routes pending invoice action to internal billing checkout', () => {
    render(
      <PlanSummaryCard
        plan="MINIMAL"
        limits={EMPTY_LIMITS}
        usage={EMPTY_USAGE}
        availableAnalyticsPeriods={[7, 30]}
        planMeta={{
          id: 'MINIMAL',
          label: 'MINIMAL',
          audience: 'Активный персональный пользователь',
          price: { monthlyUsdCents: 149, yearlyUsdCents: 1430, yearlyDiscountPercent: 20 },
        }}
        currentPendingInvoice={{
          id: 'invoice-1',
          plan: 'EXTENDED',
          interval: 'YEARLY',
          expiresAt: '2026-05-18T12:30:00.000Z',
          invoiceUrl: 'https://pay.crypt.bot/invoice/1001',
          miniAppInvoiceUrl: null,
          webAppInvoiceUrl: null,
        }}
      />
    );

    const pendingLink = screen.getByRole('link', { name: 'Открыть оплату в биллинге' });
    expect(pendingLink).toHaveAttribute('href', '/billing/checkout?plan=EXTENDED&interval=YEARLY');
  });

  it('shows only allowed periods in PeriodSelector and excludes all-time option', () => {
    const onChange = jest.fn();

    render(<PeriodSelector period="7" onChange={onChange} availablePeriods={[7, 30]} />);

    expect(screen.getByRole('button', { name: '7 дней' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: '30 дней' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '90 дней' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /all/i })).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: '30 дней' }));
    expect(onChange).toHaveBeenCalledWith('30');
  });

  it('hides premium controls in LinkEditModal for FREE plan', () => {
    renderWithToast(
      <LinkEditModal
        link={BASE_LINK}
        planFeatures={FREE_FEATURES}
        onClose={jest.fn()}
        onSave={jest.fn()}
      />
    );

    expect(screen.getByText('Ручное OG-редактирование недоступно на текущем тарифе.')).toBeInTheDocument();
    expect(screen.getByText('Срок действия и лимит кликов недоступны на текущем тарифе.')).toBeInTheDocument();
    expect(screen.getByText('Защита ссылок паролем недоступна на текущем тарифе.')).toBeInTheDocument();

    expect(screen.queryByLabelText('OG Заголовок (для соцсетей)')).not.toBeInTheDocument();
    expect(screen.queryByLabelText('Срок действия')).not.toBeInTheDocument();
    expect(screen.queryByLabelText('Лимит кликов')).not.toBeInTheDocument();
    expect(screen.queryByLabelText('Пароль ссылки')).not.toBeInTheDocument();
  });

  it('shows disabled export actions with upgrade hints in LinkActions for FREE plan', () => {
    renderWithToast(
      <LinkActions
        link={BASE_LINK}
        period="7"
        planFeatures={FREE_FEATURES}
        onUpdate={jest.fn()}
        onDelete={jest.fn()}
      />
    );

    expect(screen.getByText('CSV-экспорт недоступен на текущем тарифе. Обновите тариф до Lite или выше.')).toBeInTheDocument();

    const csvButton = screen.getByRole('button', { name: 'CSV недоступен' });
    const htmlButton = screen.getByRole('button', { name: 'HTML недоступен' });

    expect(csvButton).toBeDisabled();
    expect(htmlButton).toBeDisabled();
    expect(csvButton).toHaveAttribute('title', 'CSV-экспорт доступен начиная с тарифа Lite.');
    expect(htmlButton).toHaveAttribute('title', 'HTML-экспорт доступен начиная с тарифа Pro.');
  });
});
