import { db } from "@/lib/db";
import { FLAG_REASON_LABELS } from "@/lib/flag-reasons";
import { RejectLabelForm } from "../labels/RejectLabelForm";
import { FlagActions } from "./FlagActions";

export default async function AdminFlagsPage() {
  const flags = await db.labelFlag.findMany({
    where: { status: "open" },
    orderBy: { createdAt: "asc" },
    include: {
      reporter: true,
      label: {
        include: {
          blend: { include: { brand: true } },
          uploader: true,
          versions: { where: { isCurrent: true }, take: 1 },
        },
      },
    },
  });

  return (
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        Flags
      </h1>
      <p className="mt-2 text-charcoal/60">
        Community-reported labels awaiting review.
      </p>

      {flags.length === 0 ? (
        <p className="mt-8 text-charcoal/60">No open flags.</p>
      ) : (
        <ul className="mt-8 flex flex-col gap-4">
          {flags.map((flag) => {
            const currentVersion = flag.label.versions[0];
            return (
              <li
                key={flag.id}
                className="flex flex-col gap-3 rounded-lg border border-charcoal/10 bg-warm-white p-4 sm:flex-row sm:items-start"
              >
                {currentVersion && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={currentVersion.fileUrl}
                    alt=""
                    className="h-16 w-16 shrink-0 rounded-full border border-charcoal/10 object-cover"
                  />
                )}
                <div className="flex-1">
                  <p className="font-medium text-charcoal">
                    {flag.label.blend.brand.name} - {flag.label.blend.name}
                  </p>
                  <p className="text-sm text-charcoal/60">
                    uploaded by {flag.label.uploader.username}
                  </p>
                  <p className="mt-2 text-sm text-charcoal">
                    Reported by {flag.reporter.username}:{" "}
                    <strong>{FLAG_REASON_LABELS[flag.reason]}</strong>
                    {flag.note ? ` (${flag.note})` : ""}
                  </p>
                </div>
                <div className="flex flex-col gap-2 sm:w-72">
                  {flag.label.status !== "rejected" && (
                    <RejectLabelForm labelId={flag.label.id} />
                  )}
                  <FlagActions
                    flagId={flag.id}
                    uploaderId={flag.label.uploaderId}
                    uploaderUsername={flag.label.uploader.username}
                  />
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
