import Link from "next/link";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { updateNotificationSettings } from "@/lib/actions/notification-settings";
import {
  NOTIFICATION_TYPES,
  NOTIFICATION_TYPE_LABELS,
} from "@/lib/notification-types";

export default async function NotificationSettingsPage() {
  const session = await auth();
  const userId = (session?.user as { id?: string } | undefined)?.id as string;

  const settings = await db.notificationSetting.findMany({
    where: { userId },
  });
  const enabledByType = new Map(settings.map((s) => [s.type, s.enabled]));

  return (
    <div>
      <Link
        href="/notifications"
        className="text-sm text-terracotta hover:underline"
      >
        &larr; Notifications
      </Link>
      <h1 className="mt-4 font-heading text-3xl font-semibold text-terracotta">
        Notification Settings
      </h1>
      <p className="mt-2 text-charcoal/60">
        Choose which notifications you want to receive in-app. These don&apos;t
        affect follow/watch state, just whether they generate a notification.
      </p>

      <form action={updateNotificationSettings} className="mt-8 flex flex-col gap-4">
        {NOTIFICATION_TYPES.map((type) => (
          <label
            key={type}
            className="flex items-center justify-between rounded-lg border border-charcoal/10 bg-warm-white px-4 py-3"
          >
            <span className="text-charcoal">{NOTIFICATION_TYPE_LABELS[type]}</span>
            <input
              type="checkbox"
              name={type}
              defaultChecked={enabledByType.get(type) ?? true}
              className="h-5 w-5 accent-terracotta"
            />
          </label>
        ))}

        <button
          type="submit"
          className="mt-2 w-fit rounded-full bg-terracotta px-6 py-2 font-medium text-white hover:bg-terracotta/90"
        >
          Save
        </button>
      </form>
    </div>
  );
}
