"use client";

import React, { useEffect, useState } from "react";
import { AccordionItem, AccordionProps, ThemeKey } from "./types";

import { Accordion as AccordionComponent } from "@shared/components/accordion";
import { Divider } from "@shared/components/divider";
import { Text } from "@shared/components/text";

export const Accordion: React.FC<AccordionProps> = ({
  items,
  title,
  anchorId,
  background = "white",
  enableHeading = false,
  maxWidth = true,
  initialExpandedItems: initialExpandedItemsProp = [],
  hashAutoExpand = false,
  descriptionMaxWidth = "max-w-[980px]",
  itemContainerClassName,
}) => {
  const [expandedItems, setExpandedItems] = useState<string[]>(
    initialExpandedItemsProp
  );

  useEffect(() => {
    if (hashAutoExpand && typeof window !== "undefined") {
      const hash = window.location.hash;
      if (hash) {
        const expandItemId = hash.substring(hash.indexOf("#") + 1);
        setExpandedItems(prev => {
          if (prev.includes(expandItemId)) return prev;
          return [...prev, expandItemId];
        });
      }
    }
  }, [hashAutoExpand]);

  /* istanbul ignore next -- passed to AccordionComponent which does not forward onClick */
  const handleToggle = (itemAnchorId: string) => {
    setExpandedItems(prev =>
      prev.includes(itemAnchorId)
        ? prev.filter(id => id !== itemAnchorId)
        : [...prev, itemAnchorId]
    );
  };

  const bgColorClasses: Record<ThemeKey, string> = {
    blue: "bg-[#07B2E2]",
    green: "bg-[#26B170]",
    yellow: "bg-[#F5FF1E]",
    purple: "bg-[#931D69]",
    white: "bg-white",
    navy: "bg-[#00002D]",
    cream500: "bg-[#FFFEEF]",
  };

  return (
    <section
      id={anchorId}
      className={`${bgColorClasses[background]} flex flex-col px-5 pb-20 pt-4 md:px-10`}
    >
      <div className={`${maxWidth ? "max-w-120 xl:mx-auto" : ""}`}>
        <Text
          as={enableHeading ? "h1" : "h2"}
          className="heading2 mb-10 pt-12 text-left text-text md:heading1 lg:text-center"
        >
          {title}
        </Text>
        <div className={`pt-6 md:pt-10 ${itemContainerClassName ?? ""}`}>
          {items?.map((item: AccordionItem, index: number) => {
            const itemKey = item.anchorId || `item-${index}`;
            const isOpen = item.anchorId
              ? expandedItems.includes(item.anchorId)
              : undefined;

            return (
              <div
                key={itemKey}
                id={item.anchorId}
                className="snap-start scroll-mt-48 lg:scroll-mt-60"
              >
                <AccordionComponent
                  title={item.title}
                  defaultOpen={isOpen}
                  containerClassName="border-none"
                  buttonClassName="p-0 label1"
                  titleClassName="label3 md:label1 text-text"
                  className="p-0 pt-6 text-text"
                  iconClassName="text-icon"
                  borderRadiusNone={true}
                  openOnlyOnDesktop={false}
                  {...(item.anchorId && {
                    onClick: /* istanbul ignore next */ () =>
                      handleToggle(item.anchorId!),
                  })}
                >
                  <div className={descriptionMaxWidth}>
                    <Text as="div">{item.description}</Text>
                  </div>
                </AccordionComponent>
                {index < items.length - 1 && (
                  <Divider key={`divider-${index}`} className="my-6 md:my-10" />
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

export default Accordion;
