import React from "react";
import Link from "next/link";

export interface BlogItem {
  id: number;
  slug: string;
  title: string;
  description: string;
  author: string;
  datePosted: string;
  readTime: string;
  category: string;
  coverImage: string;
  blogUrl: string;
}

function formatDate(dateStr: string) {
  const date = new Date(dateStr);
  return date.toLocaleDateString("en-US", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default function BlogCard({ blog }: { blog: BlogItem }) {
  return (
    <div className="col-lg-4 col-md-6 col-sm-12 mb-4">
      <div className="card blog-card h-100 border-0 shadow-sm">
        {blog?.coverImage && blog?.coverImage.trim() !== "" ? (
          <Link
            href={blog.blogUrl}
            className="blog-card-thumb d-block position-relative overflow-hidden"
          >
            <img
              src={blog.coverImage}
              alt={blog.title}
              className="card-img-top w-100"
              style={{ height: "220px", objectFit: "cover" }}
            />
            <span className="badge text-bg-secondary bg-primary position-absolute top-0 start-0 m-3 px-3 py-2">
              {blog.category}
            </span>
          </Link>
        ) : (
          <div className="px-3 pt-3">
            <span className="badges badge-yellow">
              {blog.category}
            </span>
          </div>
        )}

        <div className="card-body d-flex flex-column">
          <ul className="list-inline mb-2 blog-card-meta text-muted small">
            <li className="list-inline-item me-3">
              <i className="fi fi-rr-user me-1"></i>
              {blog.author}
            </li>
            <li className="list-inline-item me-3">
              <i className="fi fi-rr-calendar me-1"></i>
              {formatDate(blog.datePosted)}
            </li>
            <li className="list-inline-item">
              <i className="fi fi-rr-clock-three me-1"></i>
              {blog.readTime}
            </li>
          </ul>

          <h5 className="card-title mb-2">
            <Link href={blog.blogUrl} className="blog-card-title">
              {blog.title}
            </Link>
          </h5>

          <p className="card-text text-muted flex-grow-1">
            {blog.description.length > 120
              ? `${blog.description.slice(0, 120).trim()}...`
              : blog.description}
          </p>

          <Link href={blog.blogUrl} className="default-btn btn btn-primary border-0">
            Read More <i className="fi fi-rr-arrow-small-right ms-1"></i>
            <span></span>
          </Link>
        </div>
      </div>
    </div>
  );
}
