import { useCallback } from 'react';
import classNames from 'classnames';

import type { BoxProps } from '~/src/components/Box';
import type { ImageProps } from '~/src/components/Image';
import type { Scroller2Props } from '~/src/components/Scroller2';
import type { CSSProperties, FC } from 'react';
import type { DesktopTwoColumnLayoutProps } from './types';

import Box from '~/src/components/Box';
import Gradient from '~/src/components/Gradient';
import Image from '~/src/components/Image';
import Page from '~/src/components/Page';
import Scroller2 from '~/src/components/Scroller2';
import { useI18n } from '~/src/lib/i18n';
import toSizedImageUrlNext from '~/src/lib/toSizedImageUrlNext';
import { toRgba } from '~/src/lib/utils/color';
import { usePageTheme } from '../../hooks/theme';

const MAX_COLUMN_CONTENT_WIDTH = '48rem';
const SIZED_IMAGE_WIDTH = 1600;

const DesktopTwoColumnLayout: FC<DesktopTwoColumnLayoutProps> = ({
  primaryContent,
  secondaryContent,
  header,
  children,
  image,
  alignContent,
  testId,
  contentRootRef,
  onScroll,
  ...pageProps
}) => {
  const pageTheme = usePageTheme();
  const { t } = useI18n();

  const sizedImageUrl =
    image?.url &&
    toSizedImageUrlNext({
      url: image.url,
      width: SIZED_IMAGE_WIDTH,
    });

  return (
    <Page
      nodeRef={contentRootRef}
      testId={classNames('itemPage', 'desktopTwoColumnLayout', testId)}
      backgroundColor={pageTheme.backgroundColor}
      textColor={pageTheme.textColor}
      contentStyle={{
        paddingBottom: 0,
      }}
      renderBackground={useCallback(() => {
        const customProps: {
          container?: Partial<BoxProps>;
          innerContainer?: Partial<BoxProps>;
          image?: Partial<ImageProps>;
        } = (() => {
          switch (image.layout.type) {
            case 'half-fill':
              return {
                container: {
                  flexRow: true,
                },

                innerContainer: {
                  fullHeight: true,
                  width: '50%',
                  margin: alignContent === 'left' ? '0 0 0 auto' : '0',
                },

                image: {
                  fullHeight: true,
                  fullWidth: true,
                  cover: true,
                  testId: 'halfFillImage',

                  imgStyle: {
                    opacity: 0.8,
                  },
                },
              };

            case 'half-center':
              return {
                container: {
                  maxWidth: '120rem',
                  margin: '0 auto',
                  flexRow: true,
                },

                innerContainer: {
                  padding: `5rem 0 0 2rem`,
                  margin: alignContent === 'left' ? '0 0 0 auto' : '0',
                  width: '50%',
                },

                image: {
                  maxWidth: '48rem',
                  fullWidth: true,
                  testId: 'halfCenterImage',

                  // style: imageLayout.withBorder
                  //   ? {
                  //       borderRadius: '1.6rem',
                  //       border: `solid 1px ${toRgba(pageTheme.textColor, 0.3)}`,
                  //     }
                  //   : {},

                  imgStyle: {
                    opacity: 0.8,
                  },
                },
              };

            case 'full-fill': {
              return {
                image: {
                  fullHeight: true,
                  fullWidth: true,
                  cover: true,
                  testId: 'fullFillImage',

                  style: {
                    // for now the gradient isn't configurable in settings, but easily could be
                    // It's safer to force gradient here so that content/text is visible
                    WebkitMaskImage: `linear-gradient(${
                      alignContent === 'left' ? '90deg' : '270deg'
                    }, rgba(0,0,0,.15) 0%, rgba(0,0,0,.85) 100%)`,
                  },

                  imgStyle: {
                    opacity: 0.8,
                  },
                },
              };
            }

            default:
              return {};
          }
        })();

        return (
          <Box fullHeight {...customProps.container}>
            <Box {...customProps.innerContainer} centerContent fullHeight>
              <Image
                src={sizedImageUrl}
                aspect={
                  image?.width && image.height
                    ? image?.height / image?.width
                    : undefined
                }
                alt={t('item.pageBackgroundImageAlt')}
                maxWidth="100%"
                fadeInDuration={400}
                imgStyle={{
                  filter: 'saturate(.92)',
                  ...customProps.image?.imgStyle,
                }}
                {...customProps.image}
                testId={classNames(
                  'backgroundImage',
                  customProps.image?.testId
                )}
              />
            </Box>
          </Box>
        );
      }, [image])}
      renderHeader={() => {
        return (
          <>
            <Gradient
              positionAbsolute
              left={0}
              top={0}
              right={0}
              zIndex={0}
              pointerEvents="none"
              from={toRgba(
                pageTheme.backgroundColor,
                (0.65 * pageTheme.gradientOpacity) / 100
              )}
              to={toRgba(pageTheme.backgroundColor, 0)}
              height={`calc(${header.height} + 1rem)`}
            />
            {header.content}
          </>
        );
      }}
      renderContent={useCallback(() => {
        const dynamicProps: {
          primaryContainerStyle?: CSSProperties;
          secondaryContainerStyle?: CSSProperties;
          scrollerProps?: Partial<Scroller2Props>;
        } = (() => {
          switch (image.layout.type) {
            case 'half-center':
              return {
                primaryContainerStyle: {
                  maxWidth: '60rem',
                  marginLeft: alignContent === 'left' ? 'auto' : undefined,
                  paddingLeft: '2rem',
                },

                secondaryContainerStyle: {
                  maxWidth: '60rem',
                  marginLeft: alignContent === 'right' ? 'auto' : '',
                  padding: `calc(${header.height} + 7rem) 0 10rem 2rem`,
                },

                scrollerProps: {
                  withOverflowGradients: true,
                },
              };

            case 'half-fill':
              return {
                primaryContainerStyle: {
                  paddingLeft: '2rem',
                },
              };

            case 'full-fill':
              return {
                primaryContainerStyle: {
                  maxWidth: '60rem',
                  paddingLeft: '1rem',
                  marginLeft: alignContent === 'left' ? 'auto' : undefined,
                },

                scrollerProps: {
                  withOverflowGradients: false,
                },
              };
          }
        })();

        return (
          <>
            <Scroller2
              width="50%"
              positionAbsolute
              withOverflowGradients
              gradientColor={pageTheme.backgroundColor}
              gradientAlpha={(0.7 * pageTheme.gradientOpacity) / 100}
              left={alignContent === 'left' ? '50%' : '0'}
              top={0}
              bottom={0}
              renderContent={({ contentContainerProps: { nodeRef } }) => {
                return (
                  <Box
                    nodeRef={nodeRef}
                    minHeight="100%"
                    flexColumn
                    alignCenter
                    style={{
                      padding: `calc(${header.height} + 7rem) 2rem 10rem`,
                      ...dynamicProps.secondaryContainerStyle,
                    }}
                  >
                    {secondaryContent}
                  </Box>
                );
              }}
            />
            <Scroller2
              width="50%"
              positionAbsolute
              withOverflowGradients
              testId="primaryContent"
              gradientColor={pageTheme.backgroundColor}
              gradientAlpha={(0.7 * pageTheme.gradientOpacity) / 100}
              left={alignContent === 'left' ? '0' : '50%'}
              top={0}
              bottom={0}
              onScroll={onScroll}
              {...dynamicProps.scrollerProps}
              renderContent={({ contentContainerProps: { nodeRef } }) => {
                return (
                  <Box
                    nodeRef={nodeRef}
                    minHeight="100%"
                    flexColumn
                    alignCenter
                    style={{
                      padding: `calc(${header.height} + 4rem) 2rem 10rem`,
                      ...dynamicProps.primaryContainerStyle,
                    }}
                  >
                    <Box
                      style={{
                        flexGrow: 1,
                        flexShrink: 0,

                        display: 'flex',
                        alignItems: 'center',
                        position: 'relative',
                      }}
                    >
                      <div
                        style={{
                          margin: '0 auto',
                          width: '100%',
                          maxWidth: MAX_COLUMN_CONTENT_WIDTH,
                        }}
                      >
                        {primaryContent}
                      </div>
                    </Box>
                  </Box>
                );
              }}
            />
            {children}
            <style jsx>
              {`
                :global(.pageSection:not(:first-child)) {
                  margin-top: 5rem;
                }

                :global(.pageSection.isGrouped:not(:first-child)) {
                  margin-top: 2rem;
                }
              `}
            </style>
          </>
        );
      }, [
        primaryContent,
        secondaryContent,
        alignContent,
        image,
        header.height,
        pageTheme,
        onScroll,
      ])}
      footerHeight="4rem"
      footerStyle={{ pointerEvents: 'none' }}
      withOverflowGradients={false}
      {...pageProps}
    />
  );
};

export default DesktopTwoColumnLayout;
