import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import {
  getLandlordOverrides,
  type OverrideRow,
  type LandlordOverrideCategory,
} from "@/lib/landlordOverrides/server";
import { CLASSIFIER_FIELDS } from "@/lib/bulkUpload/columnFields";

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

  const results = await getLandlordOverrides(slug);
  const total = Object.values(results).reduce((n, rows) => n + rows.length, 0);

  return (
    <div className="max-w-4xl mx-auto px-6 py-10">
      <div className="mb-8">
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight mb-1">
          Landlord overrides
        </h1>
        <p className="text-sm text-gray-500 max-w-lg">
          Property facts classified from your bulk-upload descriptions. Read-only
          — editing comes later.
        </p>
      </div>

      {total === 0 ? (
        <div className="bg-white border border-gray-100 rounded-2xl px-6 py-12 text-center text-sm text-gray-400 shadow-sm">
          No classified values yet. They appear here once a bulk upload with
          landlord-description columns has been processed.
        </div>
      ) : (
        CLASSIFIER_FIELDS.map((field) => (
          <OverrideSection
            key={field.value}
            title={field.label}
            rows={results[field.value as LandlordOverrideCategory]}
          />
        ))
      )}
    </div>
  );
}

function OverrideSection({ title, rows }: { title: string; rows: OverrideRow[] }) {
  return (
    <div className="bg-white border border-gray-100 rounded-2xl overflow-hidden shadow-sm mb-6">
      <div className="flex items-center justify-between px-6 py-3 bg-gray-50 border-b border-gray-100">
        <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
          {title}
        </p>
        <span className="text-xs text-gray-400">
          {rows.length} {rows.length === 1 ? "value" : "values"}
        </span>
      </div>
      {rows.length === 0 ? (
        <div className="px-6 py-8 text-center text-sm text-gray-400">
          No values for this category.
        </div>
      ) : (
        <div className="divide-y divide-gray-50">
          {rows.map((row, i) => (
            <div key={i} className="grid grid-cols-12 items-center px-6 py-3 gap-2">
              <p
                className="col-span-6 text-sm text-gray-700 truncate"
                title={row.description}
              >
                {row.description}
              </p>
              <p className="col-span-4 text-sm font-semibold text-gray-900">
                {row.value}
              </p>
              <div className="col-span-2 flex justify-end">
                <SourceBadge source={row.source} />
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Provenance of a resolved override value. os_places is the deterministic OS
// Places classification-code mapping (ADR-0007); user is a landlord correction;
// classifier is the ML default.
const SOURCE_BADGES: Record<string, { label: string; className: string }> = {
  user: { label: "user", className: "bg-emerald-50 text-emerald-700" },
  classifier: { label: "classifier", className: "bg-indigo-50 text-indigo-700" },
  os_places: { label: "OS Places", className: "bg-sky-50 text-sky-700" },
};

function SourceBadge({ source }: { source: string }) {
  const badge = SOURCE_BADGES[source] ?? {
    label: source,
    className: "bg-gray-100 text-gray-600",
  };
  return (
    <span
      className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold ${badge.className}`}
    >
      {badge.label}
    </span>
  );
}
