// app/admin/dashboard/websites/edit/[id]/page.tsx
import WebsiteForm from '@/app/components/admin/websites/WebsiteForm';
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 Website',
  description: 'Edit an existing website in the admin panel.',
};

async function getWebsiteData(websiteId: string, token: string) {
  try {
    const response = await fetch(`${process.env.NEXTAUTH_URL}/api/backend/admin/websites/${websiteId}`, {
      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 website data:', error);
    throw error;
  }
  
  return null;
}

interface EditWebsitePageProps {
  params: Promise<{ id: string }>;
}

export default async function EditWebsitePage({ params }: EditWebsitePageProps) {
  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.WEBSITES_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">Access Denied</h1>
          <p className="text-var-danger-text mt-2">
            You don`t have permission to edit websites.
          </p>
        </div>
      </div>
    );
  }

  let websiteData;
  try {
    websiteData = await getWebsiteData(id, token);
  } catch (error) {
    console.error('Failed to fetch website 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">Error</h1>
          <p className="text-var-danger-text mt-2">
            Failed to load website data. Please try again.
          </p>
        </div>
      </div>
    );
  }

  if (!websiteData) {
    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-muted" 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">Website not found</p>
            <p className="text-sm mt-1">The website you`re looking for doesn`t exist.</p>
          </div>
        </div>
      </div>
    );
  }

  return <WebsiteForm websiteId={id} initialData={websiteData.website} />;
}