"use client";

import {
  useBookmarkEntityMutation,
  useGetBookmarkListQuery,
} from "@/api/seaqa.api";
import { IAnswer } from "@/api/types/questions";
import Avatar from "@/components/common/Avatar";
import {
  BookmarkSkeletonList,
  EmptyState,
  Paginator,
  formatDate,
} from "@/components/MyContent/contentShared";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { Trash2 } from "lucide-react";

const PER_PAGE = 20;

interface BookmarkRowProps {
  answer: IAnswer;
  onRemove: (id: number) => void;
  removing: boolean;
}

// Bookmark row — mirrors the My Content question/answer rows: a clickable row
// inside a single divide-y container, with the body clamped to two lines and a
// compact footer (author on the left, Remove on the right). The Remove button
// stops propagation so it doesn't trigger navigation.
const BookmarkRow: React.FC<BookmarkRowProps> = ({
  answer,
  onRemove,
  removing,
}) => {
  const authorMeta = [answer.author.rank?.name, formatDate(answer.createdAt)]
    .filter(Boolean)
    .join(" · ");

  const questionHref = answer.question?.code
    ? `/discussion/${answer.question.code}`
    : `/discussion/${answer.questionId}`;

  return (
    <Link
      href={questionHref}
      className="block px-6 py-4 space-y-1.5 hover:bg-coolgray-50/60 transition-colors no-underline"
    >
      {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 gap-3 pt-1">
        <div className="flex items-center gap-2 min-w-0">
          <Avatar
            src={answer.author.profileImage?.filePath}
            name={answer.author.name}
            size="sm"
          />
          <div className="min-w-0">
            <p className="text-xs font-semibold text-coolgray-700 leading-tight truncate">
              {answer.author.name}
            </p>
            {authorMeta && (
              <p className="text-[11px] text-coolgray-400 leading-tight truncate">
                {authorMeta}
              </p>
            )}
          </div>
        </div>

        <button
          type="button"
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onRemove(answer.id);
          }}
          disabled={removing}
          className="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-coolgray-200 text-xs font-semibold text-coolgray-600 hover:bg-coolgray-50 transition-colors cursor-pointer disabled:opacity-50"
        >
          <Trash2 className="h-3.5 w-3.5" />
          Remove
        </button>
      </div>
    </Link>
  );
};

const BookmarkListSection = ({
  hideHeading = false,
}: {
  hideHeading?: boolean;
}) => {
  const [page, setPage] = useState(1);
  const { data, isLoading, isFetching } = useGetBookmarkListQuery({
    entityType: "answer",
    page,
    perPage: PER_PAGE,
    sortBy: "id",
    sortDirection: "desc",
  });
  const [bookmarkEntity, { isLoading: removing }] = useBookmarkEntityMutation();

  const bookmarks = data?.data ?? [];
  const totalPages = data?.totalPages ?? 1;

  // After a removal (or any refetch) the result set can shrink — if the
  // current page no longer exists, step back to the last valid page.
  useEffect(() => {
    if (page > totalPages) setPage(totalPages);
  }, [page, totalPages]);

  const handleRemove = async (entityId: number) => {
    await bookmarkEntity({ entityType: "answer", entityId });
  };

  const heading = !hideHeading && (
    <h2 className="text-black font-semibold text-2xl leading-tight tracking-tight">
      Bookmark List
    </h2>
  );

  if (isLoading) {
    return (
      <div className="flex flex-col w-full gap-6">
        {heading}
        <BookmarkSkeletonList />
      </div>
    );
  }

  return (
    <div className="flex flex-col w-full gap-5">
      {heading}

      {bookmarks.length === 0 ? (
        <EmptyState label="bookmarks" />
      ) : (
        <>
          <div
            className={`bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden transition-opacity ${
              isFetching ? "opacity-60" : "opacity-100"
            }`}
          >
            {bookmarks.map((answer) => (
              <BookmarkRow
                key={answer.id}
                answer={answer}
                onRemove={handleRemove}
                removing={removing}
              />
            ))}
          </div>

          <Paginator
            totalPages={totalPages}
            currentPage={page}
            onChange={setPage}
          />
        </>
      )}
    </div>
  );
};

export default BookmarkListSection;
