// app/admin/dashboard/pages/builder/[id]/page.tsx
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';
import Link from 'next/link';
import PageBuilder from '@/app/components/admin/page-builder/PageBuilder';

export const metadata: Metadata = {
  title: 'Page Builder',
  description: 'Build your page with drag and drop builder.',
};

async function getPageData(pageId: string, token: string) {
  try {
    const response = await fetch(`${process.env.NEXTAUTH_URL}/api/backend/admin/pages/${pageId}`, {
      cache: 'no-store',
      headers: { Authorization: `Bearer ${token}` },
    });
    if (response.ok) return await response.json();
  } catch (error) {
    console.error('Failed to fetch page data:', error);
  }
  return null;
}

interface PageBuilderProps { params: Promise<{ id: string }>; }

export default async function GlobalPageBuilder({ params }: PageBuilderProps) {
  const { id } = await params;
  const token = await getTokenFromCookies();

  if (!token) redirect('/admin/login');

  const hasPermission = await authService.checkUserPermission(token, PERMISSIONS.PAGES_BUILD);
  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&apos;t have permission to use the page builder.</p>
        </div>
      </div>
    );
  }

  const pageData = await getPageData(id, token);

  if (!pageData) {
    return (
      <div className="max-w-6xl 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="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">Page not found</p>
          <p className="text-sm text-var-text-muted mt-1">The page you&apos;re trying to build doesn&apos;t exist.</p>
        </div>
      </div>
    );
  }

  const page = pageData.page;

  return (
    <div className="h-screen flex flex-col bg-var-bg">

      {/* ── Builder Header ───────────────────────────────────────────────── */}
      <header className="bg-var-surface border-b border-var-border px-5 py-0 flex items-center justify-between h-14 shrink-0">

        {/* Left — back + page info */}
        <div className="flex items-center gap-4 min-w-0">
          <Link
            href="/admin/dashboard/pages"
            className="flex items-center justify-center w-8 h-8 rounded-lg text-var-text-muted hover:text-var-text hover:bg-var-surface-hover transition-colors shrink-0"
            title="Back to Pages"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
          </Link>

          <div className="w-px h-6 bg-var-border shrink-0" />

          <div className="flex items-center gap-2.5 min-w-0">
            <div className="w-7 h-7 bg-gradient-blue rounded-lg flex items-center justify-center shrink-0">
              <svg className="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1V5zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 15a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1H5a1 1 0 01-1-1v-4zm10 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z" />
              </svg>
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold text-var-text truncate">{page.page_title}</span>
                <span className="hidden sm:inline-flex items-center gap-1 text-xs text-var-text-muted bg-var-surface-hover px-2 py-0.5 rounded-full font-mono shrink-0">
                  <svg className="w-3 h-3" 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>
                  /{page.page_slug}
                </span>
              </div>
              {page.page_short_description && (
                <p className="text-xs text-var-text-muted truncate hidden md:block leading-tight">
                  {page.page_short_description}
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Right — status + actions */}
        <div className="flex items-center gap-2 shrink-0">
          <a
            href={`/${page.page_slug}`}
            target="_blank"
            rel="noreferrer"
            className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-var-text-secondary hover:text-var-text border border-var-border hover:border-var-border-strong rounded-lg bg-var-surface hover:bg-var-surface-hover transition-colors"
            title="View live page"
          >
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
            </svg>
            Preview
          </a>

          <Link
            href={`/admin/dashboard/pages/edit/${id}`}
            className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-var-text-secondary hover:text-var-text border border-var-border hover:border-var-border-strong rounded-lg bg-var-surface hover:bg-var-surface-hover transition-colors"
            title="Page settings"
          >
            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            Page Settings
          </Link>
        </div>
      </header>

      {/* ── Page Builder ─────────────────────────────────────────────────── */}
      <PageBuilder
        pageId={id}
        contentType="pages"
        title="Page Builder"
        subtitle="Build your page layout"
      />
    </div>
  );
}