import React, { useEffect, useMemo } from 'react';
import { Render } from "@measured/puck";
import { renderConfig } from "../puck/config";
import { usePublicPage, usePublicSiteConfig } from "../hooks/useSites";
import { Loader2 } from "lucide-react";
import type { Theme, HeaderConfig, FooterConfig } from "../puck/types";

// Theme token to CSS custom property mapping
function themeToCSSVars(theme: Theme): Record<string, string> {
  const vars: Record<string, string> = {};

  // Colors
  if (theme.colors) {
    const { colors } = theme;
    if (colors.primary) vars['--color-primary'] = colors.primary;
    if (colors.secondary) vars['--color-secondary'] = colors.secondary;
    if (colors.accent) vars['--color-accent'] = colors.accent;
    if (colors.background) vars['--color-background'] = colors.background;
    if (colors.surface) vars['--color-surface'] = colors.surface;
    if (colors.text) vars['--color-text'] = colors.text;
    if (colors.textMuted) vars['--color-text-muted'] = colors.textMuted;
  }

  // Typography
  if (theme.typography) {
    const { typography } = theme;
    if (typography.fontFamily) vars['--font-family'] = typography.fontFamily;
    if (typography.headingFamily) vars['--font-heading'] = typography.headingFamily;
    if (typography.baseFontSize) vars['--font-size-base'] = typography.baseFontSize;
  }

  // Buttons
  if (theme.buttons) {
    const { buttons } = theme;
    if (buttons.borderRadius) vars['--button-radius'] = buttons.borderRadius;
    if (buttons.paddingX) vars['--button-padding-x'] = buttons.paddingX;
    if (buttons.paddingY) vars['--button-padding-y'] = buttons.paddingY;
  }

  // Sections
  if (theme.sections) {
    const { sections } = theme;
    if (sections.maxWidth) vars['--section-max-width'] = sections.maxWidth;
    if (sections.defaultPadding) vars['--section-padding'] = sections.defaultPadding;
    if (sections.containerPadding) vars['--section-container-padding'] = sections.containerPadding;
  }

  return vars;
}

// Site header component
function SiteHeader({ config, pages }: { config: HeaderConfig; pages?: { title: string; slug: string; include_in_nav: boolean }[] }) {
  const navPages = pages?.filter(p => p.include_in_nav) || [];

  if (config.style === 'none') {
    return null;
  }

  // Don't render empty header - check if there's any content to show
  const hasLogo = config.logoUrl || config.businessName;
  const hasNav = config.showNavigation && navPages.length > 0;
  const hasCta = config.ctaText && config.ctaLink;

  if (!hasLogo && !hasNav && !hasCta) {
    return null;
  }

  return (
    <header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          {/* Logo */}
          <div className="flex items-center">
            {config.logoUrl ? (
              <img
                src={config.logoUrl}
                alt={config.businessName || 'Logo'}
                className="h-8"
              />
            ) : config.businessName ? (
              <span className="text-xl font-bold text-gray-900 dark:text-white">
                {config.businessName}
              </span>
            ) : null}
          </div>

          {/* Navigation */}
          {config.showNavigation && navPages.length > 0 && (
            <nav className="hidden md:flex items-center space-x-6">
              {navPages.map((page) => (
                <a
                  key={page.slug}
                  href={`/${page.slug}`}
                  className="text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors"
                >
                  {page.title}
                </a>
              ))}
            </nav>
          )}

          {/* CTA Button */}
          {config.ctaText && config.ctaLink && (
            <a
              href={config.ctaLink}
              className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors text-sm font-medium"
            >
              {config.ctaText}
            </a>
          )}
        </div>
      </div>
    </header>
  );
}

// Site footer component
function SiteFooter({ config }: { config: FooterConfig }) {
  if (config.style === 'none') {
    return null;
  }

  // Don't render empty footer
  const hasCopyright = config.copyrightText;
  const hasSocialLinks = config.socialLinks && Object.values(config.socialLinks).some(url => url);

  if (!hasCopyright && !hasSocialLinks) {
    return null;
  }

  return (
    <footer className="bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex flex-col md:flex-row items-center justify-between gap-4">
          {/* Copyright */}
          {config.copyrightText && (
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {config.copyrightText}
            </p>
          )}

          {/* Social Links */}
          {config.socialLinks && Object.keys(config.socialLinks).length > 0 && (
            <div className="flex items-center space-x-4">
              {Object.entries(config.socialLinks).map(([platform, url]) => (
                url && (
                  <a
                    key={platform}
                    href={url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                    aria-label={platform}
                  >
                    {/* Simple text fallback - could be replaced with icons */}
                    <span className="text-sm capitalize">{platform}</span>
                  </a>
                )
              ))}
            </div>
          )}
        </div>
      </div>
    </footer>
  );
}

// SEO Meta tags component
function SEOHead({
  title,
  metaTitle,
  metaDescription,
  ogImage,
  canonicalUrl,
  noindex,
}: {
  title: string;
  metaTitle?: string;
  metaDescription?: string;
  ogImage?: string;
  canonicalUrl?: string;
  noindex?: boolean;
}) {
  useEffect(() => {
    // Set page title
    document.title = metaTitle || title;

    // Helper to update or create meta tag
    const setMeta = (name: string, content: string, property = false) => {
      if (!content) return;
      const attr = property ? 'property' : 'name';
      let tag = document.querySelector(`meta[${attr}="${name}"]`);
      if (!tag) {
        tag = document.createElement('meta');
        tag.setAttribute(attr, name);
        document.head.appendChild(tag);
      }
      tag.setAttribute('content', content);
    };

    // Meta description
    if (metaDescription) {
      setMeta('description', metaDescription);
    }

    // Open Graph tags
    setMeta('og:title', metaTitle || title, true);
    if (metaDescription) {
      setMeta('og:description', metaDescription, true);
    }
    if (ogImage) {
      setMeta('og:image', ogImage, true);
    }

    // Robots tag
    if (noindex) {
      setMeta('robots', 'noindex, nofollow');
    }

    // Canonical URL
    if (canonicalUrl) {
      let link = document.querySelector('link[rel="canonical"]') as HTMLLinkElement;
      if (!link) {
        link = document.createElement('link');
        link.rel = 'canonical';
        document.head.appendChild(link);
      }
      link.href = canonicalUrl;
    }

    // Cleanup function - remove tags when component unmounts
    return () => {
      // We don't remove tags on unmount to avoid flickering
    };
  }, [title, metaTitle, metaDescription, ogImage, canonicalUrl, noindex]);

  return null;
}

export const PublicPage: React.FC = () => {
  const { data: pageData, isLoading: pageLoading, error: pageError } = usePublicPage();
  const { data: siteConfig, isLoading: configLoading } = usePublicSiteConfig();

  const isLoading = pageLoading || configLoading;

  // Compute CSS variables from theme
  const cssVars = useMemo(() => {
    if (siteConfig?.merged_theme) {
      return themeToCSSVars(siteConfig.merged_theme);
    }
    return {};
  }, [siteConfig?.merged_theme]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
      </div>
    );
  }

  if (pageError || !pageData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            Page Not Found
          </h1>
          <p className="text-gray-600 dark:text-gray-400">
            This page doesn't exist or the site is disabled.
          </p>
        </div>
      </div>
    );
  }

  const hideChrome = pageData.hide_chrome;
  const header = siteConfig?.header || {};
  const footer = siteConfig?.footer || {};

  return (
    <>
      {/* SEO Meta Tags */}
      <SEOHead
        title={pageData.title}
        metaTitle={pageData.meta_title}
        metaDescription={pageData.meta_description}
        ogImage={pageData.og_image}
        canonicalUrl={pageData.canonical_url}
        noindex={pageData.noindex}
      />

      {/* Apply theme as CSS custom properties */}
      <div
        className="public-page min-h-screen flex flex-col"
        style={cssVars}
      >
        {/* Header (unless hide_chrome is set) */}
        {!hideChrome && <SiteHeader config={header} />}

        {/* Page Content */}
        <main className="flex-1">
          <Render config={renderConfig} data={pageData.puck_data} />
        </main>

        {/* Footer (unless hide_chrome is set) */}
        {!hideChrome && <SiteFooter config={footer} />}
      </div>
    </>
  );
};

export default PublicPage;
