// app/admin/dashboard/audit-logs/page.tsx
import { Suspense } from 'react';
import { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import AuditLogsClient from './AuditLogsClient';
import { authService } from '@/services/auth-service';
import { PERMISSIONS } from '@/lib/permissions';
import { AuditLog } from '@/types/audit-log';

export const metadata: Metadata = {
  title: 'Audit Logs | Admin Dashboard',
  description: 'Monitor and track all system activities, user actions, and changes across the platform.',
  robots: 'noindex, nofollow',
};

interface AuditLogsResponse {
  logs: AuditLog[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    pages: number;
  };
  filters: {
    actions: string[];
    resourceTypes: string[];
  };
}

async function fetchInitialAuditLogs(token: string): Promise<AuditLogsResponse | null> {
  try {
    const baseUrl = process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
    
    const response = await fetch(`${baseUrl}/api/backend/admin/audit-logs?page=1&limit=10`, {
      cache: 'no-store',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
    
    if (response.ok) return await response.json();
    if (response.status === 403) console.error('Forbidden access to audit logs');
    return null;
  } catch (error) {
    console.error('Failed to fetch initial audit logs data:', error);
    return null;
  }
}

function ErrorDisplay({ error }: { error: Error }) {
  return (
    <div className="min-h-screen bg-var-bg p-6">
      <div className="max-w-7xl mx-auto">
        <div className="bg-var-danger-bg border border-var-danger-border rounded-lg p-4">
          <div className="flex">
            <div className="shrink-0">
              <svg className="h-5 w-5 text-var-danger" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <h3 className="text-sm font-medium text-var-danger-text">Error Loading Audit Logs</h3>
              <p className="text-sm text-var-danger-text mt-1">{error.message}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AccessDenied() {
  return (
    <div className="space-y-6">
      <div className="bg-var-danger-bg border border-var-danger-border rounded-2xl p-6 text-center">
        <h1 className="text-2xl font-bold text-var-danger-text">Access Denied</h1>
        <p className="text-var-danger-text mt-2">You don`t have permission to view audit logs.</p>
      </div>
    </div>
  );
}

function LoadingDisplay() {
  return (
    <div className="min-h-screen bg-var-bg p-6">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <div className="h-9 w-48 bg-var-surface-hover rounded animate-pulse"></div>
          <div className="h-5 w-96 bg-var-surface-hover rounded mt-2 animate-pulse"></div>
        </div>
        <div className="bg-var-surface rounded-lg shadow-var-card border border-var-border">
          <div className="p-6">
            <div className="space-y-4">
              <div className="h-10 bg-var-surface-hover rounded animate-pulse"></div>
              <div className="space-y-3">
                <div className="h-16 bg-var-surface-hover rounded animate-pulse"></div>
                <div className="h-16 bg-var-surface-hover rounded animate-pulse"></div>
                <div className="h-16 bg-var-surface-hover rounded animate-pulse"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default async function AuditLogsPage() {
  const cookieStore = await cookies();
  const token = cookieStore.get('admin_token')?.value || null;
  
  if (!token) redirect('/admin/login');

  const hasPermission = await authService.checkUserPermission(token, PERMISSIONS.AUDIT_LOGS_READ);
  if (!hasPermission) return <AccessDenied />;

  const initialData = await fetchInitialAuditLogs(token);
  if (!initialData) return <ErrorDisplay error={new Error('Failed to load audit logs. Please try again later.')} />;

  return (
    <Suspense fallback={<LoadingDisplay />}>
      <AuditLogsClient
        initialLogs={initialData.logs}
        initialPagination={initialData.pagination}
        filterOptions={initialData.filters}
      />
    </Suspense>
  );
}