import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '@cameleer/design-system';
import { ConfigPanel } from './ConfigPanel';
import type { DeploymentPageFormState } from '../hooks/useDeploymentPageState';

const baseDep: any = {
  id: 'd1', appId: 'a', appVersionId: 'v', environmentId: 'e',
  status: 'STOPPED', targetState: 'STOPPED', deploymentStrategy: 'BLUE_GREEN',
  replicaStates: [], deployStage: null, containerId: null, containerName: null,
  errorMessage: null, deployedAt: '2026-04-23T10:35:00Z', stoppedAt: null,
  createdAt: '2026-04-23T10:35:00Z', createdBy: 'alice',
  deployedConfigSnapshot: {
    jarVersionId: 'v', agentConfig: { engineLevel: 'COMPLETE' },
    containerConfig: { memoryLimitMb: 512, replicas: 3 }, sensitiveKeys: ['SECRET'],
  },
};

function wrap(ui: React.ReactNode) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return render(
    <QueryClientProvider client={qc}>
      <ThemeProvider>{ui}</ThemeProvider>
    </QueryClientProvider>,
  );
}

describe('ConfigPanel', () => {
  it('renders sub-tabs in Snapshot mode', () => {
    wrap(<ConfigPanel deployment={baseDep} appSlug="a" envSlug="e" archived={false} />);
    // Use role=tab to avoid matching text inside rendered tab content (e.g. hint text)
    const tabs = screen.getAllByRole('tab');
    const tabLabels = tabs.map((t) => t.textContent ?? '');
    expect(tabLabels.some((l) => /resources/i.test(l))).toBe(true);
    expect(tabLabels.some((l) => /monitoring/i.test(l))).toBe(true);
    expect(tabLabels.some((l) => /variables/i.test(l))).toBe(true);
    expect(tabLabels.some((l) => /sensitive keys/i.test(l))).toBe(true);
  });

  it('hides the Snapshot/Diff toggle when archived', () => {
    wrap(<ConfigPanel deployment={baseDep} appSlug="a" envSlug="e" archived />);
    expect(screen.queryByText(/diff vs current/i)).toBeNull();
  });

  it('hides the toggle when no currentForm provided', () => {
    wrap(<ConfigPanel deployment={baseDep} appSlug="a" envSlug="e" archived={false} />);
    expect(screen.queryByText(/diff vs current/i)).toBeNull();
  });

  it('shows the toggle when currentForm is provided and not archived', () => {
    const currentForm: DeploymentPageFormState = {
      monitoring: {
        engineLevel: 'REGULAR',
        payloadCaptureMode: 'BOTH',
        payloadSize: '4',
        payloadUnit: 'KB',
        applicationLogLevel: 'INFO',
        agentLogLevel: 'INFO',
        metricsEnabled: true,
        metricsInterval: '60',
        samplingRate: '1.0',
        compressSuccess: false,
        replayEnabled: true,
        routeControlEnabled: true,
      },
      resources: {
        memoryLimit: '256', memoryReserve: '', cpuRequest: '500', cpuLimit: '',
        appPort: '8080', replicas: '1', deployStrategy: 'blue-green',
        stripPrefix: true, sslOffloading: true, externalRouting: true, runtimeType: 'auto', customArgs: '',
        extraNetworks: [],
      },
      variables: { envVars: [] },
      sensitiveKeys: { sensitiveKeys: [] },
    };
    wrap(<ConfigPanel deployment={baseDep} appSlug="a" envSlug="e" archived={false} currentForm={currentForm} />);
    expect(screen.getByText(/snapshot/i)).toBeInTheDocument();
    expect(screen.getByText(/diff vs current/i)).toBeInTheDocument();
  });

  it('renders empty-state when no snapshot', () => {
    const noSnap = { ...baseDep, deployedConfigSnapshot: null };
    wrap(<ConfigPanel deployment={noSnap} appSlug="a" envSlug="e" archived={false} />);
    expect(screen.getByText(/no config snapshot/i)).toBeInTheDocument();
  });
});
