"use client";

import { useState, type ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { cn } from "@/shared/utils/cn";

export interface FAQItem {
  question: string;
  answer: ReactNode;
}

export interface ServiceFAQProps {
  title?: string;
  eyebrow?: string;
  items: FAQItem[];
  className?: string;
  defaultOpenIndex?: number | null;
}

function FAQItemComponent({
  question,
  answer,
  isOpen,
  onToggle,
}: {
  question: string;
  answer: ReactNode;
  isOpen: boolean;
  onToggle: () => void;
}) {
  return (
    <div className="border-b border-border/60 last:border-b-0">
      <button
        type="button"
        onClick={onToggle}
        className="w-full py-4 flex items-start justify-between gap-3 text-left group"
        aria-expanded={isOpen}
      >
        <span className="text-sm font-medium text-foreground group-hover:text-primary transition-colors">
          {question}
        </span>
        <ChevronDown
          className={cn(
            "h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5 transition-transform duration-200",
            isOpen && "rotate-180"
          )}
        />
      </button>
      <div
        className={cn(
          "overflow-hidden transition-all duration-300",
          isOpen ? "max-h-[1000px] opacity-100" : "max-h-0 opacity-0"
        )}
      >
        <div className="pb-4 pr-8">
          <div className="text-sm text-muted-foreground leading-relaxed">{answer}</div>
        </div>
      </div>
    </div>
  );
}

/**
 * ServiceFAQ - FAQ accordion section.
 */
export function ServiceFAQ({
  title = "Frequently Asked Questions",
  eyebrow = "Common Questions",
  items,
  className,
  defaultOpenIndex = null,
}: ServiceFAQProps) {
  const [openIndex, setOpenIndex] = useState<number | null>(defaultOpenIndex);

  if (items.length === 0) return null;

  return (
    <section className={cn("py-6", className)}>
      {/* Header */}
      <div className="text-center mb-6">
        <p className="text-xs font-semibold text-primary uppercase tracking-wider mb-1.5">
          {eyebrow}
        </p>
        <h2 className="text-xl sm:text-2xl font-bold leading-tight tracking-tight text-foreground">
          {title}
        </h2>
      </div>

      {/* FAQ list */}
      <div className="bg-card border border-border rounded-xl px-5 shadow-sm">
        {items.map((item, index) => (
          <FAQItemComponent
            key={index}
            question={item.question}
            answer={item.answer}
            isOpen={openIndex === index}
            onToggle={() => setOpenIndex(openIndex === index ? null : index)}
          />
        ))}
      </div>
    </section>
  );
}

export default ServiceFAQ;
