// app/admin/dashboard/redirects/edit/[id]/page.tsx
import RedirectForm from '@/app/components/admin/redirects/RedirectForm';
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 Redirect',
  description: 'Edit an existing URL redirect in the admin panel.',
};

async function getRedirectData(redirectId: string, token: string) {
  try {
    const response = await fetch(
      `${process.env.NEXTAUTH_URL}/api/backend/admin/redirects/${redirectId}`,
      {
        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 redirect data:', error);
    throw error;
  }
  return null;
}

interface EditRedirectPageProps {
  params: Promise<{ id: string }>;
}

export default async function EditRedirectPage({ params }: EditRedirectPageProps) {
  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.REDIRECTS_UPDATE);
  if (!hasPermission) {
    return (
      <div className="max-w-3xl 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 redirects.
          </p>
        </div>
      </div>
    );
  }

  let redirectData;
  try {
    redirectData = await getRedirectData(id, token);
  } catch {
    return (
      <div className="max-w-3xl 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 redirect data. Please try again.
          </p>
        </div>
      </div>
    );
  }

  if (!redirectData) {
    return (
      <div className="max-w-3xl mx-auto">
        <div className="text-center py-12">
          <svg className="w-12 h-12 mx-auto mb-3 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
          </svg>
          <p className="text-lg font-medium text-var-text">Redirect not found</p>
          <p className="text-sm text-var-text-muted mt-1">
            The redirect you&apos;re looking for doesn&apos;t exist.
          </p>
        </div>
      </div>
    );
  }

  return <RedirectForm redirectId={id} initialData={redirectData.redirect} />;
}