"use client";
import { useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { formatPostDate, type PostSummary } from "@/lib/blog/types";
export function ManagePosts({ posts }: { posts: PostSummary[] }) {
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(1);
  const [pending, startTransition] = useTransition();
  const router = useRouter();
  const filtered = posts.filter((post) =>
    `${post.title} ${post.author} ${post.slug}`
      .toLowerCase()
      .includes(query.toLowerCase()),
  );
  const current = Math.min(page, Math.max(1, Math.ceil(filtered.length / 15)));
  return (
    <section className="manage-posts" aria-labelledby="managed-articles">
      <div className="manage-section-heading">
        <div>
          <h2 id="managed-articles">Published articles</h2>
          <p>
            {filtered.length} articles. Writing and publishing continue in Wix.
          </p>
        </div>
        <button
          className="manage-button secondary"
          disabled={pending}
          onClick={() => startTransition(() => router.refresh())}
        >
          {pending ? "Refreshing…" : "Refresh view"}
        </button>
      </div>
      <label className="manage-search">
        <span>Find an article</span>
        <input
          type="search"
          value={query}
          onChange={(event) => {
            setQuery(event.target.value);
            setPage(1);
          }}
          placeholder="Search by title, author or URL"
        />
      </label>
      <div className="manage-table-scroll">
        <table>
          <thead>
            <tr>
              <th scope="col">Article</th>
              <th scope="col">Published</th>
              <th scope="col">SEO fields</th>
              <th scope="col">Preview</th>
            </tr>
          </thead>
          <tbody>
            {filtered.slice((current - 1) * 15, current * 15).map((post) => (
              <tr key={post.slug}>
                <td>
                  <strong>{post.title}</strong>
                  <span className="manage-slug">/post/{post.slug}/</span>
                </td>
                <td>
                  <time dateTime={post.publishedAt}>
                    {formatPostDate(post.publishedAt)}
                  </time>
                  <span className="manage-slug">{post.author}</span>
                </td>
                <td>
                  {post.seo.title && post.seo.description
                    ? "Title & description imported"
                    : "Needs review"}
                  {post.seo.noIndex && (
                    <span className="manage-slug">
                      Hidden from search in Wix
                    </span>
                  )}
                </td>
                <td>
                  <Link href={`/post/${encodeURIComponent(post.slug)}/`}>
                    View article
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {!filtered.length && (
        <p className="manage-empty">No articles match your search.</p>
      )}
      {filtered.length > 15 && (
        <div className="manage-pagination">
          <button
            type="button"
            disabled={current === 1}
            onClick={() => setPage(current - 1)}
          >
            Previous
          </button>
          <span>
            Page {current} of {Math.ceil(filtered.length / 15)}
          </span>
          <button
            type="button"
            disabled={current * 15 >= filtered.length}
            onClick={() => setPage(current + 1)}
          >
            Next
          </button>
        </div>
      )}
    </section>
  );
}
