import Link from "next/link";
import { getHistoryIndexData } from "@/lib/delivery";
import { Panel, SectionHeading } from "@/components/ui";

function formatDisplayDate(dateKey: string) {
  const [year, month, day] = dateKey.split("-").map(Number);
  const date = new Date(year, month - 1, day);
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric"
  }).format(date);
}

export default async function HistoryPage() {
  const days = await getHistoryIndexData();

  return (
    <div className="space-y-4">
      <Panel>
        <SectionHeading title="By date" count={days.length} />
        <div className="space-y-1.5">
          {days.length === 0 ? (
            <p className="text-xs text-[var(--muted)]">No history records yet.</p>
          ) : (
            days.map((day) => (
              <Link key={day.dateKey} href={`/history/${day.dateKey}`} className="block rounded-xl border border-stone-200/70 bg-stone-50 px-3 py-2.5">
                <div className="flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-stone-900">{formatDisplayDate(day.dateKey)}</p>
                    <p className="mt-0.5 text-xs text-[var(--muted)]">
                      {day.paidCount} paid, {day.awaitingCount} awaiting, {day.activityCount} changes
                    </p>
                  </div>
                  <svg viewBox="0 0 20 20" fill="none" aria-hidden="true" className="h-4 w-4 shrink-0 text-stone-400">
                    <path d="M7 4.5 12.5 10 7 15.5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
              </Link>
            ))
          )}
        </div>
      </Panel>
    </div>
  );
}
