"use client";

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

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

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

/**
 * Individual FAQ item with expand/collapse
 */
function FAQItemComponent({
  question,
  answer,
  isOpen,
  onToggle,
}: {
  question: string;
  answer: string;
  isOpen: boolean;
  onToggle: () => void;
}) {
  return (
    <div className="border-b border-border last:border-b-0">
      <button
        type="button"
        onClick={onToggle}
        className="w-full py-4 flex items-start justify-between gap-3 text-left hover:text-primary transition-colors"
        aria-expanded={isOpen}
      >
        <span className="text-sm font-medium text-foreground">{question}</span>
        {isOpen ? (
          <ChevronUp className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
        ) : (
          <ChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
        )}
      </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">
          <p className="text-sm text-muted-foreground leading-relaxed">{answer}</p>
        </div>
      </div>
    </div>
  );
}

/**
 * ServiceFAQ - Reusable FAQ accordion section
 *
 * Displays frequently asked questions with collapsible answers.
 * Used at the bottom of service pages to address common concerns.
 */
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-8", className)}>
      {/* Section Header */}
      <div className="text-center mb-6">
        <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-2">
          {eyebrow}
        </p>
        <h2 className="text-display-sm font-display text-foreground">{title}</h2>
      </div>

      {/* FAQ Container */}
      <div className="bg-card border border-border rounded-2xl 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;
