import { db } from "@/app/db/db";
import { bulkAddressUploads } from "@/app/db/schema/bulk_address_uploads";
import { eq, desc } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { redirect } from "next/navigation";
import Link from "next/link";
import {
  ArrowRightIcon,
  DocumentTextIcon,
  CloudArrowUpIcon,
} from "@heroicons/react/24/outline";

const STATUS_LABELS: Record<string, { label: string; classes: string }> = {
  ready_for_processing: { label: "Ready", classes: "bg-amber-100 text-amber-700" },
  processing: { label: "Processing", classes: "bg-blue-100 text-blue-700" },
  finalising: { label: "Uploading to ARA", classes: "bg-blue-100 text-blue-700" },
  complete: { label: "Complete", classes: "bg-green-100 text-green-700" },
  failed: { label: "Failed", classes: "bg-red-100 text-red-700" },
};

function formatDate(date: Date) {
  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date);
}

export default async function BulkUploadListPage(props: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await props.params;
  const session = await getServerSession(AuthOptions);
  if (!session) redirect("/login");

  const uploads = await db
    .select()
    .from(bulkAddressUploads)
    .where(eq(bulkAddressUploads.portfolioId, slug))
    .orderBy(desc(bulkAddressUploads.createdAt));

  return (
    <div className="max-w-4xl mx-auto px-6 py-10">
      {/* Header */}
      <div className="mb-8">
        <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">
          Portfolio › Bulk Uploads
        </p>
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">
          Batch Uploads
        </h1>
        <p className="text-sm text-gray-500 mt-1">
          Select an upload to continue processing, or start a new import.
        </p>
      </div>

      {uploads.length === 0 ? (
        /* Empty state */
        <div className="flex flex-col items-center justify-center py-24 border-2 border-dashed border-gray-200 rounded-2xl text-center">
          <div className="w-14 h-14 rounded-full bg-gray-100 flex items-center justify-center mb-4">
            <CloudArrowUpIcon className="h-7 w-7 text-gray-400" />
          </div>
          <p className="text-base font-semibold text-gray-700 mb-1">No uploads yet</p>
          <p className="text-sm text-gray-400">
            Use the Bulk Upload button on your portfolio to get started.
          </p>
        </div>
      ) : (
        /* Upload list */
        <div className="space-y-3">
          {/* Column headers */}
          <div className="grid grid-cols-12 px-4 pb-1">
            <span className="col-span-6 text-xs font-semibold text-gray-400 uppercase tracking-wider">
              File
            </span>
            <span className="col-span-3 text-xs font-semibold text-gray-400 uppercase tracking-wider">
              Uploaded
            </span>
            <span className="col-span-2 text-xs font-semibold text-gray-400 uppercase tracking-wider">
              Status
            </span>
            <span className="col-span-1" />
          </div>

          {uploads.map((upload) => {
            const status = STATUS_LABELS[upload.status] ?? {
              label: upload.status,
              classes: "bg-gray-100 text-gray-600",
            };
            return (
              <Link
                key={upload.id}
                href={`/portfolio/${slug}/bulk-upload/${upload.id}`}
                className="grid grid-cols-12 items-center bg-white border border-gray-100 rounded-xl px-4 py-4 hover:border-gray-300 hover:shadow-sm transition-all group"
              >
                {/* Filename */}
                <div className="col-span-6 flex items-center gap-3 min-w-0">
                  <div className="w-9 h-9 rounded-lg bg-gray-50 border border-gray-100 flex items-center justify-center shrink-0">
                    <DocumentTextIcon className="h-5 w-5 text-midblue" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold text-gray-900 truncate">
                      {upload.filename}
                    </p>
                    <p className="text-xs text-gray-400 truncate font-mono">
                      {upload.s3Key.split("/").pop()}
                    </p>
                  </div>
                </div>

                {/* Date */}
                <div className="col-span-3">
                  <p className="text-sm text-gray-500">
                    {formatDate(upload.createdAt)}
                  </p>
                </div>

                {/* Status badge */}
                <div className="col-span-2">
                  <span
                    className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold ${status.classes}`}
                  >
                    <span className="w-1.5 h-1.5 rounded-full bg-current opacity-70" />
                    {status.label}
                  </span>
                </div>

                {/* Arrow */}
                <div className="col-span-1 flex justify-end">
                  <ArrowRightIcon className="h-4 w-4 text-gray-300 group-hover:text-gray-600 transition-colors" />
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
