'use client'

import React, { useState, useRef, useEffect } from 'react'
import { IoIosAdd, IoIosClose } from 'react-icons/io'
import { AccordionProps } from '@/app/types'

const Accordion: React.FC<AccordionProps> = ({ title, content }) => {
  const [isOpen, setIsOpen] = useState(false)
  const contentRef = useRef<HTMLDivElement>(null)
  const [contentHeight, setContentHeight] = useState<number>(0)

  useEffect(() => {
    if (contentRef.current) {
      setContentHeight(contentRef.current.scrollHeight)
    }
  }, [content])

  const renderContent = () => {
    if (typeof content === 'string') {
      return (
        <div
          className="text-md font-medium [&>ol]:list-decimal [&>ol]:pl-4 [&_ul]:list-disc [&_ul]:py-2 [&_ul]:pl-4 [&_li]:mb-2 [&_p]:mt-1 [&_a]:text-orange [&_a]:hover:underline"
          dangerouslySetInnerHTML={{ __html: content }}
        />
      )
    }
    return <div className="text-md font-medium">{content}</div>
  }

  return (
    <div className="relative bg-white rounded-2xl my-4">
      <button
        className="flex justify-between items-center py-4 px-6  hover:bg-gray-50 rounded-2xl space-x-9 w-full"
        onClick={() => setIsOpen(!isOpen)}
      >
        <h3 className="text-xl font-bold text-left">{title}</h3>
        <div className="w-6 h-6 flex items-center justify-center rounded-full border border-orange">
          <div
            className={`transition-all duration-500 ${
              isOpen ? 'rotate-180' : 'rotate-0'
            }`}
          >
            {isOpen ? (
              <IoIosClose className="w-5 h-5 text-orange" />
            ) : (
              <IoIosAdd className="w-5 h-5 text-orange" />
            )}
          </div>
        </div>
      </button>

      <div
        ref={contentRef}
        style={
          { '--accordion-height': `${contentHeight}px` } as React.CSSProperties
        }
        className={`
          grid
          transition-all duration-500 ease-&lsqb;cubic-bezier(0.4,0,0.2,1)&rsqb;
          ${
            isOpen ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'
          }
        `}
      >
        <div className="overflow-hidden">
          <div className=" rounded-xl px-6 mt-2">
            <div className="py-4">{renderContent()}</div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Accordion
