import React, { ElementType, FC } from 'react';
import Image from 'next/image';
import { VariantProps, cva } from 'class-variance-authority';
import { cssMerge } from '../../utils/cssMerge';
import { Section } from '../../molecules/Section';
import { Button, ButtonProps } from '../../molecules/Button';
import { ImageProps } from '../../types';
import { FeatureCard, FeatureCardProps } from './FeatureCard';
import { splitAndColorArray } from './utils/splitAndColor';

interface FeatureHighlightProps extends VariantProps<typeof wrapper> {
  cards: FeatureCardProps[];
  eyebrow?: string;
  headline?: string;
  headingAs?: ElementType;
  buttons?: ButtonProps[];
  body?: string;
  mobileBackground?: ImageProps;
  desktopBackground?: ImageProps;
}

const wrapper = cva(['tw-grid', 'lg:tw-grid-cols-12', 'tw-gap-8']);
const headlineStyles = cva(['tw-font-medium', 'tw-text-display-xs', 'md:tw-text-display-md']);
const buttonWrapper = cva(['tw-flex tw-gap-2 tw-flex-col sm:tw-flex-row', 'tw-w-fit', 'tw-mt-4']);
const columns = cva([
  'tw-grid',
  'tw-gap-4',
  'md:tw-grid-cols-2',
  'md:tw-gap-8',
  'md:tw-items-center',
  'lg:tw-col-span-8',
]);
const singleColumn = cva(['tw-grid', 'tw-gap-4', 'tw-w-full'], {
  variants: {
    shiftDown: {
      true: ['md:tw-mt-32'],
    },
  },
});

export const FeatureHighlight: FC<FeatureHighlightProps> = ({
  eyebrow,
  headline,
  headingAs,
  body,
  buttons,
  cards,
  mobileBackground,
  desktopBackground,
}) => {
  const H = headingAs || 'h2';
  const twoArrays = cards ? splitAndColorArray(cards) : [];

  return (
    <Section className={cssMerge(wrapper())}>
      <div className="tw-grid tw-gap-3 tw-h-fit lg:tw-col-span-4">
        {eyebrow && <p className="tw-eyebrow">{eyebrow}</p>}
        {headline && <H className={headlineStyles()}>{headline}</H>}
        {body && <p className="tw-text-lg tw-text-gray-300">{body}</p>}
        {buttons && (
          <div className={cssMerge(buttonWrapper())}>
            {buttons.map((button, index) => (
              <Button key={index} {...button} />
            ))}
          </div>
        )}
      </div>
      <div className={cssMerge(columns())}>
        {twoArrays.map((features, index) => (
          <div key={index} className={cssMerge(singleColumn({ shiftDown: cards.length === 4 && index === 0 }))}>
            {features.map((feature, index) => (
              <FeatureCard key={index} {...feature} />
            ))}
          </div>
        ))}
      </div>
      {mobileBackground && <Image src={mobileBackground.src} alt="" fill className="-tw-z-10 md:tw-hidden" />}
      {desktopBackground && (
        <Image src={desktopBackground.src} alt="" fill className="-tw-z-10 tw-hidden md:tw-block" />
      )}
    </Section>
  );
};
