"use client";

import { useState, useEffect } from "react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Loader2 } from "lucide-react";
import { Dictionary } from "@/lib/IDict";
import { pb } from "@/lib/pb";

// Модель для FAQ из PocketBase
interface PBFaq {
  id: string;
  question: string;
  answer: string;
  lang: string;
  order: number;
}

export function FAQ({ dict, lang }: { dict: Dictionary["faq"]; lang: string }) {
  const [faqs, setFaqs] = useState<PBFaq[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchFaqs() {
      try {
        setLoading(true);
        // Тянем вопросы для текущего языка и сортируем по полю order (по возрастанию)
        const records = await pb.collection("faqs").getFullList<PBFaq>({
          filter: `lang = "${lang}"`,
          sort: "order",
        });
        setFaqs(records);
      } catch (error) {
        console.error("Ошибка загрузки FAQ:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchFaqs();
  }, [lang]);

  return (
    <section
      id="faq"
      className="py-20 px-4 container mx-auto max-w-3xl min-h-[400px]"
    >
      <h2 className="text-3xl font-bold mb-10 text-center">{dict.title}</h2>

      {loading ? (
        <div className="flex flex-col items-center justify-center py-10 text-primary opacity-50">
          <Loader2 className="w-8 h-8 animate-spin mb-4" />
          <span className="text-sm tracking-widest uppercase font-mono">
            Loading_Data...
          </span>
        </div>
      ) : faqs.length === 0 ? (
        <p className="text-center text-muted-foreground font-mono">
          {/* Если база пуста, можно вывести сообщение или fallback */}0 records
          found in database.
        </p>
      ) : (
        <Accordion type="single" collapsible className="w-full">
          {faqs.map((faq, index) => (
            <AccordionItem
              key={faq.id}
              value={`item-${faq.id}`}
              className="border-border/50"
            >
              <AccordionTrigger className="text-left text-foreground hover:text-primary transition-colors font-medium">
                {faq.question}
              </AccordionTrigger>
              <AccordionContent className="text-muted-foreground leading-relaxed">
                {faq.answer}
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>
      )}
    </section>
  );
}
