import { Component, useEffect, useMemo, useState } from "react";
import { PageTransition } from "@/components/PageTransition";
import { getBlockComponent, type BlockContent } from "@/components/page-blocks";
import { resolveBlockSlug } from "@/lib/blockSlug";
import { apiUrl } from "@/lib/apiUrl";
import { normalizeContent, getRenderableSectionBlocks, layoutToGridColumns } from "@/admin/pages/sectionLayouts";
import type { PageSection } from "@/admin/types";
import { PageSectionRenderer } from "@/components/PageSectionRenderer";
import {
  buildContentPlaceholderVars,
} from "@/lib/contentPlaceholders";
import {
  findComponentLibraryContent,
  resolveEditorBlockContent,
} from "@/lib/mergeBlockContent";
import { useComponentDefaults } from "@/hooks/useComponentDefaults";
import { useSiteChrome } from "@/contexts/SiteChromeContext";
import {
  normalizePageSettings,
  shouldHideGlobalFooter,
  shouldRenderFooterBlock,
} from "@/lib/pageFooterSettings";
import Landing from "./Landing";

class DashboardErrorBoundary extends Component<{ children: React.ReactNode }, { hasError: boolean }> {
  state = { hasError: false };
  static getDerivedStateFromError = () => ({ hasError: true });
  render() {
    if (this.state.hasError) return <Landing />;
    return this.props.children;
  }
}

type PageBlock = {
  componentId: number;
  componentName: string;
  componentSlug?: string;
  content: Record<string, unknown>;
};
type PageData = {
  id: number;
  title: string;
  slug: string;
  content: unknown;
  settings?: {
    showFooter?: boolean;
  } | null;
  status: string;
};

export default function DynamicHomePage() {
  const [page, setPage] = useState<PageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [useCustomPage, setUseCustomPage] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch(apiUrl("/api/pages/preview/home"))
      .then((res) => {
        if (!res.ok) throw new Error("not found");
        return res.json();
      })
      .then((data) => {
        if (!cancelled && data?.page?.content && Array.isArray(data.page.content) && data.page.content.length > 0) {
          setPage(data.page);
          setUseCustomPage(true);
        }
      })
      .catch(() => {})
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

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

  if (!useCustomPage || !page || !page.content) {
    return (
      <DashboardErrorBoundary>
        <Landing />
      </DashboardErrorBoundary>
    );
  }

  let sections: PageSection[];
  try {
    sections = normalizeContent(page.content);
  } catch {
    return (
      <DashboardErrorBoundary>
        <Landing />
      </DashboardErrorBoundary>
    );
  }

  if (!sections.length || sections.every((s) => !Array.isArray(s.blocks) || s.blocks.length === 0)) {
    return (
      <DashboardErrorBoundary>
        <Landing />
      </DashboardErrorBoundary>
    );
  }

  const placeholderVars = buildContentPlaceholderVars(sections, { pageTitle: page?.title });
  const { components: libraryComponents } = useComponentDefaults({ source: "public" });
  const { setHasPageFooter } = useSiteChrome();
  const footerShowSetting = page?.settings?.showFooter;
  const pageSettings = useMemo(
    () => normalizePageSettings(
      footerShowSetting === undefined ? page?.settings : { showFooter: footerShowSetting },
    ),
    [footerShowSetting, page?.settings],
  );

  useEffect(() => {
    setHasPageFooter(shouldHideGlobalFooter(sections, pageSettings));
    return () => setHasPageFooter(false);
  }, [sections, pageSettings, setHasPageFooter]);

  return (
    <DashboardErrorBoundary>
      <PageTransition>
        <div className="min-h-full bg-background flex flex-col">
          {sections.map((section, si) => (
            <PageSectionRenderer
              key={section.id ?? si}
              section={section}
              sectionIndex={si}
              gridTemplateColumns={layoutToGridColumns(section.layout)}
            >
              {getRenderableSectionBlocks(section).map((block, bi) => {
                const slug = resolveBlockSlug(block);
                if (!shouldRenderFooterBlock(slug, pageSettings)) {
                  return null;
                }
                const BlockComp = getBlockComponent(slug);
                const rawContent = (block.content ?? {}) as BlockContent;
                const libraryContent = findComponentLibraryContent(block, libraryComponents, slug);
                const content = resolveEditorBlockContent(rawContent, {
                  blockSlug: slug,
                  libraryContent,
                  pageVars: placeholderVars,
                }) as BlockContent;
                if (!BlockComp) {
                  return (
                    <div key={bi} className="rounded-xl border bg-card p-4 text-muted-foreground text-sm">
                      {block.componentName}
                    </div>
                  );
                }
                return (
                  <div key={`${si}-${bi}-${slug}-${block.componentId}`}>
                    <BlockComp content={content} />
                  </div>
                );
              })}
            </PageSectionRenderer>
          ))}
        </div>
      </PageTransition>
    </DashboardErrorBoundary>
  );
}
