"use client";

import React from "react";
import Link from "next/link";
import ReactPaginate from "react-paginate";
import {
  MessageSquare,
  ChevronLeft,
  ChevronRight,
  Bookmark,
  ArrowRight,
  CheckCircle2,
  Clock,
  XCircle,
  FileText,
  GitMerge,
  type LucideIcon,
} from "lucide-react";
import type { IAnswer, IQuestion } from "@/api/types/questions";

// Shared presentational pieces for the My Content and public user-profile
// content lists, so both render question/answer rows identically.

export function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

export function stripHtml(html: string): string {
  return html.replace(/<[^>]*>/g, "").trim();
}

export const statusConfig: Record<
  string,
  { label: string; className: string; icon: LucideIcon }
> = {
  approved: {
    label: "Approved",
    className: "bg-emerald-50 border-emerald-200 text-emerald-700",
    icon: CheckCircle2,
  },
  published: {
    label: "Approved",
    className: "bg-emerald-50 border-emerald-200 text-emerald-700",
    icon: CheckCircle2,
  },
  pending: {
    label: "Pending Approval",
    className: "bg-amber-50 border-amber-200 text-amber-700",
    icon: Clock,
  },
  pending_approval: {
    label: "Pending Approval",
    className: "bg-amber-50 border-amber-200 text-amber-700",
    icon: Clock,
  },
  rejected: {
    label: "Rejected",
    className: "bg-red-50 border-red-200 text-red-700",
    icon: XCircle,
  },
  draft: {
    label: "Draft",
    className: "bg-amber-50 border-amber-200 text-amber-600",
    icon: FileText,
  },
  merged: {
    label: "Merged",
    className: "bg-violet-50 border-violet-200 text-violet-700",
    icon: GitMerge,
  },
};

const APPROVED_STATUSES = new Set(["approved", "published"]);

// Skeleton for the question/answer/draft lists — mirrors QuestionRow/AnswerRow
// inside a single divide-y container: a pill row (topic/status), the title, a
// two-line body clamp, then a footer with a meta chip on the left and a date on
// the right.
export const SkeletonList = () => (
  <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden">
    {Array.from({ length: 4 }).map((_, i) => (
      <div key={i} className="px-6 py-4 space-y-2.5 animate-pulse">
        <div className="flex items-center gap-2">
          <div className="h-5 w-20 bg-coolgray-200 rounded-full" />
          <div className="h-5 w-16 bg-coolgray-100 rounded-full" />
        </div>
        <div className="h-5 w-3/4 bg-coolgray-200 rounded" />
        <div className="space-y-1.5">
          <div className="h-3.5 w-full bg-coolgray-100 rounded" />
          <div className="h-3.5 w-2/3 bg-coolgray-100 rounded" />
        </div>
        <div className="flex items-center justify-between pt-1">
          <div className="h-3.5 w-20 bg-coolgray-100 rounded" />
          <div className="h-3.5 w-16 bg-coolgray-100 rounded" />
        </div>
      </div>
    ))}
  </div>
);

// Skeleton for the bookmark list — mirrors BookmarkRow inside a single
// divide-y container: title, a two-line body clamp, then a footer with an
// avatar + author meta on the left and a "Remove" button placeholder on the
// right.
export const BookmarkSkeletonList = () => (
  <div className="bg-white rounded-2xl border border-[#E2E2E2] divide-y divide-coolgray-100 overflow-hidden">
    {Array.from({ length: 4 }).map((_, i) => (
      <div key={i} className="px-6 py-4 space-y-2.5 animate-pulse">
        <div className="h-5 w-3/4 bg-coolgray-200 rounded" />
        <div className="space-y-1.5">
          <div className="h-3.5 w-full bg-coolgray-100 rounded" />
          <div className="h-3.5 w-2/3 bg-coolgray-100 rounded" />
        </div>
        <div className="flex items-center justify-between gap-3 pt-1">
          <div className="flex items-center gap-2">
            <div className="h-8 w-8 bg-coolgray-200 rounded-full" />
            <div className="space-y-1.5">
              <div className="h-3 w-24 bg-coolgray-200 rounded" />
              <div className="h-2.5 w-32 bg-coolgray-100 rounded" />
            </div>
          </div>
          <div className="h-7 w-20 bg-coolgray-100 rounded-lg" />
        </div>
      </div>
    ))}
  </div>
);

// Shared empty state for every My Content tab — identical design, only the
// noun in the message changes per tab. The "Browse seaqa" CTA points at the
// public Q&A listing.
export const EmptyState = ({
  label,
  message,
  cta = { label: "Browse seaqa", href: "/questions" },
}: {
  label: string;
  message?: string;
  cta?: { label: string; href: string } | null;
}) => (
  <div className="bg-white rounded-2xl border border-[#E2E2E2] px-6 py-14 flex flex-col items-center gap-3 text-center">
    <Bookmark className="h-8 w-8 text-coolgray-200" />
    <p className="text-sm text-coolgray-400 font-medium">
      {message ?? `No ${label} yet`}
    </p>
    {cta && (
      <Link
        href={cta.href}
        className="inline-flex items-center gap-1 text-xs text-blue-light hover:text-blue-light-hover font-semibold transition-colors no-underline"
      >
        {cta.label}
        <ArrowRight className="h-3.5 w-3.5" />
      </Link>
    )}
    <span className="sr-only">{label}</span>
  </div>
);

export const TopicPill = ({ name }: { name: string }) => (
  <span className="inline-flex items-center px-3 py-1 rounded-full border border-slate-400 text-xs text-slate-600 bg-transparent font-medium">
    {name}
  </span>
);

export const StatusPill = ({ status }: { status: string }) => {
  const cfg = statusConfig[status] ?? {
    label: status,
    className: "bg-coolgray-100 border-coolgray-200 text-coolgray-600",
    icon: FileText,
  };
  const Icon = cfg.icon;
  return (
    <span
      className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full border text-xs font-semibold ${cfg.className}`}
    >
      <Icon className="h-3 w-3" />
      {cfg.label}
    </span>
  );
};

export const QuestionRow = ({ q }: { q: IQuestion }) => {
  const categories = q.categories ?? [];
  const isApproved = APPROVED_STATUSES.has(q.status);
  const isMerged = q.status === "merged";
  // Approved and merged questions both link to a live discussion; everything
  // else renders as a non-interactive card.
  const isClickable = isApproved || isMerged;
  const href = `/discussion/${q.code}`;
  const preview = stripHtml(q.description || "").slice(0, 200);
  const baseClass = "block px-6 py-4 space-y-1.5 transition-colors";
  const interactiveClass = isClickable
    ? "hover:bg-coolgray-50/60 cursor-pointer"
    : "cursor-default";
  const content = (
    <>
      <div className="flex items-center gap-2 flex-wrap">
        {categories.map((c) => (
          <TopicPill key={c.id} name={c.name} />
        ))}
        <StatusPill status={q.status} />
      </div>
      <p
        className={`text-base font-bold text-coolgray-900 leading-snug ${
          isClickable ? "hover:text-blue-light transition-colors" : ""
        }`}
      >
        {q.title}
      </p>
      {preview && (
        <p className="text-[13px] text-coolgray-500 leading-[1.7] line-clamp-2 whitespace-pre-line">
          {preview}
        </p>
      )}
      {q.status === "rejected" && q.rejectedReason && (
        <p className="text-red-600 text-[12px] font-medium leading-[1.4] whitespace-pre-line">
          Reason: {q.rejectedReason}
        </p>
      )}
      <div className="flex items-center justify-between pt-1">
        <div className="flex items-center gap-1 text-xs text-coolgray-400">
          <MessageSquare className="h-3.5 w-3.5" />
          <span className="font-medium">
            {q.answersCount} {q.answersCount === 1 ? "answer" : "answers"}
          </span>
        </div>
        <span className="text-xs text-coolgray-400">
          {formatDate(q.createdAt)}
        </span>
      </div>
    </>
  );
  return isClickable ? (
    <Link href={href} className={`${baseClass} ${interactiveClass}`}>
      {content}
    </Link>
  ) : (
    <div className={`${baseClass} ${interactiveClass}`}>{content}</div>
  );
};

export const AnswerRow = ({ answer }: { answer: IAnswer }) => {
  const href = answer.question?.code
    ? `/discussion/${answer.question.code}`
    : `/discussion/${answer.questionId}`;
  const categories = answer.question?.categories ?? [];
  return (
    <Link
      href={href}
      className="block px-6 py-4 space-y-1.5 hover:bg-coolgray-50/60 transition-colors"
    >
      <div className="flex items-center gap-2 flex-wrap">
        {categories.map((c) => (
          <TopicPill key={c.id} name={c.name} />
        ))}
        <StatusPill status={answer.status} />
      </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] line-clamp-2 prose-rich"
          dangerouslySetInnerHTML={{ __html: answer.body }}
        />
      )}
      {answer.status === "rejected" && answer.rejectedReason && (
        <p className="text-red-600 text-[12px] font-medium leading-[1.4] whitespace-pre-line">
          Reason: {answer.rejectedReason}
        </p>
      )}
      <div className="flex items-center justify-between pt-1">
        <div className="flex items-center gap-1 text-xs text-coolgray-400">
          <MessageSquare className="h-3.5 w-3.5" />
          <span className="font-medium">
            {answer.commentsCount}{" "}
            {answer.commentsCount === 1 ? "comment" : "comments"}
          </span>
        </div>
        <span className="text-xs text-coolgray-400">
          {formatDate(answer.createdAt)}
        </span>
      </div>
    </Link>
  );
};

export const Paginator = ({
  totalPages,
  currentPage,
  onChange,
}: {
  totalPages: number;
  currentPage: number;
  onChange: (next: number) => void;
}) => {
  if (totalPages <= 1) return null;
  return (
    <ReactPaginate
      pageCount={totalPages}
      pageRangeDisplayed={3}
      marginPagesDisplayed={1}
      forcePage={currentPage - 1}
      onPageChange={({ selected }) => onChange(selected + 1)}
      previousLabel={<ChevronLeft size={15} strokeWidth={2} />}
      nextLabel={<ChevronRight size={15} strokeWidth={2} />}
      breakLabel="…"
      containerClassName="flex items-center justify-center gap-1.5 mt-2"
      pageClassName="flex"
      pageLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-coolgray-200 text-coolgray-600 text-[14px] font-semibold hover:bg-coolgray-50 transition-colors cursor-pointer"
      activeClassName="[&>a]:bg-blue-light [&>a]:text-white [&>a]:border-blue-light"
      previousClassName="flex"
      previousLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-coolgray-200 text-coolgray-600 hover:bg-coolgray-50 transition-colors cursor-pointer"
      nextClassName="flex"
      nextLinkClassName="w-8 h-8 flex items-center justify-center rounded-lg border border-coolgray-200 text-coolgray-600 hover:bg-coolgray-50 transition-colors cursor-pointer"
      breakClassName="flex"
      breakLinkClassName="w-8 h-8 flex items-center justify-center text-coolgray-500 text-[14px]"
      disabledClassName="opacity-40 cursor-not-allowed pointer-events-none"
    />
  );
};
