"use client";

import { useGetQuestionListQuery } from "@/api/seaqa.api";
import Link from "next/link";
import React from "react";
import SeaQaRelatedQuestionsSkeleton from "@/components/skeleton/SeaQaRelatedQuestionsSkeleton";

interface SeaQaRelatedQuestionsProps {
  categoryIds: number[];
  currentQuestionId?: number;
}

const SeaQaRelatedQuestions: React.FC<SeaQaRelatedQuestionsProps> = ({
  categoryIds,
  currentQuestionId,
}) => {
  const {
    data: qData,
    isLoading: qLoading,
    isFetching,
  } = useGetQuestionListQuery(
    { categoryIds, perPage: 7 },
    { skip: categoryIds.length === 0 },
  );

  const questions = (qData?.data ?? [])
    .filter((q) => q.id !== currentQuestionId)
    .slice(0, 4);

  // Show the skeleton while the related-questions query is in flight. When the
  // query is skipped (a question with no categories), this stays false and we
  // fall through to the "no related questions" empty state.
  if (qLoading || isFetching) {
    return <SeaQaRelatedQuestionsSkeleton />;
  }

  return (
    <div className="flex flex-col gap-3 w-full">
      {/* Questions on Similar Topics */}
      <div className="bg-white rounded-2xl p-4">
        <p className="text-[12px] font-semibold text-[#9ca3af] tracking-[0.06em] uppercase mb-3">
          Questions on Similar Topics
        </p>
        <div>
          {questions.length === 0 ? (
            <p className="text-gray-400 text-[13px] py-2">
              No related questions found.
            </p>
          ) : (
            questions.map((question) => (
              <Link
                key={question.id}
                href={`/discussion/${question.code}`}
                className="group block py-3.5 border-b border-[#f3f4f6] no-underline last:border-b-0 last:pb-0"
              >
                <p className="text-[13px] font-medium text-[#1f2937] leading-[1.4] transition-colors group-hover:text-[#3b82f6]">
                  {question.title}
                </p>
                <p className="text-[11px] font-semibold text-[#9ca3af] mt-0.5">
                  {question.answersCount} answer
                  {question.answersCount !== 1 ? "s" : ""}
                </p>
              </Link>
            ))
          )}
        </div>
      </div>
    </div>
  );
};

export default SeaQaRelatedQuestions;
