// app/admin/dashboard/authors/edit/[id]/page.tsx
import AuthorForm from '@/app/components/admin/authors/AuthorForm';
import { authService } from '@/services/auth-service';
import { PERMISSIONS } from '@/lib/permissions';
import { redirect } from 'next/navigation';
import { getTokenFromCookies } from '@/lib/auth-utils';
import { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Edit Author',
  description: 'Edit an existing author in the admin panel.',
};

async function getAuthorData(authorId: string, token: string) {
  try {
    const response = await fetch(
      `${process.env.NEXTAUTH_URL}/api/backend/admin/authors/${authorId}`,
      {
        cache: 'no-store',
        headers: { Authorization: `Bearer ${token}` },
      }
    );
    if (response.ok) return await response.json();
    if (response.status === 404) return null;
  } catch (error) {
    console.error('Failed to fetch author data:', error);
    throw error;
  }
  return null;
}

interface EditAuthorPageProps {
  params: Promise<{ id: string }>;
}

export default async function EditAuthorPage({ params }: EditAuthorPageProps) {
  const { id } = await params;
  const token = await getTokenFromCookies();

  if (!token) redirect('/admin/login');

  const verifiedToken = await authService.verifyToken(token);
  if (!verifiedToken) redirect('/admin/login');

  const hasPermission = await authService.checkUserPermission(
    token,
    PERMISSIONS.AUTHORS_UPDATE
  );

  if (!hasPermission) {
    return (
      <div className="max-w-6xl mx-auto">
        <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&apos;t have permission to edit authors.
          </p>
        </div>
      </div>
    );
  }

  let authorData;
  try {
    authorData = await getAuthorData(id, token);
  } catch {
    return (
      <div className="max-w-6xl mx-auto">
        <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">Error</h1>
          <p className="text-var-danger-text mt-2">
            Failed to load author data. Please try again.
          </p>
        </div>
      </div>
    );
  }

  if (!authorData) {
    return (
      <div className="max-w-6xl mx-auto">
        <div className="text-center py-12">
          <div className="text-var-text-muted">
            <svg
              className="w-12 h-12 mx-auto mb-3 text-var-text-disabled"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
              />
            </svg>
            <p className="text-lg font-medium text-var-text">Author not found</p>
            <p className="text-sm mt-1 text-var-text-muted">
              The author you&apos;re looking for doesn&apos;t exist.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return <AuthorForm authorId={id} initialData={authorData.author} />;
}