import { forwardRef, type InputHTMLAttributes } from "react";
import {
	Accordion,
	AccordionContent,
	AccordionItem,
	AccordionTrigger,
} from "~/components/ui/accordion";
import type { Faq } from "~/i18n/locales";
import { cn } from "~/lib/utils";

interface AccordionCompProps extends InputHTMLAttributes<HTMLDivElement> {
	texts: Faq[];
	defaultOpen?: number;
}

/**
 * Renders an accordion component with collapsible items.
 *
 * @component
 * @example
 * ```tsx
 * <AccordionComp
 *   texts={[
 *     { title: "Item 1", description: "Description for Item 1" },
 *     { title: "Item 2", description: "Description for Item 2" },
 *     { title: "Item 3", description: "Description for Item 3" },
 *   ]}
 *   className="my-4"
 * />
 * ```
 */
export const AccordionComp = forwardRef<HTMLDivElement, AccordionCompProps>(
	({ texts, defaultOpen, className }, ref) => {
		if (!texts || texts.length === 0) {
			return null; // Return null if no texts are provided
		}
		return (
			<div
				className={cn("mx-auto flex max-w-xl justify-center", className)}
				ref={ref}
			>
				<Accordion
					className="w-full"
					collapsible
					defaultValue={
						defaultOpen !== undefined ? `item-${defaultOpen}` : undefined
					}
					type="single"
				>
					{texts.map((text, index) => (
						<AccordionItem
							className="border-b dark:border-muted-foreground/50"
							// biome-ignore lint/suspicious/noArrayIndexKey: <index is safe here>
							key={`ac-item-${index}`}
							value={`item-${index}`}
						>
							<AccordionTrigger className="cursor-pointer gap-4 border-natural-200 text-left text-md">
								{text.title}
							</AccordionTrigger>
							<AccordionContent className="text-base">
								{text.description}
							</AccordionContent>
						</AccordionItem>
					))}
				</Accordion>
			</div>
		);
	},
);

AccordionComp.displayName = "AccordionComp";
