import React, { ElementType, FC, useState } from 'react';
import { VariantProps, cva } from 'class-variance-authority';
import { cssMerge } from '../../utils/cssMerge';
import { AccordionItem, AccordionItemProps } from './AccordionItem';
import { Section } from '../../molecules/Section';

interface AccordionProps extends VariantProps<typeof wrapper> {
  accordions: AccordionItemProps[];
  eyebrow?: string;
  headline?: string;
  headingAs?: ElementType;
}

const wrapper = cva(['tw-grid', 'tw-gap-8', 'md:tw-gap-12', 'lg:tw-grid-cols-12', 'lg:tw-gap-20']);
const headlineStyles = cva(['tw-font-medium', 'tw-text-display-sm', 'md:tw-text-display-md']);

export const Accordion: FC<AccordionProps> = ({ accordions, eyebrow, headline, headingAs }) => {
  const H = headingAs || 'h2';
  const [openIndex, setOpenIndex] = useState<number | null>(null);
  const accordionClick = (index: number) => setOpenIndex(openIndex === index ? null : index);
  return (
    <Section className={cssMerge(wrapper())}>
      {(eyebrow || headline) && (
        <div className="lg:tw-col-span-5">
          {eyebrow && <p className="eyebrow tw-mb-4">{eyebrow}</p>}
          {headline && <H className={headlineStyles()}>{headline}</H>}
        </div>
      )}
      {accordions && (
        <div className="lg:tw-col-span-7 lg:tw-col-start-6">
          {accordions.map((item, i) => (
            <AccordionItem
              {...item}
              open={openIndex === i}
              onClick={() => accordionClick(i)}
              onKeyDown={({ key }) => key === 'Enter' || key === ' ' && accordionClick(i)}
              tabIndex={0}
            />
          ))}
        </div>
      )}
    </Section>
  );
};
