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

import { HeaderNavigation, FooterHome } from '../../design_system/sections';
import { ThemeProvider } from '../../contexts';
import { MetaPixel, MetaPixelTracker } from '../../tracking';
import { ChatWidget } from '../../design_system/components/ChatWidget';
import { FormDefinitionsProvider } from '../contexts/form-definitions';
import { KeystoneSSRProvider } from '../providers/ssr-provider';
import {
  getCompanyInformation,
  getWebsitePhotos,
  getServices,
  getLocations,
  getTeamMembers,
  getForm,
  getAdsConfig,
  getMetaPixelId,
} from '../../lib/server-api';

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

export type KeystoneRootLayoutHeaderOverrides = {
  logoHref?: string;
  /** Overrides the title/company name shown in the center of the nav bar (otherwise from business_info) */
  logoText?: string;
  /** Overrides the primary CTA button label (default: "Contact Us") */
  ctaLabel?: string;
  /** Overrides the secondary CTA button label (default: "Book Now" when a booking/portal URL is configured) */
  secondaryLabel?: 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,
    leadFormDefinition,
    jobApplicationFormDefinition,
    marketingListSignupFormDefinition,
    adsConfig,
  ] =
    await Promise.all([
      getCompanyInformation(),
      getWebsitePhotos(),
      getServices(),
      getLocations(),
      getTeamMembers(),
      getForm('lead'),
      getForm('job_application'),
      getForm('marketing_list_signup'),
      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?.trim() || null;
  const portalUrl = ci?.portal_url?.trim() || null;
  const bookingHref = portalUrl ?? externalManagementUrl ?? null;
  const chatEnabled = Boolean(ci?.chat_enabled);

  const headerOverrides = options?.headerOverrides;
  const headerProps = {
    logo: {
      href: headerOverrides?.logoHref || '/',
      ...(headerOverrides?.logoText != null && { text: headerOverrides.logoText }),
    },
    cta_button: {
      label: headerOverrides?.ctaLabel || 'Contact Us',
      secondary_label: headerOverrides?.secondaryLabel ?? (bookingHref ? 'Book Now' : undefined),
    },
  };

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

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

