'use client'

import { forwardRef, type MouseEvent, type ReactNode, type SyntheticEvent,useEffect, useState } from 'react'
import type { TAccordionSkin } from 'shared-types'

import { PktIcon } from '../icon/Icon'
import { useAccordionContext } from './Accordion'

export type TPktAccordionSkin = TAccordionSkin

export interface IPktAccordionItem {
  defaultOpen?: boolean
  id: string
  title: string | ReactNode
  skin?: TPktAccordionSkin
  compact?: boolean
  isOpen?: boolean
  children?: ReactNode
  name?: string
  className?: string
  onClick?: (e: MouseEvent<HTMLDetailsElement>) => void
  onToggle?: (e: SyntheticEvent<HTMLDetailsElement>) => void
}

export const PktAccordionItem = forwardRef<HTMLDetailsElement, IPktAccordionItem>(
  (
    {
      defaultOpen = false,
      id,
      title,
      skin,
      compact = false,
      isOpen: controlledIsOpen,
      children,
      name,
      className,
      onClick,
      onToggle,
    },
    ref,
  ) => {
    const [internalIsOpen, setInternalIsOpen] = useState(defaultOpen)
    const { name: contextName } = useAccordionContext()

    // Bruk name fra props eller fra context
    const actualName = name || contextName

    // Bruk controlled isOpen om prop, ellers bruk intern state
    const isOpen = controlledIsOpen !== undefined ? controlledIsOpen : internalIsOpen

    useEffect(() => {
      if (controlledIsOpen === undefined) {
        setInternalIsOpen(defaultOpen)
      }
    }, [defaultOpen, controlledIsOpen])

    const handleToggle = (e: SyntheticEvent<HTMLDetailsElement>) => {
      const detailsElement = e.currentTarget
      const newOpenState = detailsElement.open

      // Ignorer toggle-events som skyldes React-synkronisering av open-attributtet
      if (newOpenState === isOpen) return

      if (controlledIsOpen === undefined) {
        setInternalIsOpen(newOpenState)
      }

      onToggle?.(e)
    }

    const handleClick = (e: MouseEvent<HTMLDetailsElement>) => {
      // La native toggle skje først, så trigge onClick
      setTimeout(() => {
        onClick?.(e)
      }, 0)
    }

    const accordionItemClass = [
      'pkt-accordion-item',
      compact && 'pkt-accordion-item--compact',
      skin && `pkt-accordion-item--${skin}`,
      className,
    ]
      .filter(Boolean)
      .join(' ')

    return (
      <details
        ref={ref}
        className={accordionItemClass}
        id={id}
        open={isOpen}
        onClick={handleClick}
        name={actualName}
        onToggle={handleToggle}
      >
        <summary className="pkt-accordion-item__title" id={`pkt-accordion-item-summary-${id}`}>
          {title}
          <PktIcon name="chevron-thin-down" className="pkt-accordion-item__icon" aria-hidden="true" />
        </summary>
        <div className="pkt-accordion-item__content" id={`pkt-accordion-item__content-${id}`} role="region">
          <div className="pkt-accordion-item__content-inner">{children}</div>
        </div>
      </details>
    )
  },
)

PktAccordionItem.displayName = 'PktAccordionItem'
