import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { Bell, CheckCircle2, MailWarning } from "lucide-react";

import NotificationActions from "@/app/components/notifications/NotificationActions";
import { AUTH_COOKIE_NAME } from "@/lib/auth/constants";
import {
  hasPermission,
  loadAuthorizationForUser,
} from "@/lib/auth/authorization";
import { hashSessionToken } from "@/lib/auth/session-token";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function requireStaffNotifications() {
  const cookieStore = await cookies();
  const token = cookieStore.get(AUTH_COOKIE_NAME)?.value?.trim();

  if (!token) {
    redirect("/admin/login");
  }

  const session = await prisma.authSession.findUnique({
    where: {
      tokenHash: hashSessionToken(token),
    },
    select: {
      userId: true,
      expiresAt: true,
      user: {
        select: {
          status: true,
        },
      },
    },
  });

  if (
    !session ||
    session.expiresAt <= new Date() ||
    session.user.status !== "ACTIVE"
  ) {
    redirect("/admin/login");
  }

  const authorization = await loadAuthorizationForUser(session.userId);

  if (
    !authorization ||
    authorization.status !== "ACTIVE" ||
    authorization.roles.length === 0
  ) {
    redirect("/admin/login");
  }

  if (authorization.roles.includes("SUPER_ADMIN")) {
    redirect("/admin/notifications");
  }

  if (!hasPermission(authorization, "NOTIFICATION_VIEW")) {
    redirect("/staff");
  }

  return authorization;
}

function formatDate(value: Date) {
  return value.toLocaleString("en-IN", {
    timeZone: "Asia/Kolkata",
    dateStyle: "medium",
    timeStyle: "short",
  });
}

export default async function StaffNotificationsPage() {
  const authorization = await requireStaffNotifications();

  const notifications = await prisma.notification.findMany({
    where: {
      userId: authorization.userId,
    },
    orderBy: {
      createdAt: "desc",
    },
    take: 100,
    select: {
      id: true,
      title: true,
      message: true,
      channel: true,
      status: true,
      eventType: true,
      entityType: true,
      entityId: true,
      sentAt: true,
      readAt: true,
      createdAt: true,
    },
  });

  const unreadCount = notifications.filter(
    (notification) => !notification.readAt,
  ).length;

  const failedCount = notifications.filter(
    (notification) => notification.status === "FAILED",
  ).length;

  return (
    <main className="mx-auto w-full max-w-6xl p-5 md:p-8">
      <div className="mb-6">
        <p className="text-xs font-extrabold uppercase tracking-[0.18em] text-blue-700">
          STAFF COMMUNICATION CENTER
        </p>
        <h1 className="mt-1 text-2xl font-extrabold text-slate-900">
          My Notifications
        </h1>
        <p className="mt-2 text-sm text-slate-500">
          Notifications assigned to your CRM account.
        </p>
      </div>

      <div className="mb-6 grid gap-4 sm:grid-cols-3">
        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center gap-3">
            <Bell className="text-blue-600" size={20} />
            <div>
              <p className="text-xs font-bold uppercase text-slate-400">
                Latest
              </p>
              <p className="text-2xl font-extrabold text-slate-900">
                {notifications.length}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center gap-3">
            <CheckCircle2 className="text-emerald-600" size={20} />
            <div>
              <p className="text-xs font-bold uppercase text-slate-400">
                Unread
              </p>
              <p className="text-2xl font-extrabold text-slate-900">
                {unreadCount}
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center gap-3">
            <MailWarning className="text-amber-600" size={20} />
            <div>
              <p className="text-xs font-bold uppercase text-slate-400">
                Failed
              </p>
              <p className="text-2xl font-extrabold text-slate-900">
                {failedCount}
              </p>
            </div>
          </div>
        </div>
      </div>

      <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
        <div className="border-b border-slate-100 px-5 py-4 md:px-6">
          <h2 className="font-extrabold text-slate-900">
            Notification History
          </h2>
          <p className="mt-1 text-xs text-slate-400">
            Showing up to your latest 100 notifications.
          </p>
        </div>

        {notifications.length === 0 ? (
          <div className="px-6 py-14 text-center text-sm text-slate-400">
            No notifications yet.
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {notifications.map((notification) => {
              const canRetry =
                notification.status === "FAILED" &&
                (
                  notification.eventType === "LEAD_ASSIGNED" ||
                  notification.eventType === "LEAD_REASSIGNED"
                );

              return (
                <article
                  key={notification.id}
                  className={
                    notification.readAt
                      ? "px-5 py-5 md:px-6"
                      : "bg-blue-50/30 px-5 py-5 md:px-6"
                  }
                >
                  <div className="flex items-start gap-4">
                    <div className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 text-slate-600">
                      <Bell size={18} />
                    </div>

                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-2">
                        <h3 className="font-extrabold text-slate-900">
                          {notification.title}
                        </h3>

                        <span className="rounded-full bg-slate-100 px-2 py-1 text-[10px] font-bold uppercase text-slate-600">
                          {notification.status}
                        </span>

                        {!notification.readAt && (
                          <span className="rounded-full bg-blue-100 px-2 py-1 text-[10px] font-bold uppercase text-blue-700">
                            NEW
                          </span>
                        )}
                      </div>

                      <p className="mt-2 text-sm leading-6 text-slate-600">
                        {notification.message}
                      </p>

                      <div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-[11px] font-semibold text-slate-400">
                        <span>{formatDate(notification.createdAt)}</span>
                        <span>{notification.channel}</span>
                        <span>{notification.eventType}</span>
                        {notification.entityType && (
                          <span>{notification.entityType}</span>
                        )}
                      </div>

                      <NotificationActions
                        notificationId={notification.id}
                        unread={!notification.readAt}
                        canRetry={canRetry}
                      />
                    </div>
                  </div>
                </article>
              );
            })}
          </div>
        )}
      </section>
    </main>
  );
}
