"use client";

import React, { useState } from "react";
import moment from "moment";
import { useParams, useRouter } from "next/navigation";
import SeaQaQuestionDetail from "@/components/SeaQa/SeaQaDetailsComponents/SeaQaQuestionDetail";
import SeaQaAnswerForm from "@/components/SeaQa/SeaQaDetailsComponents/SeaQaAnswerForm";
import SeaQaAnswerCard from "@/components/SeaQa/SeaQaDetailsComponents/SeaQaAnswerCard";
import SeaQaRelatedQuestions from "@/components/SeaQa/SeaQaDetailsComponents/SeaQaRelatedQuestions";
import LoginModal from "@/components/Membership/LoginModal";
import PaywallCard from "@/components/Membership/PaywallCard";
import SubscriptionRequiredModal from "@/components/Membership/SubscriptionRequiredModal";
import { useGetQuestionBySlugQuery } from "@/api/seaqa.api";
import { useAppSelector } from "@/redux/hooks";
import ErrorCard from "@/components/common/ErrorCard";
import SeaQaQuestionDetailSkeleton from "@/components/skeleton/SeaQaQuestionDetailSkeleton";
import SeaQaAnswerCardSkeleton from "@/components/skeleton/SeaQaAnswerCardSkeleton";
import SeaQaRelatedQuestionsSkeleton from "@/components/skeleton/SeaQaRelatedQuestionsSkeleton";

const FALLBACK_AVATAR = "/assets/images/avatar-dummy.png";

function formatDate(iso: string): string {
  return moment(iso).format("MMMM D, YYYY");
}

const SeaQaDetailsPage = () => {
  const { slug } = useParams<{ slug: string }>();
  const router = useRouter();
  const { user, isAuthenticated } = useAppSelector((state) => state.auth);
  const isSubscribed = user?.isPremium ?? false;

  const [loginModalOpen, setLoginModalOpen] = useState(false);
  const [subModalOpen, setSubModalOpen] = useState(false);

  const {
    data: question,
    isLoading,
    isError,
    refetch,
  } = useGetQuestionBySlugQuery(slug);

  // The current user has already answered if any answer's author matches them.
  // author.id is numeric while user.id may be a string, so coerce before comparing.
  const currentUserId = user?.id != null ? Number(user.id) : null;
  const isMyAnswerPresent = !!(
    currentUserId != null &&
    question?.answers?.some((a) => a?.author?.id === currentUserId)
  );

  return (
    <div className="bg-[#efefef] min-h-screen pb-12 font-sans">
      <main className="w-[1074px] max-w-full mx-auto py-6 px-4 flex flex-col lg:flex-row gap-6">
        {/* Main Content */}
        <div className="w-full lg:w-[650px] shrink-0 flex flex-col gap-3">
          {isError ? (
            <ErrorCard
              message="Failed to load question. Please try again."
              onRetry={() => refetch()}
            />
          ) : (
            <div className="bg-white p-[16px_24px] flex flex-col items-start gap-3 rounded-2xl w-full">
              {isLoading && <SeaQaQuestionDetailSkeleton />}

              {question && (
                <>
                  {/* Condition 1: Not logged in — show title only + paywall */}
                  {!isAuthenticated ? (
                    <>
                      {/* <div className="w-full pb-10">
                      <h1 className="text-gray-900 font-bold text-[24px] leading-7.5 tracking-[-0.48px]">
                        {question.title}
                      </h1>
                    </div> */}
                      {/* <div className="flex flex-col gap-3 self-stretch w-full">
                      {question.categories &&
                        question.categories.length > 0 && (
                          <div className="flex flex-wrap gap-2">
                            {question.categories.map((cat) => (
                              <span
                                key={cat.id}
                                className="inline-flex items-center h-6.25 px-3 rounded-full border border-[#94a3b8] bg-transparent text-[12px] font-medium text-[#475569]"
                              >
                                {cat.name}
                              </span>
                            ))}
                          </div>
                        )}
                      <div className="w-full flex flex-col gap-1">
                        <h1 className="text-[18px] font-bold text-[#111827] leading-[1.35]">
                          {question.title}
                        </h1>
                      </div>
                     
                    </div> */}
                      <SeaQaQuestionDetail
                        title={question.title}
                        description={question.description}
                        categories={question.categories}
                      />
                      <PaywallCard
                        onLoginClick={() => setLoginModalOpen(true)}
                      />
                    </>
                  ) : (
                    /* Conditions 2 & 3: logged in (subscribed or not) */
                    <>
                      <SeaQaQuestionDetail
                        title={question.title}
                        description={question.description}
                        categories={question.categories}
                      />

                      {question?.status !== "closed" && (
                        <>
                          {/* Condition 3: subscribed — show answer form */}
                          {isSubscribed ? (
                            // A user may only submit one answer per question. If they
                            // already have a non-draft answer, show a status message
                            // instead of the "Write answer" form. Drafts still open the
                            // form so they can finish/edit it.
                            (question.myAnswer &&
                              question.myAnswer.status !== "draft") ||
                            isMyAnswerPresent ? (
                              <div className="w-full flex flex-col gap-3">
                                <div className="w-full flex items-center justify-center py-6 border border-dashed border-gray-300 rounded-[10px]">
                                  <p className="text-[15px] text-gray-500 text-center px-4 leading-relaxed">
                                    {question.myAnswer &&
                                    question.myAnswer.status ===
                                      "pending_approval"
                                      ? "You've already answered this question. Your answer is pending approval from the admin."
                                      : "You've already answered this question — only one answer per question is allowed."}
                                  </p>
                                </div>

                                {/* A pending answer isn't in the public answers
                                  list yet, so show the user their own submission. */}
                                {question.myAnswer?.status ===
                                  "pending_approval" &&
                                  question.myAnswer.body && (
                                    <div className="w-full bg-white border border-[#e5e7eb] rounded-2xl p-5">
                                      <p className="text-xs font-semibold uppercase tracking-wide text-gray-400 mb-2">
                                        Your answer
                                      </p>
                                      <div
                                        className="prose-rich break-words"
                                        dangerouslySetInnerHTML={{
                                          __html: question.myAnswer.body,
                                        }}
                                      />
                                    </div>
                                  )}
                              </div>
                            ) : (
                              <SeaQaAnswerForm
                                key={question.id}
                                questionId={question.id}
                                slug={slug}
                                draft={
                                  question.myAnswer?.status === "draft"
                                    ? {
                                        id: question.myAnswer.id,
                                        body: question.myAnswer.body,
                                      }
                                    : null
                                }
                              />
                            )
                          ) : (
                            /* Condition 2: not subscribed — subscribe to reply CTA */
                            // <div
                            //   onClick={() => setSubModalOpen(true)}
                            //   className="w-full flex text-blue-light font-semibold text-[15px] hover:underline cursor-pointer items-center justify-center py-6 border border-dashed border-gray-300 rounded-[10px]"
                            // >
                            //   <button
                            //     onClick={() => setSubModalOpen(true)}
                            //     className=""
                            //   >
                            //     Subscribe to Reply
                            //   </button>
                            // </div>
                            <PaywallCard
                              mode={isAuthenticated ? "subscribe" : "login"}
                              onLoginClick={() => setLoginModalOpen(true)}
                              onSubscribeClick={() => setSubModalOpen(true)}
                            />
                          )}
                        </>
                      )}
                    </>
                  )}
                </>
              )}
            </div>
          )}

          {/* Answer skeletons while loading */}
          {isLoading && (
            <div className="flex flex-col gap-3">
              <SeaQaAnswerCardSkeleton />
              <SeaQaAnswerCardSkeleton />
            </div>
          )}

          {/* Condition 3 only: subscribed — show answers */}
          {isAuthenticated &&
            isSubscribed &&
            question &&
            question.answers.length > 0 && (
              <div className="flex flex-col gap-3">
                {question.answers.map((answer) => (
                  <SeaQaAnswerCard key={answer.id} answer={answer} />
                ))}
              </div>
            )}
        </div>

        {/* Sidebar */}
        <aside className="w-full lg:w-[400px] shrink-0 flex flex-col gap-3 pt-1">
          {isLoading ? (
            <SeaQaRelatedQuestionsSkeleton />
          ) : question ? (
            <SeaQaRelatedQuestions
              categoryIds={question.categories.map((c) => c.id)}
              currentQuestionId={question.id}
            />
          ) : null}
        </aside>
      </main>

      <LoginModal
        isOpen={loginModalOpen}
        onClose={() => setLoginModalOpen(false)}
        onSuccess={refetch}
      />

      <SubscriptionRequiredModal
        isOpen={subModalOpen}
        onClose={() => setSubModalOpen(false)}
        onViewPlans={() =>
          router.push(
            `/my-account?current-section=subscription&redirect=${encodeURIComponent(
              window.location.pathname,
            )}`,
          )
        }
      />
    </div>
  );
};

export default SeaQaDetailsPage;
