import Link from "next/link";
import type { DashboardSummary } from "@/types";
import { LOAD_STATUS_LABELS } from "@/src/modules/loads/load-status";

function formatDate(value: string) {
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleString();
}

export function RecentLoadActivityCard({ items }: { items: DashboardSummary["recentActivity"] }) {
  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-base font-semibold">Recent Load Activity</h3>
        <span className="text-sm text-gray-500">{items.length}</span>
      </div>
      {items.length ? (
        <div className="space-y-3">
          {items.map((item) => (
            <div key={item.id} className="rounded-xl border bg-gray-50 p-3">
              <div className="text-sm font-medium text-gray-900">
                {item.headline ?? `Load moved to ${LOAD_STATUS_LABELS[item.toStatus as keyof typeof LOAD_STATUS_LABELS] ?? item.toStatus}`}
              </div>
              {item.contextLine ? <div className="mt-1 text-xs text-gray-600">{item.contextLine}</div> : null}
              {item.referenceLine ? <div className="mt-1 text-xs text-gray-500">{item.referenceLine}</div> : null}
              <div className="mt-1 text-xs text-gray-500">{formatDate(item.changedAt)}</div>
              <div className="mt-2 flex flex-wrap gap-3">
                <Link href={`/loads/${item.loadId}`} className="text-sm font-medium text-blue-700 hover:underline">
                  Open load
                </Link>
                <Link
                  href={`/cori?source=dispatch&topic=load&question=${encodeURIComponent(`What should I do next after this update: ${item.headline ?? `Load moved to ${LOAD_STATUS_LABELS[item.toStatus as keyof typeof LOAD_STATUS_LABELS] ?? item.toStatus}`}`)}${(item.headline ?? `Load moved to ${LOAD_STATUS_LABELS[item.toStatus as keyof typeof LOAD_STATUS_LABELS] ?? item.toStatus}`) ? `&title=${encodeURIComponent(item.headline ?? `Load moved to ${LOAD_STATUS_LABELS[item.toStatus as keyof typeof LOAD_STATUS_LABELS] ?? item.toStatus}`)}` : ''}${item.contextLine || item.referenceLine ? `&context=${encodeURIComponent([item.contextLine, item.referenceLine].filter(Boolean).join(' · '))}` : ''}`}
                  className="text-sm font-medium text-gray-700 hover:underline"
                >
                  Ask CORI
                </Link>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-sm text-gray-500">No recent status changes.</div>
      )}
    </section>
  );
}
