// app/admin/dashboard/categories/edit/[id]/page.tsx
import CategoryForm from '@/app/components/admin/categories/CategoryForm';
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 Category',
  description: 'Edit an existing category in the admin panel.',
};

async function getCategoryData(categoryId: string, token: string) {
  try {
    const response = await fetch(`${process.env.NEXTAUTH_URL}/api/backend/admin/categories/${categoryId}`, {
      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 category data:', error);
    throw error;
  }
  
  return null;
}

interface EditCategoryPageProps {
  params: Promise<{ id: string }>;
}

export default async function EditCategoryPage({ params }: EditCategoryPageProps) {
  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.CATEGORIES_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`t have permission to edit categories.
          </p>
        </div>
      </div>
    );
  }

  let categoryData;
  try {
    categoryData = await getCategoryData(id, token);
  } catch (error) {
    console.error('Failed to fetch category data:', error);
    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 category data. Please try again.
          </p>
        </div>
      </div>
    );
  }

  if (!categoryData) {
    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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <p className="text-lg font-medium text-var-text">Category not found</p>
            <p className="text-sm mt-1 text-var-text-muted">The category you`re looking for doesn`t exist.</p>
          </div>
        </div>
      </div>
    );
  }

  return <CategoryForm categoryId={id} initialData={categoryData.category} />;
}