'use client'
import React, { useState } from 'react'
import type { FDFaqBlock as FDFaqBlockProps } from '@/payload-types'
import RichText from '@/components/RichText'

export const FDFaqBlockComponent: React.FC<FDFaqBlockProps> = ({
  heading,
  items,
  theme = 'gray',
}) => {
  const [openIndex, setOpenIndex] = useState<number | null>(null)

  const bgClass =
    theme === 'dark'
      ? 'bg-fd-navy'
      : theme === 'gray'
        ? 'bg-fd-gray-light'
        : 'bg-white'
  const headingColor = theme === 'dark' ? 'text-fd-yellow' : 'text-fd-navy'
  const textColor = theme === 'dark' ? 'text-white' : 'text-fd-navy'
  const borderColor = theme === 'dark' ? 'border-white/20' : 'border-fd-navy/10'
  const proseColor = theme === 'dark' ? 'text-white/80' : 'text-fd-navy/80'

  return (
    <section className={`w-full py-16 md:py-20 lg:py-[130px] ${bgClass}`}>
      <div className="max-w-[1200px] mx-auto px-6 md:px-8 flex flex-col items-start gap-6">
        <h2 className={`w-full max-w-[550px] font-joey-heavy text-fd-h1 ${headingColor}`}>
          {heading}
        </h2>
        <div className="w-full max-w-[1162px]">
          {items?.map((item, index) => (
            <div key={index} className={`border-b ${borderColor}`}>
              <button
                className={`flex w-full items-center gap-3 md:gap-4 py-4 md:py-5 text-left transition-colors ${textColor}`}
                onClick={() => setOpenIndex(openIndex === index ? null : index)}
                aria-expanded={openIndex === index}
              >
                <svg
                  className={`w-4 h-4 md:w-5 md:h-5 flex-shrink-0 transition-transform duration-200 ${
                    openIndex === index ? 'rotate-45' : ''
                  }`}
                  viewBox="0 0 20 20"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                >
                  <line x1="10" y1="2" x2="10" y2="18" />
                  <line x1="2" y1="10" x2="18" y2="10" />
                </svg>
                <span className="font-joey text-fd-h3">
                  {item.question}
                </span>
              </button>
              <div
                className={`grid transition-all duration-200 ease-out ${
                  openIndex === index
                    ? 'grid-rows-[1fr] opacity-100 pb-5'
                    : 'grid-rows-[0fr] opacity-0'
                }`}
              >
                <div className="overflow-hidden">
                  <div className={`font-joey text-fd-body pl-7 md:pl-9 fd-prose ${proseColor}`}>
                    <RichText data={item.answer} />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}
