import React from 'react';
import type { Metadata } from 'next';

import { HeaderNavigation, FooterHome } from '../../design_system/sections';
import { ThemeProvider } from '../../contexts';
import { MetaPixel } from '../../tracking';
import { ChatWidget } from '../../design_system/components/ChatWidget';
import {
  getCompanyInformation,
  getWebsitePhotos,
  getServices,
  getLocations,
  getTeamMembers,
  getAdsConfig,
  getMetaPixelId,
} from '../../lib/server-api';

import type { CompanyInformation, Location, NavItem, Service, SiteConfig } from '../../types';

export type KeystoneRootLayoutHeaderOverrides = {
  logoHref?: string;
  ctaLabel?: string;
  ctaHref?: string;
  secondaryLabel?: string;
  secondaryHref?: string;
};

export type KeystoneRootLayoutOptions = {
  /** If provided, overrides header CTA defaults */
  headerOverrides?: KeystoneRootLayoutHeaderOverrides;
  /** Chat widget position */
  chatPosition?: 'bottom-right' | 'bottom-left';
};

function buildNavigationWithDynamicData(
  baseConfig: SiteConfig,
  services: Service[] | null,
  locations: Location[] | null
): SiteConfig {
  const serviceNavItems: NavItem[] = (services || []).map((service: Service) => ({
    label: service.name,
    href: `/services/${service.slug}`,
  }));

  const locationNavItems: NavItem[] = (locations || []).map((location: Location) => ({
    label: location.name,
    href: `/locations/${location.slug}`,
  }));

  // Clone the config and populate dynamic children
  const headerNav = baseConfig.navigation.header.map((item: NavItem) => {
    if (item.label === 'Services') {
      return { ...item, children: serviceNavItems };
    }
    if (item.label === 'Locations') {
      return { ...item, children: locationNavItems };
    }
    return item;
  });

  // Footer columns: add services to column 2, locations to column 3
  const footerNav = baseConfig.navigation.footer.map((column: NavItem[], index: number) => {
    if (index === 1) {
      // Keep all services in footer for SEO. Header has its own smart truncation / "View all".
      return [{ label: 'Services', href: '/services' }, ...serviceNavItems];
    }
    if (index === 2) {
      // Keep all locations in footer for SEO. Header has its own smart truncation / "View all".
      return [{ label: 'Locations', href: '/locations' }, ...locationNavItems];
    }
    return column;
  });

  return {
    ...baseConfig,
    navigation: {
      header: headerNav,
      footer: footerNav,
    },
  };
}

/**
 * Shared app shell for customer sites.
 *
 * Note: Next's `export const metadata` must remain in the site/app.
 * This component focuses on:
 * - fetching shared data
 * - injecting Meta Pixel
 * - applying theme
 * - rendering Header + Footer
 * - rendering ChatWidget gated by `companyInformation.chat_enabled`
 */
export async function KeystoneRootLayout(props: {
  children: React.ReactNode;
  config: SiteConfig;
  options?: KeystoneRootLayoutOptions;
}) {
  const { children, config, options } = props;

  const [companyInformation, websitePhotos, servicesData, locationsData, teamMembersData, adsConfig] =
    await Promise.all([
      getCompanyInformation(),
      getWebsitePhotos(),
      getServices(),
      getLocations(),
      getTeamMembers(),
      getAdsConfig(),
    ]);

  const metaPixelId = getMetaPixelId(adsConfig);

  const services = Array.isArray(servicesData) ? servicesData : [];
  const locations = Array.isArray(locationsData) ? locationsData : [];
  const teamMembers = Array.isArray(teamMembersData) ? teamMembersData : [];

  const dynamicConfig = buildNavigationWithDynamicData(config, services, locations);

  const theme = config.site.theme;

  const ci = companyInformation as CompanyInformation | null;
  const externalManagementUrl = ci?.external_management_url || 'https://booking.example.com';
  const chatEnabled = Boolean(ci?.chat_enabled);

  const headerOverrides = options?.headerOverrides;
  const headerProps = {
    logo: { href: headerOverrides?.logoHref || '/' },
    cta_button: {
      label: headerOverrides?.ctaLabel || 'Contact Us',
      href: headerOverrides?.ctaHref || '/contact',
      secondary_label:
        headerOverrides?.secondaryLabel ?? (externalManagementUrl ? 'Book Now' : undefined),
      secondary_href: headerOverrides?.secondaryHref ?? externalManagementUrl,
    },
  };

  return (
    <html lang="en" data-theme={theme}>
      <body>
        {metaPixelId ? <MetaPixel pixelId={metaPixelId} /> : null}
        <ThemeProvider theme={theme}>
          <HeaderNavigation
            config={dynamicConfig}
            companyInformation={companyInformation}
            websitePhotos={websitePhotos}
            props={headerProps}
          />
          {children}
          <FooterHome
            config={dynamicConfig}
            companyInformation={companyInformation}
            websitePhotos={websitePhotos}
          />
          {chatEnabled ? (
            <ChatWidget position={options?.chatPosition || 'bottom-right'} teamMembers={teamMembers} />
          ) : null}
        </ThemeProvider>
      </body>
    </html>
  );
}

// Export Metadata type for convenience at call sites
export type { Metadata };

