'use client';

import { useMemo, useState } from 'react';
import type { Post } from 'contentlayer/generated';
import { siteConfig } from '@/lib/config';
import { PostListItem } from './post-list-item';

interface Props {
  posts: Post[];
  pageSize?: number;
}

type SortOrder = 'new' | 'old';

export function PostListWithControls({ posts, pageSize }: Props) {
  const [sortOrder, setSortOrder] = useState<SortOrder>('new');
  const [page, setPage] = useState(1);

  const size = pageSize ?? siteConfig.postsPerPage ?? 5;

  const sortedPosts = useMemo(() => {
    const arr = [...posts];
    arr.sort((a, b) => {
      const aDate = a.published_at
        ? new Date(a.published_at).getTime()
        : 0;
      const bDate = b.published_at
        ? new Date(b.published_at).getTime()
        : 0;
      return sortOrder === 'new' ? bDate - aDate : aDate - bDate;
    });
    return arr;
  }, [posts, sortOrder]);

  const totalPages = Math.max(1, Math.ceil(sortedPosts.length / size));
  const currentPage = Math.min(page, totalPages);
  const start = (currentPage - 1) * size;
  const currentPosts = sortedPosts.slice(start, start + size);

  const handleChangeSort = (order: SortOrder) => {
    setSortOrder(order);
    setPage(1);
  };

  const goToPage = (p: number) => {
    if (p < 1 || p > totalPages) return;
    setPage(p);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-4 text-xs text-slate-500 dark:text-slate-400">
        <div className="flex items-center gap-2">
          <span>排序：</span>
          <button
            type="button"
            onClick={() => handleChangeSort('new')}
            className={`rounded-full px-2 py-0.5 ${
              sortOrder === 'new'
                ? 'bg-blue-600 text-white dark:bg-blue-500'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700'
            }`}
          >
            新到舊
          </button>
          <button
            type="button"
            onClick={() => handleChangeSort('old')}
            className={`rounded-full px-2 py-0.5 ${
              sortOrder === 'old'
                ? 'bg-blue-600 text-white dark:bg-blue-500'
                : 'bg-slate-100 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700'
            }`}
          >
            舊到新
          </button>
        </div>
        <div>
          第 {currentPage} / {totalPages} 頁
        </div>
      </div>

      <ul className="space-y-3">
        {currentPosts.map((post) => (
          <PostListItem key={post._id} post={post} />
        ))}
      </ul>

      {totalPages > 1 && (
        <nav className="flex items-center justify-center gap-3 text-xs text-slate-600 dark:text-slate-300">
          <button
            type="button"
            onClick={() => goToPage(currentPage - 1)}
            disabled={currentPage === 1}
            className="rounded border border-slate-200 px-2 py-1 disabled:opacity-40 dark:border-slate-700"
          >
            上一頁
          </button>
          <div className="flex items-center gap-1">
            {Array.from({ length: totalPages }).map((_, i) => {
              const p = i + 1;
              const isActive = p === currentPage;
              return (
                <button
                  key={p}
                  type="button"
                  onClick={() => goToPage(p)}
                  className={`h-7 w-7 rounded text-xs ${
                    isActive
                      ? 'bg-blue-600 text-white dark:bg-blue-500'
                      : 'hover:bg-slate-100 dark:hover:bg-slate-800'
                  }`}
                >
                  {p}
                </button>
              );
            })}
          </div>
          <button
            type="button"
            onClick={() => goToPage(currentPage + 1)}
            disabled={currentPage === totalPages}
            className="rounded border border-slate-200 px-2 py-1 disabled:opacity-40 dark:border-slate-700"
          >
            下一頁
          </button>
        </nav>
      )}
    </div>
  );
}

