import type { ReactNode } from "react";
import { useEffect } from "react";
import { PageTransition } from "@/components/PageTransition";
import { CmsPageContent, type CmsPageData } from "@/components/CmsPageContent";
import { Button } from "@/components/ui/button";
import NotFound from "@/pages/NotFound";

type CmsPageViewProps = {
  page: CmsPageData | null;
  loading: boolean;
  notFound: boolean;
  error?: boolean;
  onRetry?: () => void;
  titleSuffix?: string;
  previewBanner?: ReactNode;
};

export function CmsPageView({
  page,
  loading,
  notFound,
  error = false,
  onRetry,
  titleSuffix = "",
  previewBanner,
}: CmsPageViewProps) {
  useEffect(() => {
    if (!page?.title) return;
    const previousTitle = document.title;
    document.title = `${page.title}${titleSuffix}`;
    const metaDescription = document.querySelector('meta[name="description"]');
    const previousDescription = metaDescription?.getAttribute("content") ?? "";
    if (metaDescription) {
      metaDescription.setAttribute("content", page.title);
    }
    return () => {
      document.title = previousTitle;
      if (metaDescription) {
        metaDescription.setAttribute("content", previousDescription);
      }
    };
  }, [page?.title, titleSuffix]);

  if (loading) {
    return (
      <div className="min-h-[50vh] flex items-center justify-center bg-background">
        <p className="text-muted-foreground font-display">Loading…</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-[50vh] flex items-center justify-center bg-background px-4">
        <div className="text-center max-w-md">
          <h1 className="mb-4 text-2xl font-bold text-foreground">Something went wrong</h1>
          <p className="mb-6 text-muted-foreground">
            We could not load this page. Please try again.
          </p>
          {onRetry ? (
            <Button type="button" onClick={onRetry}>
              Try again
            </Button>
          ) : null}
        </div>
      </div>
    );
  }

  if (notFound || !page) {
    return <NotFound />;
  }

  return (
    <PageTransition>
      <div className="min-h-full bg-background flex flex-col">
        {previewBanner}
        <CmsPageContent page={page} />
      </div>
    </PageTransition>
  );
}
