// app/admin/dashboard/users/edit/[id]/page.tsx
import UserForm from '@/app/components/admin/users/UserForm';
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 User',
  description: 'Edit an existing user in the admin panel.',
};

async function getUserData(userId: string, token: string) {
  try {
    const response = await fetch(`${process.env.NEXTAUTH_URL}/api/backend/admin/users/${userId}`, {
      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 user data:', error);
    throw error;
  }
  return null;
}

interface EditUserPageProps { params: Promise<{ id: string }>; }

export default async function EditUserPage({ params }: EditUserPageProps) {
  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.USERS_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 users.</p>
        </div>
      </div>
    );
  }

  let userData;
  try {
    userData = await getUserData(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 user data. Please try again.</p>
        </div>
      </div>
    );
  }

  if (!userData) {
    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">User not found</p>
            <p className="text-sm mt-1 text-var-text-muted">The user you&apos;re looking for doesn&apos;t exist.</p>
          </div>
        </div>
      </div>
    );
  }

  return <UserForm userId={id} initialData={userData.user} />;
}