"use client";
import { useState } from "react";
import Link from "next/link";
import type { CmsPost } from "@/lib/cms/model";
import { formatPostDate } from "@/lib/blog/types";
export function AdminPosts({ posts }: { posts: CmsPost[] }) {
  const [query, setQuery] = useState(""),
    [status, setStatus] = useState("all"),
    [page, setPage] = useState(1);
  const filtered = posts.filter(
    (post) =>
      (status === "all" ||
        post.status === status ||
        (status === "changes" && post.hasDraft)) &&
      `${post.title} ${post.author} ${post.slug}`
        .toLowerCase()
        .includes(query.toLowerCase()),
  );
  const current = Math.min(page, Math.max(1, Math.ceil(filtered.length / 15)));
  return (
    <>
      <div className="admin-page-heading">
        <div>
          <h1>Blog posts</h1>
          <p>All your stories, from first draft to published article.</p>
        </div>
        <Link className="admin-button" href="/admin/posts/new/">
          Create a post
        </Link>
      </div>
      <div className="admin-card">
        <div className="admin-tabs">
          {[
            "all",
            "published",
            "draft",
            "scheduled",
            "changes",
            "archived",
          ].map((value) => (
            <button
              key={value}
              className={status === value ? "selected" : ""}
              onClick={() => {
                setStatus(value);
                setPage(1);
              }}
            >
              {value === "changes" ? "Working copies" : value}
            </button>
          ))}
        </div>
        <label className="admin-search">
          Search articles
          <input
            type="search"
            value={query}
            placeholder="Search by title, author or URL"
            onChange={(event) => {
              setQuery(event.target.value);
              setPage(1);
            }}
          />
        </label>
        <p className="admin-small">{filtered.length} articles</p>
        <div className="admin-table-scroll">
          <table className="admin-table">
            <thead>
              <tr>
                <th>Article</th>
                <th>Status</th>
                <th>Published</th>
                <th>Manage</th>
              </tr>
            </thead>
            <tbody>
              {filtered.slice((current - 1) * 15, current * 15).map((post) => (
                <tr key={post.id}>
                  <td>
                    <Link href={`/admin/posts/${post.id}/`}>
                      <strong>{post.title}</strong>
                    </Link>
                    <small>/post/{post.slug}/</small>
                  </td>
                  <td>
                    <span className={"admin-status " + post.status}>
                      {post.status}
                    </span>
                    {post.hasDraft && <small>Unpublished changes</small>}
                  </td>
                  <td>
                    {post.publishedAt
                      ? formatPostDate(post.publishedAt)
                      : "Not published"}
                  </td>
                  <td>
                    <Link href={`/admin/posts/${post.id}/`}>Edit post</Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {!filtered.length && (
          <p className="admin-empty">No articles match this filter.</p>
        )}
        <div className="admin-pagination">
          <button disabled={current === 1} onClick={() => setPage(current - 1)}>
            Previous
          </button>
          <span>
            Page {current} of {Math.max(1, Math.ceil(filtered.length / 15))}
          </span>
          <button
            disabled={current * 15 >= filtered.length}
            onClick={() => setPage(current + 1)}
          >
            Next
          </button>
        </div>
      </div>
    </>
  );
}
