import {
  REJECTION_REASONS,
  REJECTION_REASON_LABELS,
} from "@/lib/rejection-reasons";
import { getRejectionMessage } from "@/lib/rejection-message";
import { db } from "@/lib/db";
import { RejectionMessagesForm } from "./RejectionMessagesForm";
import { SiteSettingsForm } from "./SiteSettingsForm";
import { AdminOnlyGate } from "../AdminOnlyGate";

const SITE_SETTING_KEYS = [
  "contributor_upload_threshold",
  "thumbs_down_flag_threshold",
  "label_min_dimension",
  "label_max_dimension",
  "sheet_builder_avery_wide",
  "sheet_builder_avery_regular",
] as const;

const SITE_SETTING_LABELS: Record<(typeof SITE_SETTING_KEYS)[number], string> = {
  contributor_upload_threshold: "Uploads required for contributor status",
  thumbs_down_flag_threshold: "Thumbs down before auto-flag to moderation",
  label_min_dimension: "Minimum label upload dimension (px)",
  label_max_dimension: "Maximum label upload dimension (px)",
  sheet_builder_avery_wide: "Wide mouth Avery SKU",
  sheet_builder_avery_regular: "Regular mouth Avery SKU",
};

export default async function AdminSettingsPage() {
  const messages = await Promise.all(
    REJECTION_REASONS.map(async (reason) => ({
      reason,
      label: REJECTION_REASON_LABELS[reason],
      message: await getRejectionMessage(reason),
    })),
  );

  const settingRows = await db.setting.findMany({
    where: { key: { in: [...SITE_SETTING_KEYS] } },
  });
  const settingValues = Object.fromEntries(
    settingRows.map((s) => [s.key, s.value]),
  );
  const siteSettings = SITE_SETTING_KEYS.map((key) => ({
    key,
    label: SITE_SETTING_LABELS[key],
    value: settingValues[key] ?? "",
  }));

  return (
    <AdminOnlyGate>
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        Settings
      </h1>
      <p className="mt-2 text-charcoal/60">
        Site-wide thresholds and messaging shown to users.
      </p>

      <div className="mt-8">
        <h2 className="font-heading text-xl font-semibold text-charcoal">
          Site thresholds
        </h2>
        <p className="mt-1 text-sm text-charcoal/60">
          Numeric and configuration values used across the site.
        </p>
        <div className="mt-4">
          <SiteSettingsForm settings={siteSettings} />
        </div>
      </div>

      <div className="mt-10">
        <h2 className="font-heading text-xl font-semibold text-charcoal">
          Rejection messages
        </h2>
        <p className="mt-1 text-sm text-charcoal/60">
          Shown to uploaders when a label is rejected for this reason. The
          admin can also add a note specific to a single rejection.
        </p>
        <div className="mt-4">
          <RejectionMessagesForm messages={messages} />
        </div>
      </div>
    </div>
    </AdminOnlyGate>
  );
}
