"use client";

import { useState } from "react";
import { FAQCategory, FAQItem } from "@/lib/types/models";
import TopicSidebar from "../faq-sidebar";

interface FAQContentProps {
  data: FAQCategory[];
}

export default function Page({ data }: FAQContentProps) {
  const [selectedTopicIndex, setSelectedTopicIndex] = useState(0);
  const [expandedIndex, setExpandedIndex] = useState<number | null>(0);

  const toggleExpanded = (index: number) => {
    setExpandedIndex(expandedIndex === index ? null : index);
  };
  const selectedTopic = data[selectedTopicIndex];
  return (
    <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
      <TopicSidebar
        topics={data}
        selectedIndex={selectedTopicIndex}
        onSelectTopic={(val) => {
          setExpandedIndex(0);
          setSelectedTopicIndex(val);
        }}
      />

      <div className="lg:col-span-3 bg-white">
        <div className="bg-primary text-white  py-3  px-6">
          <h2 className="text-xl font-bold leading-none pb-1">
            {selectedTopic?.name}
          </h2>
        </div>
        <div className="space-y-3 mb-8">
          {selectedTopic?.questions?.length ? (
            selectedTopic.questions.map((faq: FAQItem, index: number) => (
              <div key={index} className="border-b border-gray-200 py-3">
                {/* Question */}
                <button
                  onClick={() => toggleExpanded(index)}
                  className="flex justify-between items-center w-full text-left gap-4  px-6"
                >
                  <span className="text-[16px] lg:text-[20px] text-[#3E3E3E] font-semibold tracking-wide">
                    {index + 1}. {faq?.categoryQuestion || "Untitled Question"}
                  </span>
                  <span className="text-[18px] lg:text-[26px] text-[#3E3E3E] font-semibold">
                    {expandedIndex === index ? "−" : "+"}
                  </span>
                </button>

                {/* Answer */}
                {expandedIndex === index && (
                  <div className="text-neutral-black-70 text-[13px] lg:text-[16px] tracking-wide leading-snug  px-11 mt-2">
                    <div
                      dangerouslySetInnerHTML={{
                        __html:
                          faq?.categoryAnswer || "<p>No answer available.</p>",
                      }}
                    />
                  </div>
                )}
              </div>
            ))
          ) : (
            <p className="px-6 py-4 text-neutral-500">
              No FAQs found for this topic.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
