"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { toast } from "react-hot-toast";
import { SquarePen, Trash2 } from "lucide-react";
import {
  useDeleteAnswerMutation,
  useGetAnswerListQuery,
  useGetBookmarkListQuery,
  useGetQuestionListQuery,
} from "@/api/seaqa.api";
import { parseApiError } from "@/api/utils/error-handler";
import type { IAnswer } from "@/api/types/questions";
import type { IUserProfile } from "@/api/types/auth";
import Avatar from "@/components/common/Avatar";
import ConfirmModal from "@/components/common/ConfirmModal";
import BookmarkListSection from "@/components/MyAccount/BookmarkListSection";
import {
  AnswerRow,
  EmptyState,
  formatDate,
  Paginator,
  QuestionRow,
  SkeletonList,
  stripHtml,
  TopicPill,
} from "@/components/MyContent/contentShared";

interface MyContentSectionProps {
  userProfile?: IUserProfile;
}

const PER_PAGE = 10;

type Tab = "questions" | "answers" | "drafts" | "bookmarks";

// Draft answers get a dedicated card with an "Edit Draft" action that opens the
// discussion, where SeaQaAnswerForm pre-fills the saved draft body, plus a trash
// button that deletes the draft (DELETE /sea-qa/answer/{answerId}) after a
// confirmation modal handled by the parent.
const DraftRow = ({
  answer,
  onDelete,
}: {
  answer: IAnswer;
  onDelete: () => void;
}) => {
  const href = answer.question?.code
    ? `/discussion/${answer.question.code}`
    : `/discussion/${answer.questionId}`;
  const lastEdited = answer.editedAt || answer.updatedAt || answer.createdAt;
  const categories = answer.question?.categories ?? [];
  // The whole card navigates to the discussion (same destination as the
  // "Edit Draft" action). The delete button stops propagation so it doesn't
  // trigger navigation.
  return (
    <Link
      href={href}
      className="block px-6 py-4 space-y-1.5 hover:bg-coolgray-50/60 transition-colors no-underline"
    >
      <div className="flex items-center gap-2 flex-wrap">
        {categories.map((c) => (
          <TopicPill key={c.id} name={c.name} />
        ))}
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full bg-amber-50 border border-amber-200 text-xs text-amber-600 font-semibold">
          Draft · Answer
        </span>
      </div>
      {answer.question?.title && (
        <p className="text-base font-bold text-coolgray-900 leading-snug hover:text-blue-light transition-colors">
          {answer.question.title}
        </p>
      )}

      {answer.body && (
        <div
          className="text-[13px] text-coolgray-500 leading-[1.7]  prose-rich"
          dangerouslySetInnerHTML={{ __html: answer.body }}
        />
      )}
      <div className="flex items-center justify-between pt-1">
        <span className="text-xs text-coolgray-400">
          Last edited {formatDate(lastEdited)}
        </span>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onDelete();
            }}
            aria-label="Delete draft"
            className="p-1.5 rounded-lg text-coolgray-300 hover:text-red-400 hover:bg-red-50 transition-colors cursor-pointer"
          >
            <Trash2 className="h-3.5 w-3.5" />
          </button>
          <span className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-coolgray-200 text-xs font-semibold text-coolgray-600 transition-colors">
            <SquarePen className="h-3.5 w-3.5" />
            Edit Draft
          </span>
        </div>
      </div>
    </Link>
  );
};

const MyContentSection = ({ userProfile }: MyContentSectionProps) => {
  const searchParams = useSearchParams();
  const [tab, setTab] = useState<Tab>("questions");
  const [questionPage, setQuestionPage] = useState(1);
  const [answerPage, setAnswerPage] = useState(1);
  const [draftPage, setDraftPage] = useState(1);

  // Draft pending deletion (drives the confirmation modal).
  const [draftToDelete, setDraftToDelete] = useState<IAnswer | null>(null);
  const [deleteAnswer, { isLoading: isDeleting }] = useDeleteAnswerMutation();

  const handleConfirmDelete = async () => {
    if (!draftToDelete) return;
    try {
      await deleteAnswer(draftToDelete.id).unwrap();
      toast.success("Draft deleted.");
      setDraftToDelete(null);
    } catch (error) {
      toast.error(parseApiError(error));
    }
  };

  // Apply the deep-link tab param, e.g. ?tab=answers (used by the
  // rejected-content notifications). Status is no longer filtered — every
  // question/answer is shown in its tab with a status badge on the row.
  useEffect(() => {
    const tabParam = searchParams.get("tab");
    if (
      tabParam === "answers" ||
      tabParam === "questions" ||
      tabParam === "drafts" ||
      tabParam === "bookmarks"
    ) {
      setTab(tabParam);
    }
  }, [searchParams]);

  const refetchOpts = { refetchOnMountOrArgChange: true } as const;

  // Active lists — no status filter; every question/answer is listed and the
  // per-row badge shows its moderation status.
  const { data: questionData, isLoading: isQuestionLoading } =
    useGetQuestionListQuery(
      {
        myQuestions: true,
        page: questionPage,
        perPage: PER_PAGE,
        sortBy: "id",
        sortDirection: "desc",
      },
      refetchOpts,
    );

  const { data: answerData, isLoading: isAnswerLoading } =
    useGetAnswerListQuery(
      {
        myAnswers: true,
        includeQuestion: true,
        page: answerPage,
        perPage: PER_PAGE,
        sortBy: "id",
        sortDirection: "desc",
      },
      refetchOpts,
    );

  const { data: draftData, isLoading: isDraftLoading } = useGetAnswerListQuery(
    {
      myAnswers: true,
      includeQuestion: true,
      status: "draft",
      page: draftPage,
      perPage: PER_PAGE,
      sortBy: "id",
      sortDirection: "desc",
    },
    refetchOpts,
  );

  // Totals for the tab counts (perPage:1 — we only need totalRecords).
  const { data: qTotal } = useGetQuestionListQuery(
    { myQuestions: true, perPage: 1 },
    refetchOpts,
  );
  const { data: aTotal } = useGetAnswerListQuery(
    { myAnswers: true, perPage: 1 },
    refetchOpts,
  );

  const { data: bookmarkTotal } = useGetBookmarkListQuery(
    { entityType: "answer", perPage: 1 },
    refetchOpts,
  );

  // Draft count comes straight from the draft list query (no extra request).
  const draftCount = draftData?.totalRecords ?? 0;
  // The Answers tab excludes drafts (they live in their own tab), so its count
  // is the raw total minus drafts.
  const answerNonDraftTotal = Math.max(
    (aTotal?.totalRecords ?? 0) - draftCount,
    0,
  );

  const questions = questionData?.data ?? [];
  // The answer list returns drafts too — filter them out here so the Answers
  // tab and the Drafts tab stay distinct.
  const answers = (answerData?.data ?? []).filter((a) => a.status !== "draft");
  const drafts = draftData?.data ?? [];

  const TABS: { key: Tab; label: string; count: number }[] = [
    { key: "questions", label: "Questions", count: qTotal?.totalRecords ?? 0 },
    { key: "answers", label: "Answers", count: answerNonDraftTotal },
    { key: "drafts", label: "Drafts", count: draftCount },
    {
      key: "bookmarks",
      label: "Bookmarks",
      count: bookmarkTotal?.totalRecords ?? 0,
    },
  ];

  return (
    <div className="flex flex-col gap-5 font-system">
      {/* Profile card + tabs */}
      <div className="bg-white rounded-2xl border border-[#E2E2E2] overflow-hidden">
        {userProfile && (
          <>
            <div className="p-6 space-y-4">
              <div className="flex items-start sm:items-center gap-4">
                <Avatar
                  src={userProfile.profileImage?.filePath}
                  name={userProfile.name || "User"}
                  size="2xl"
                />

                <div className="flex-1 min-w-0">
                  <p className="text-lg font-bold text-coolgray-900 leading-tight truncate">
                    {userProfile.name}
                  </p>
                  <p className="text-sm text-coolgray-500 mt-0.5 truncate">
                    {userProfile.rank?.name}
                    {userProfile.presentCompany
                      ? ` · ${userProfile.presentCompany}`
                      : ""}
                  </p>
                </div>

                <Link
                  href="/my-account?current-section=edit-profile"
                  className="self-start sm:self-auto sm:ml-auto shrink-0 flex items-center gap-1.5 px-3 sm:px-5 py-2 rounded-xl text-sm font-semibold bg-coolgray-100 text-coolgray-700 hover:bg-coolgray-200 border border-coolgray-200 transition-colors no-underline"
                >
                  <SquarePen className="h-3.5 w-3.5" />
                  <span className="hidden sm:inline">Edit Profile</span>
                </Link>
              </div>

              {userProfile.aboutMe && (
                <p className="text-sm text-coolgray-500 leading-relaxed whitespace-pre-line">
                  {userProfile.aboutMe}
                </p>
              )}
            </div>

            <div className="border-t border-coolgray-100" />
          </>
        )}

        <div className="flex">
          {TABS.map((t) => {
            const active = tab === t.key;
            return (
              <button
                key={t.key}
                type="button"
                onClick={() => setTab(t.key)}
                className={`flex-1 flex flex-col items-center py-3 text-xs font-semibold transition-all border-b-2 ${
                  active
                    ? "border-blue-light text-coolgray-900"
                    : "border-transparent text-coolgray-500 hover:text-coolgray-700"
                }`}
              >
                <span className="text-base font-bold text-coolgray-900">
                  {t.count}
                </span>
                <span className="leading-tight text-center">{t.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Lists */}
      {tab === "questions" &&
        (isQuestionLoading ? (
          <SkeletonList />
        ) : questions.length === 0 ? (
          <EmptyState label="questions" />
        ) : (
          <>
            <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden">
              {questions.map((q) => (
                <QuestionRow key={q.id} q={q} />
              ))}
            </div>
            <Paginator
              totalPages={questionData?.totalPages ?? 1}
              currentPage={questionPage}
              onChange={setQuestionPage}
            />
          </>
        ))}

      {tab === "answers" &&
        (isAnswerLoading ? (
          <SkeletonList />
        ) : answers.length === 0 ? (
          <EmptyState label="answers" />
        ) : (
          <>
            <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden">
              {answers.map((a) => (
                <AnswerRow key={a.id} answer={a} />
              ))}
            </div>
            <Paginator
              totalPages={answerData?.totalPages ?? 1}
              currentPage={answerPage}
              onChange={setAnswerPage}
            />
          </>
        ))}

      {tab === "drafts" &&
        (isDraftLoading ? (
          <SkeletonList />
        ) : drafts.length === 0 ? (
          <EmptyState label="drafts" />
        ) : (
          <>
            <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden">
              {drafts.map((d) => (
                <DraftRow
                  key={d.id}
                  answer={d}
                  onDelete={() => setDraftToDelete(d)}
                />
              ))}
            </div>
            <Paginator
              totalPages={draftData?.totalPages ?? 1}
              currentPage={draftPage}
              onChange={setDraftPage}
            />
          </>
        ))}

      {tab === "bookmarks" && <BookmarkListSection hideHeading />}

      <ConfirmModal
        isOpen={!!draftToDelete}
        onClose={() => {
          if (!isDeleting) setDraftToDelete(null);
        }}
        onConfirm={handleConfirmDelete}
        title="Delete draft?"
        description="This draft answer will be permanently removed. This can't be undone."
        confirmLabel="Delete"
        cancelLabel="Cancel"
        destructive
        loading={isDeleting}
        loadingLabel="Deleting…"
      />
    </div>
  );
};

export default MyContentSection;
