import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import fs from 'node:fs';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import AcademicsPage from '../app/academics/page';
import LoginPage from '../app/login/page';
import VerificationsPage from '../app/verifications/page';
import { toProxyAssetUrl, type AcademicOverviewPayload } from '../lib/proxy-client';
import { AdminShell } from './admin-shell';
import { HealthStatusCard } from './health-status-card';

const pushMock = vi.fn();

vi.mock('next/navigation', () => ({
  useRouter: () => ({ push: pushMock }),
  usePathname: () => '/',
}));

describe('Admin Web Phase 2 Portal & Shell UI', () => {
  afterEach(() => {
    vi.restoreAllMocks();
    pushMock.mockReset();
  });

  it('AdminShell renders SAIC branding, Phase 2 nav links, and responsive drawer toggle', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(JSON.stringify({ success: false }), { status: 401 }),
    );

    render(
      <AdminShell>
        <div>Shell body</div>
      </AdminShell>,
    );

    expect(screen.getByText('SAIC Administration')).toBeInTheDocument();
    expect(screen.getByRole('navigation', { name: 'Admin navigation' })).toBeInTheDocument();
    expect(screen.getByRole('link', { name: /Verification Queue/i })).toHaveAttribute(
      'href',
      '/verifications',
    );
    expect(screen.getByRole('link', { name: /Academics/i })).toHaveAttribute('href', '/academics');
    expect(screen.getByRole('link', { name: /Teachers/i })).toHaveAttribute('href', '/teachers');

    const toggleButton = screen.getByRole('button', { name: 'Toggle navigation menu' });
    expect(toggleButton).toHaveAttribute('aria-expanded', 'false');
    fireEvent.click(toggleButton);
    expect(toggleButton).toHaveAttribute('aria-expanded', 'true');
  });

  it('HealthStatusCard parses single /api/health envelope and renders backend status', async () => {
    const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(
        JSON.stringify({
          success: true,
          data: {
            status: 'ok',
            database: 'up',
            timestampUtc: '2026-11-26T12:30:00.000Z',
            storageDriver: 'local',
          },
        }),
        { status: 200, headers: { 'content-type': 'application/json' } },
      ),
    );

    render(<HealthStatusCard />);

    await waitFor(() => {
      expect(screen.getByText('ok')).toBeInTheDocument();
    });
    expect(screen.getByText('up')).toBeInTheDocument();
    expect(screen.getByText('local')).toBeInTheDocument();
    expect(screen.getByText('2026-11-26T12:30:00.000Z')).toBeInTheDocument();
    expect(fetchMock).toHaveBeenCalledWith('/api/health', {
      method: 'GET',
      cache: 'no-store',
    });
  });

  it('HealthStatusCard displays graceful alert when backend is unreachable', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(
        JSON.stringify({
          success: false,
          error: {
            code: 'BACKEND_UNAVAILABLE',
            message: 'Backend API is unreachable',
          },
        }),
        { status: 503, headers: { 'content-type': 'application/json' } },
      ),
    );

    render(<HealthStatusCard />);

    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent('Backend API is unreachable');
    });
  });

  it('LoginPage submits to same-origin /api/auth/login without writing tokens to browser storage', async () => {
    const localSetItem = vi.spyOn(Storage.prototype, 'setItem');
    const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(
        JSON.stringify({
          success: true,
          data: {
            authenticated: true,
            user: { roles: ['SUPER_ADMIN'] },
          },
        }),
        { status: 200, headers: { 'content-type': 'application/json' } },
      ),
    );

    render(<LoginPage />);

    fireEvent.change(screen.getByLabelText('Email address'), {
      target: { value: 'admin@saic.edu.example' },
    });
    fireEvent.change(screen.getByLabelText('Password'), {
      target: { value: 'StrongPass123!' },
    });
    fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));

    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent(
        'Session established via HTTP-only cookie proxy.',
      );
    });
    expect(pushMock).toHaveBeenCalledWith('/verifications');
    expect(fetchMock).toHaveBeenCalledWith(
      '/api/auth/login',
      expect.objectContaining({ method: 'POST' }),
    );
    expect(localSetItem).not.toHaveBeenCalled();

    const loginSrc = fs.readFileSync(path.resolve(process.cwd(), 'src/app/login/page.tsx'), 'utf8');
    expect(loginSrc).not.toContain('localStorage');
    expect(loginSrc).not.toContain('sessionStorage');
    expect(loginSrc).not.toContain('SESSION_SECRET');
  });

  it('toProxyAssetUrl routes /api/v1/ private storage URLs through same-origin /api/proxy', () => {
    expect(toProxyAssetUrl('/api/v1/storage/download?key=abc&sig=123')).toBe(
      '/api/proxy/storage/download?key=abc&sig=123',
    );
    expect(toProxyAssetUrl('https://s3.example.com/presigned')).toBe(
      'https://s3.example.com/presigned',
    );
  });

  // Regression test for R-2: AcademicOverviewPayload.programs must use
  // `degreeLevel` (matching the Prisma model field) instead of `level`.
  it('AcademicsPage renders program degreeLevel from backend AcademicOverviewPayload (R-2 regression)', async () => {
    const mockOverview: AcademicOverviewPayload = {
      institution: { id: 'inst-1', code: 'SAIC', name: 'SAIC Institute' },
      programs: [
        {
          id: 'p-1',
          code: 'DIPL',
          name: 'Diploma in Engineering',
          degreeLevel: 'DIPLOMA',
          isActive: true,
        },
      ],
      departments: [
        {
          id: 'd-1',
          programId: 'p-1',
          code: 'CST',
          name: 'Computer Science & Technology',
          isActive: true,
        },
      ],
      sessions: [],
      terms: [],
      batches: [],
      sections: [],
      subjects: [],
      offerings: [],
    };

    vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
      const url =
        typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
      if (url.startsWith('/api/auth/session')) {
        return new Response(JSON.stringify({ success: true, data: { authenticated: true } }), {
          status: 200,
        });
      }
      if (url.startsWith('/api/proxy/admin/academics/overview')) {
        return new Response(JSON.stringify({ success: true, data: mockOverview }), {
          status: 200,
        });
      }
      return new Response(JSON.stringify({ success: false }), { status: 404 });
    });

    render(<AcademicsPage />);

    await waitFor(() => {
      expect(screen.getByText('Diploma in Engineering (DIPL)')).toBeInTheDocument();
    });
    expect(screen.getByText(/Level: DIPLOMA • 1 departments/)).toBeInTheDocument();
  });

  it('VerificationsPage renders queue items, inspects signed College ID image, and validates rejection reason', async () => {
    vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
      const url =
        typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
      if (url.startsWith('/api/auth/session')) {
        return new Response(JSON.stringify({ success: true, data: { authenticated: true } }), {
          status: 200,
        });
      }
      if (url.startsWith('/api/proxy/admin/verifications/req-1')) {
        return new Response(
          JSON.stringify({
            success: true,
            data: {
              id: 'req-1',
              status: 'PENDING_VERIFICATION',
              attemptNumber: 1,
              submittedStudentIdNumber: 'SAIC-2026-001',
              submittedAtUtc: '2026-11-26T12:00:00.000Z',
              reviewedAtUtc: null,
              rejectionReason: null,
              reviewNotes: null,
              hasDuplicateConflict: true,
              collegeIdSignedUrl: '/api/v1/storage/download?key=college_id%2Fid.png',
              student: {
                profileId: 'prof-1',
                userId: 'user-1',
                fullName: 'Amina Rahman',
                email: 'amina@saic.edu.example',
                phone: '+8801711111111',
                accountStatus: 'PENDING_VERIFICATION',
                program: { id: 'p1', code: 'DIPLOMA', name: 'Diploma' },
                department: { id: 'd1', code: 'CST', name: 'Computer Science & Technology' },
                session: { id: 's1', code: '2025-26', name: '2025-26' },
                term: { id: 't1', name: '1st Semester' },
                batch: { id: 'b1', code: 'CST-25', name: 'CST-25' },
                section: { id: 'sec1', code: 'A', name: 'Section A' },
              },
            },
          }),
          { status: 200 },
        );
      }
      return new Response(
        JSON.stringify({
          success: true,
          data: [
            {
              id: 'req-1',
              status: 'PENDING_VERIFICATION',
              attemptNumber: 1,
              submittedStudentIdNumber: 'SAIC-2026-001',
              submittedAtUtc: '2026-11-26T12:00:00.000Z',
              reviewedAtUtc: null,
              rejectionReason: null,
              hasDuplicateConflict: true,
              student: {
                profileId: 'prof-1',
                userId: 'user-1',
                fullName: 'Amina Rahman',
                email: 'amina@saic.edu.example',
                phone: '+8801711111111',
                accountStatus: 'PENDING_VERIFICATION',
                program: { id: 'p1', code: 'DIPLOMA', name: 'Diploma' },
                department: { id: 'd1', code: 'CST', name: 'Computer Science & Technology' },
                session: { id: 's1', code: '2025-26', name: '2025-26' },
                term: { id: 't1', name: '1st Semester' },
                batch: { id: 'b1', code: 'CST-25', name: 'CST-25' },
                section: { id: 'sec1', code: 'A', name: 'Section A' },
              },
            },
          ],
        }),
        { status: 200 },
      );
    });

    render(<VerificationsPage />);

    await waitFor(() => {
      expect(screen.getByText('Amina Rahman')).toBeInTheDocument();
    });
    expect(screen.getByText('Duplicate ID Conflict')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Inspect' }));

    await waitFor(() => {
      const img = screen.getByAltText('College ID card for Amina Rahman');
      expect(img).toHaveAttribute('src', '/api/proxy/storage/download?key=college_id%2Fid.png');
    });

    fireEvent.click(screen.getByRole('button', { name: 'Reject Submission' }));
    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent('at least 5 characters');
    });
  });
});
