import { Suspense } from 'react';
import { redirect } from 'next/navigation';
import Link from 'next/link';
import { getServerSession } from '@/lib/auth/getServerSession';
import { PERMISSIONS } from '@/lib/permissions/permissions';
import AccessDenied from '@/components/admin/errors/AccessDenied';
import AuthorsTable from '@/components/admin/authors/AuthorsTable';
import { AuthorsTableSkeleton } from '@/components/admin/authors/AuthorSkeleton';
import { cookies } from 'next/headers';
import { SESSION_COOKIE } from '@/lib/auth/requireAuth';
import { Metadata } from 'next';
import { internalAuthHeaders } from '@/lib/auth/internalAuth';

export const metadata: Metadata = {
  title: 'Authors',
};

// ─── Data fetchers ────────────────────────────────────────────────────────────

async function getInitialAuthors(sessionToken: string) {
  try {
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
    const res = await fetch(`${baseUrl}/api/authors?page=1&limit=10`, {
      cache: 'no-store',
      headers: { ...internalAuthHeaders(sessionToken) },
    });
    if (!res.ok) throw new Error('Failed to fetch authors');
    const data = await res.json();
    return data.data;
  } catch (error) {
    console.error('Failed to fetch initial authors:', error);
    return {
      authors: [],
      pagination: { page: 1, limit: 10, total: 0, totalPages: 0 },
    };
  }
}

async function getInitialCounts(sessionToken: string) {
  try {
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
    const res = await fetch(`${baseUrl}/api/authors/counts`, {
      cache: 'no-store',
      headers: { ...internalAuthHeaders(sessionToken) },
    });
    if (!res.ok) throw new Error('Failed to fetch counts');
    const data = await res.json();
    return data.data as { active: number; deleted: number };
  } catch (error) {
    console.error('Failed to fetch author counts:', error);
    return { active: 0, deleted: 0 };
  }
}

// ─── Page content ─────────────────────────────────────────────────────────────

async function AuthorsContent() {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get(SESSION_COOKIE)?.value;
  if (!sessionId) redirect('/admin/login');

  const session = await getServerSession();
  if (!session) redirect('/admin/login');
  if (!session.permissions.includes(PERMISSIONS.AUTHORS_READ)) return <AccessDenied />;

  const can = (permission: string) => session.permissions.includes(permission);

  const [initialData, initialCounts] = await Promise.all([
    getInitialAuthors(sessionId),
    getInitialCounts(sessionId),
  ]);

  return (
    <>
      <div className="flex flex-wrap justify-between items-center gap-3 mb-6">
        <div>
          <h1 className="text-2xl font-semibold" style={{ color: 'var(--color-text)' }}>
            Authors
          </h1>
          <p className="text-sm mt-1" style={{ color: 'var(--color-text-secondary)' }}>
            Manage the people credited on blog posts
          </p>
        </div>

        {can(PERMISSIONS.AUTHORS_CREATE) && (
          <Link
            href="/admin/dashboard/authors/new"
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-90"
            style={{ background: 'var(--color-cta)', color: 'white' }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 5v14m-7-7h14"/>
            </svg>
            Add Author
          </Link>
        )}
      </div>

      <AuthorsTable
        canEdit={can(PERMISSIONS.AUTHORS_UPDATE)}
        canDelete={can(PERMISSIONS.AUTHORS_DELETE)}
        canBulkDelete={can(PERMISSIONS.AUTHORS_BULK_DELETE)}
        canViewDeleted={can(PERMISSIONS.AUTHORS_VIEW_DELETED)}
        canPermanentDelete={can(PERMISSIONS.AUTHORS_PERMANENT_DELETE)}
        canRestore={can(PERMISSIONS.AUTHORS_RESTORE)}
        canBulkRestore={can(PERMISSIONS.AUTHORS_BULK_RESTORE)}
        canViewTimeline={can(PERMISSIONS.AUTHORS_VIEW_TIMELINE)}
        canActivateDeactivate={can(PERMISSIONS.AUTHORS_ACTIVATE_DEACTIVATE)}
        initialAuthors={initialData}
        initialCounts={initialCounts}
      />
    </>
  );
}

export default async function AuthorsPage() {
  return (
    <div className="sm:p-6">
      <Suspense fallback={<AuthorsTableSkeleton />}>
        <AuthorsContent />
      </Suspense>
    </div>
  );
}
