import { Faq } from "../../../services/content/types";
import { DataCacheKey, staleTime } from "../../../global/constants";
import { useQuery } from "@tanstack/react-query";
import React, { useState, useEffect, useCallback } from "react";
import { contentApi } from "../../../apis/contentApi";
import {
  startLoading,
  stopLoading,
} from "../../../features/loading/loadingSlice";
import { useAppDispatch } from "../../../hooks/useRedux";
import { useTranslation } from "react-i18next";

const HomeFaq = () => {
  const [openFaqIndex, setOpenFaqIndex] = useState<number | null>(0);
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const { data: loadFaqsData = [] } = useQuery<Faq[]>({
    queryKey: [DataCacheKey.FAQS],
    queryFn: async (): Promise<Faq[]> => {
      try {
        dispatch(startLoading({}));
        const res = await contentApi.LoadFaq({
          pageNumber: 0,
          pageSize: 10,
          isFeatured: true,
        });
        return res.data.faqs as Faq[];
      } catch (error) {
        console.error(error);
        return []; // 🔴 bắt buộc
      } finally {
        dispatch(stopLoading());
      }
    },
    staleTime: staleTime,
  });

  const toggleFaq = (index: number) => {
    setOpenFaqIndex(openFaqIndex === index ? null : index);
  };

  return (
    <>
      <section className="py-16 md:py-24 bg-white px-4 border-t border-slate-50">
        <div className="max-w-4xl mx-auto">
          <div className="text-center mb-12 md:mb-20">
            <h2 className="text-3xl md:text-6xl font-black tracking-tight text-[#EE0434] mb-4">
              {t("frequently")}{" "}
              <span className="text-slate-900">{t("askedQuestions")}</span>
            </h2>
            <p className="text-slate-500 text-sm md:text-xl font-medium">
              {t("weAreAlwaysHereToSupportYou")}
            </p>
          </div>

          <div className="space-y-4">
            {loadFaqsData.map((faq, index) => (
              <div key={index} className="border-b border-slate-100">
                <button
                  onClick={() => toggleFaq(index)}
                  className="w-full flex justify-between items-center py-6 text-left group transition-all"
                >
                  <span
                    className={`text-base md:text-2xl font-black transition-colors ${
                      openFaqIndex === index
                        ? "text-[#EE0434]"
                        : "text-slate-800 group-hover:text-[#EE0434]"
                    }`}
                  >
                    {faq.question}
                  </span>
                  <div
                    className={`shrink-0 w-6 h-6 md:w-8 md:h-8 flex items-center justify-center transition-all duration-500 ${
                      openFaqIndex === index
                        ? "text-[#EE0434] rotate-180"
                        : "text-slate-300"
                    }`}
                  >
                    <svg
                      className="w-5 h-5 md:w-7 md:h-7"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={3}
                        d="M19 9l-7 7-7-7"
                      />
                    </svg>
                  </div>
                </button>
                <div
                  className={`grid transition-all duration-500 ease-in-out ${
                    openFaqIndex === index
                      ? "grid-rows-[1fr] opacity-100"
                      : "grid-rows-[0fr] opacity-0"
                  }`}
                >
                  <div className="overflow-hidden">
                    {/* show html */}
                    <div
                      dangerouslySetInnerHTML={{ __html: faq.answer }}
                      className="text-slate-600 text-sm md:text-xl leading-relaxed font-medium pb-8"
                    />
                    {/* <p className="text-slate-600 text-sm md:text-xl leading-relaxed font-medium pb-8">
                      {faq.answer}
                    </p> */}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
};

export default HomeFaq;
