import * as React from 'react'
import * as AccordionPrimitive from '@radix-ui/react-accordion'
import { cn } from '@/lib/utils/cn'
import { MinusIcon, PlusIcon } from '../icons/common'
import { ReactNode } from 'react'

function Accordion({ ...props }: React.ComponentProps<typeof AccordionPrimitive.Root>) {
  return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}

function AccordionItem({
  className,
  ...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
  return (
    <AccordionPrimitive.Item
      data-slot="accordion-item"
      className={cn('overflow-hidden rounded-md border border-brown transition-all', className)}
      {...props}
    />
  )
}

function AccordionTrigger({
  className,
  children,
  icons,
  ...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger> & {
  icons?: { open: ReactNode; closed: ReactNode }
}) {
  return (
    <AccordionPrimitive.Header className="flex">
      <AccordionPrimitive.Trigger
        data-slot="accordion-trigger"
        className={cn(
          'flex flex-1 items-start justify-between gap-4 py-4 px-5 text-left text-b2-medium text-grey-50 transition-all outline-none bg-transparent-brown-40 cursor-pointer [&[data-state=open]>div>.plus]:hidden [&[data-state=open]>div>.minus]:block',
          className,
        )}
        {...props}
      >
        {children}
        <div className="w-5">
          {icons?.closed ?? <PlusIcon className="plus stroke-base-white size-5" />}
          {icons?.open ?? <MinusIcon className="minus stroke-base-white size-5 hidden" />}
        </div>
      </AccordionPrimitive.Trigger>
    </AccordionPrimitive.Header>
  )
}

function AccordionContent({
  className,
  children,
  ...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
  return (
    <AccordionPrimitive.Content
      data-slot="accordion-content"
      className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm bg-transparent-brown-40 text-b3-regular text-grey-200 px-5"
      {...props}
    >
      <div className={cn('pb-8 pt-4', className)}>{children}</div>
    </AccordionPrimitive.Content>
  )
}

type AccordionRootProps = React.ComponentProps<typeof AccordionPrimitive.Root>

export const CustomAccordion = ({
  className,
  options,
  icons,
  ...rootProps
}: {
  className?: string
  options: { value: string | ReactNode; label: string | ReactNode }[]
  icons?: { open: ReactNode; closed: ReactNode }
} & AccordionRootProps) => {
  return (
    <Accordion className={cn('w-full flex flex-col gap-3', className)} {...rootProps}>
      {options.map((option, index) => {
        return (
          <AccordionItem key={index} value={`${index}`}>
            <AccordionTrigger icons={icons}>{option.label}</AccordionTrigger>
            <AccordionContent>{option.value}</AccordionContent>
          </AccordionItem>
        )
      })}
    </Accordion>
  )
}
