import { db } from "@/app/db/db";
import { bulkAddressUploads } from "@/app/db/schema/bulk_address_uploads";
import { eq } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  CheckCircleIcon,
  ClockIcon,
  ExclamationCircleIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/outline";
import StartAddressMatchingButton from "./StartAddressMatchingButton";
import OnboardingProgress from "./OnboardingProgress";

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);
}

const STATUS_CONFIG = {
  ready_for_processing: {
    icon: ClockIcon,
    iconBg: "bg-amber-50",
    iconColor: "text-amber-500",
    title: "Awaiting column mapping",
    body: "Map your spreadsheet columns to our internal fields before processing can begin.",
    cta: true,
  },
  mapping_complete: {
    icon: CheckCircleIcon,
    iconBg: "bg-blue-50",
    iconColor: "text-blue-500",
    title: "Mapping complete",
    body: "Column mapping saved. Start onboarding to begin matching your addresses to UPRNs.",
    cta: true,
  },
  processing: {
    icon: ArrowPathIcon,
    iconBg: "bg-blue-50",
    iconColor: "text-blue-500",
    title: "Processing…",
    body: "Your file is currently being processed. This may take a few minutes.",
    cta: false,
  },
  combining: {
    icon: ArrowPathIcon,
    iconBg: "bg-blue-50",
    iconColor: "text-blue-500",
    title: "Combining results…",
    body: "Your matched addresses are being assembled. Almost ready for review.",
    cta: false,
  },
  awaiting_review: {
    icon: ArrowPathIcon,
    iconBg: "bg-blue-50",
    iconColor: "text-blue-500",
    title: "Importing addresses…",
    body: "Matches ready, writing into your portfolio.",
    cta: false,
  },
  finalising: {
    icon: ArrowPathIcon,
    iconBg: "bg-blue-50",
    iconColor: "text-blue-500",
    title: "Uploading to ARA",
    body: "Creating your properties from the matched addresses. This can take a little while for large files.",
    cta: false,
  },
  complete: {
    icon: CheckCircleIcon,
    iconBg: "bg-green-50",
    iconColor: "text-green-500",
    title: "Processing complete",
    body: "All addresses have been imported into your portfolio.",
    cta: false,
  },
  failed: {
    icon: ExclamationCircleIcon,
    iconBg: "bg-red-50",
    iconColor: "text-red-500",
    title: "Processing failed",
    body: "Something went wrong during processing. Contact a Domna representative for assistance.",
    cta: false,
  },
} as const;

export default async function BulkUploadDetailPage(props: {
  params: Promise<{ slug: string; uploadId: string }>;
}) {
  const { slug, uploadId } = await props.params;
  const session = await getServerSession(AuthOptions);
  if (!session) redirect("/login");
  const isDomnaUser = !!session.user?.email?.endsWith("@domna.homes");

  const [upload] = await db
    .select()
    .from(bulkAddressUploads)
    .where(eq(bulkAddressUploads.id, uploadId))
    .limit(1);

  if (!upload) notFound();

  const statusKey = upload.status as keyof typeof STATUS_CONFIG;
  const config = STATUS_CONFIG[statusKey] ?? STATUS_CONFIG.ready_for_processing;
  const Icon = config.icon;

  return (
    <div className="max-w-2xl mx-auto px-6 py-10">
      {/* Back */}
      <Link
        href={`/portfolio/${slug}/bulk-upload`}
        className="inline-flex items-center gap-1.5 text-sm text-gray-400 hover:text-gray-700 transition-colors mb-8"
      >
        <ArrowLeftIcon className="h-4 w-4" />
        Back to uploads
      </Link>

      {/* Header */}
      <div className="mb-8">
        <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">
          Bulk Upload
        </p>
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight mb-1">
          {upload.filename}
        </h1>
        <p className="text-sm text-gray-500">Uploaded {formatDate(upload.createdAt)}</p>
      </div>

      {/* Status card */}
      <div className="bg-white border border-gray-100 rounded-2xl p-6 shadow-sm mb-4">
        <div className="flex items-start gap-4">
          <div className={`w-11 h-11 rounded-xl flex items-center justify-center shrink-0 ${config.iconBg}`}>
            <Icon className={`h-6 w-6 ${config.iconColor}`} />
          </div>
          <div className="flex-1">
            <p className="text-sm font-semibold text-gray-900 mb-1">{config.title}</p>
            <p className="text-sm text-gray-500 leading-relaxed">{config.body}</p>

            {statusKey === "ready_for_processing" && (
              <Link
                href={`/portfolio/${slug}/bulk-upload/${uploadId}/map-columns`}
                className="mt-4 inline-flex items-center gap-2 px-5 py-2 rounded-xl bg-gradient-to-br from-[#14163d] to-[#15173e] text-white text-sm font-bold hover:opacity-90 transition-opacity"
              >
                Map Columns
                <ArrowRightIcon className="h-4 w-4" />
              </Link>
            )}

            {statusKey === "mapping_complete" && (
              <div className="mt-4 flex flex-col gap-3">
                <Link
                  href={`/portfolio/${slug}/bulk-upload/${uploadId}/map-columns`}
                  className="inline-flex items-center gap-1.5 text-sm text-gray-400 hover:text-gray-700 transition-colors"
                >
                  Edit column mapping
                  <ArrowRightIcon className="h-3.5 w-3.5" />
                </Link>
                <StartAddressMatchingButton
                  portfolioId={upload.portfolioId}
                  uploadId={uploadId}
                  filename={upload.filename}
                />
              </div>
            )}

            {(statusKey === "processing" ||
              statusKey === "combining" ||
              statusKey === "awaiting_review" ||
              statusKey === "finalising" ||
              statusKey === "complete" ||
              statusKey === "failed") &&
              upload.taskId && (
                <OnboardingProgress
                  portfolioSlug={slug}
                  portfolioId={upload.portfolioId}
                  uploadId={uploadId}
                  serverStatus={upload.status}
                  isDomnaUser={isDomnaUser}
                />
              )}

            {statusKey === "complete" && (
              <a
                href={`/portfolio/${slug}`}
                className="mt-4 inline-flex items-center gap-2 px-5 py-2 rounded-xl bg-gradient-to-br from-[#14163d] to-[#15173e] text-white text-sm font-bold hover:opacity-90 transition-opacity"
              >
                Open properties
                <ArrowRightIcon className="h-4 w-4" />
              </a>
            )}
          </div>
        </div>
      </div>

    </div>
  );
}
