import { Suspense } from 'react';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { Metadata } from 'next';
import { getServerSession } from '@/lib/auth/getServerSession';
import { PERMISSIONS } from '@/lib/permissions/permissions';
import { SESSION_COOKIE } from '@/lib/auth/requireAuth';
import AccessDenied from '@/components/admin/errors/AccessDenied';
import ThemeSettingsForm from '@/components/admin/theme-settings/ThemeSettingsForm';
import { DEFAULT_THEME, type StorefrontTheme } from '@/lib/theme/storefrontTheme';
import { internalAuthHeaders } from '@/lib/auth/internalAuth';

export const metadata: Metadata = {
  title: 'Theme Settings',
};

async function getTheme(sessionToken: string): Promise<{ theme: StorefrontTheme; updatedAt: string | null } | null> {
  try {
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
    const res = await fetch(`${baseUrl}/api/theme-settings`, {
      cache: 'no-store',
      headers: { ...internalAuthHeaders(sessionToken) },
    });
    if (!res.ok) return null;
    const data = await res.json();
    return data.data;
  } catch (error) {
    console.error('Failed to fetch theme settings:', error);
    return null;
  }
}

async function ThemeSettingsContent() {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get(SESSION_COOKIE)?.value;
  if (!sessionId) redirect('/admin/login');

  const session = await getServerSession();
  if (!session) redirect('/admin/login');
  if (!session.permissions.includes(PERMISSIONS.THEME_SETTINGS_READ)) return <AccessDenied />;

  const data = await getTheme(sessionId);

  return (
    <>
      <div className="mb-6">
        <h1 className="text-2xl font-semibold" style={{ color: 'var(--color-text)' }}>
          Theme Settings
        </h1>
        <p className="text-sm mt-1" style={{ color: 'var(--color-text-secondary)' }}>
          Colors, fonts and corner style of your online store. Changes go live for all customers as soon as you save.
          (The admin panel keeps its own look under Color Settings.)
        </p>
      </div>

      {data ? (
        <ThemeSettingsForm
          initialTheme={data.theme ?? DEFAULT_THEME}
          updatedAt={data.updatedAt}
          canUpdate={session.permissions.includes(PERMISSIONS.THEME_SETTINGS_UPDATE)}
        />
      ) : (
        <p className="p-6 text-center" style={{ color: 'var(--color-text-secondary)' }}>
          Failed to load theme settings. Please try again.
        </p>
      )}
    </>
  );
}

export default async function ThemeSettingsPage() {
  return (
    <div className="sm:p-6">
      <Suspense fallback={<div className="skeleton h-96 w-full rounded-xl" />}>
        <ThemeSettingsContent />
      </Suspense>
    </div>
  );
}
