"use client";

import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { Minus, Plus } from "lucide-react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useId, useState } from "react";
import { filterFaqArticles, getTopic } from "@/static/faq";

const QuestionList = () => {
  const searchParams = useSearchParams();
  const query = (searchParams.get("q") ?? "").trim();
  const articles = filterFaqArticles(query);
  const [openId, setOpenId] = useState<string | null>(null);
  const reducedMotion = useReducedMotion();
  const baseId = useId();
  const visibleOpenId = articles.some((article) => article.id === openId)
    ? openId
    : null;
  const summary = query
    ? `Showing ${articles.length} related ${articles.length === 1 ? "question" : "questions"}`
    : `Showing all ${articles.length} related questions`;

  return (
    <div>
      <h2 className="text-[1.65rem] font-bold leading-tight text-[#1A1A2E] sm:text-[1.85rem]">
        How can we help you?
      </h2>
      <p aria-live="polite" className="mt-1.5 text-sm text-[#9AA0B4]">
        {summary}
      </p>

      {articles.length === 0 ? (
        <div className="mt-8 rounded-2xl border border-dashed border-[#D9D6EA] px-5 py-10 text-center">
          <p className="font-semibold text-ink">
            No questions match that search.
          </p>
          <p className="mt-2 text-sm leading-relaxed text-[#6B7280]">
            Try a topic such as setup, the chat bot, security, or the API. You
            can also contact support from the card on the right.
          </p>
        </div>
      ) : (
        <ul className="mt-5 border-t border-[#E7E4F1] sm:mt-6">
          {articles.map((article) => {
            const isOpen = visibleOpenId === article.id;
            const panelId = `${baseId}-panel-${article.id}`;
            const buttonId = `${baseId}-button-${article.id}`;
            const topic = getTopic(article.topicId);

            return (
              <li key={article.id} className="border-b border-[#E7E4F1]">
                <h3>
                  <button
                    type="button"
                    id={buttonId}
                    aria-expanded={isOpen}
                    aria-controls={panelId}
                    onClick={() =>
                      setOpenId((current) =>
                        current === article.id ? null : article.id,
                      )
                    }
                    className="flex w-full items-center justify-between gap-4 py-3.5 text-left transition-colors hover:text-brand focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-brand sm:py-4"
                  >
                    <span className="text-[15px] font-medium text-[#2C2C3A] sm:text-base">
                      {article.question}
                    </span>
                    <span
                      aria-hidden="true"
                      className="grid size-6 shrink-0 place-items-center text-[#A7ABBA]"
                    >
                      {isOpen ? (
                        <Minus className="size-4" strokeWidth={1.75} />
                      ) : (
                        <Plus className="size-4" strokeWidth={1.75} />
                      )}
                    </span>
                  </button>
                </h3>

                <AnimatePresence initial={false}>
                  {isOpen ? (
                    <motion.div
                      id={panelId}
                      role="region"
                      aria-labelledby={buttonId}
                      initial={
                        reducedMotion ? false : { height: 0, opacity: 0 }
                      }
                      animate={{ height: "auto", opacity: 1 }}
                      exit={
                        reducedMotion ? undefined : { height: 0, opacity: 0 }
                      }
                      transition={{ duration: reducedMotion ? 0 : 0.22 }}
                      className="overflow-hidden"
                    >
                      <div className="pb-5 pr-4 sm:pr-12">
                        <p className="text-sm leading-relaxed text-[#5C6178] sm:text-base">
                          {article.answer}
                        </p>
                        <Link
                          href={`/faq/${article.topicId}#${article.id}`}
                          className="mt-3 inline-flex text-sm font-semibold text-brand underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-brand"
                        >
                          Open the {topic?.label ?? "topic"} guide
                        </Link>
                      </div>
                    </motion.div>
                  ) : null}
                </AnimatePresence>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
};

export default QuestionList;
