import React from "react";
import { Link } from "react-router-dom";
import { ForumPost } from "../types";
import CategoryBadge from "./CategoryBadge";
import PostStatusBadge from "./PostStatusBadge";
import { useAuth } from "../contexts/AuthContext";

interface ForumPostListItemProps {
  post: ForumPost;
  filter?: string;
}

const ForumPostListItem: React.FC<ForumPostListItemProps> = ({ post, filter }) => {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMinutes < 1) {
      return "Just now";
    } else if (diffMinutes < 60) {
      return `${diffMinutes}m ago`;
    } else if (diffHours < 24) {
      return `${diffHours}h ago`;
    } else if (diffDays < 7) {
      return `${diffDays}d ago`;
    } else {
      return date.toLocaleDateString();
    }
  };

  // Strip HTML tags for preview
  const getTextPreview = (html: string, maxLength: number = 100) => {
    const text = html.replace(/<[^>]*>/g, "");
    return text.length > maxLength
      ? `${text.substring(0, maxLength)}...`
      : text;
  };

  // Build link with filter param if admin and filter is set
  const linkTo = filter && isAdmin ? `/forum/${post.id}?filter=${filter}` : `/forum/${post.id}`;

  return (
    <div className="list-group-item list-group-item-action p-3">
      <Link to={linkTo} className="text-decoration-none d-block">
        <div className="row align-items-center">
          {/* Main content - 60% */}
          <div className="col-md-7">
            <div className="d-flex align-items-center gap-2 mb-1">
              <div className="d-flex gap-2">
                {post.isPinned && (
                  <span className="badge bg-danger badge-sm">
                    <i className="bi bi-pin-angle-fill"></i>
                  </span>
                )}
                {post.isDeleted && isAdmin && (
                  <span className="badge bg-danger badge-sm">
                    <i className="bi bi-trash me-1"></i>
                    Deleted
                  </span>
                )}
                <CategoryBadge category={post.category} />
                <PostStatusBadge status={post.status} />
                {post.tags &&
                  post.tags.length > 0 &&
                  post.tags.slice(0, 2).map((tag) => (
                    <span key={tag.id} className="badge bg-light text-dark">
                      #{tag.tagName}
                    </span>
                  ))}
                {post.tags && post.tags.length > 2 && (
                  <span className="badge bg-light text-dark">
                    +{post.tags.length - 2}
                  </span>
                )}
              </div>
            </div>

            <h6 className="mb-1 text-dark">{post.title}</h6>

            <p className="text-muted small mb-0">
              {getTextPreview(post.content)}
            </p>
          </div>

          {/* Author - 20% */}
          <div className="col-md-3">
            <div className="d-flex align-items-center">
              <div
                className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2"
                style={{
                  width: "32px",
                  height: "32px",
                  fontSize: "14px",
                  flexShrink: 0,
                }}
              >
                {post.author?.firstName?.charAt(0) || "?"}
              </div>
              <div className="text-truncate">
                <small className="text-dark d-block text-truncate">
                  {post.author?.firstName || "Unknown"}{" "}
                  {post.author?.lastName || ""}
                </small>
                <small className="text-muted">
                  {formatDate(post.updatedAt)}
                </small>
              </div>
            </div>
          </div>

          {/* Stats - 20% */}
          <div className="col-md-2 text-end">
            <div className="d-flex flex-column align-items-end gap-1">
              <small className="text-muted">
                <i className="bi bi-chat me-1"></i>
                {post.commentCount || 0}{" "}
                {post.commentCount === 1 ? "reply" : "replies"}
              </small>
            </div>
          </div>
        </div>
      </Link>
    </div>
  );
};

export default ForumPostListItem;
