"use client";

import { useMemo, useState } from "react";
import { Bell, ArrowDownLeft, ArrowUpRight, CheckCircle2, AlertCircle, Info } from "lucide-react";
import { Container } from "@/components/common/Container";
import { Card } from "@/components/common/Card";
import { useAgentNotifications } from "@/hooks/queries/useAgentNotifications";
import { useAgentNotificationState, notifKey } from "@/hooks/useAgentNotificationState";
import { Pagination } from "@/components/app/Pagination";
import { useTranslation } from "@/hooks/useTranslation";

type Filter = "all" | "unread" | "read";

function getNotificationStyles(message: string) {
  const m = message.toLowerCase();
  if (m.includes("money in"))
    return { icon: ArrowDownLeft, colorClass: "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400", dotClass: "bg-emerald-500" };
  if (m.includes("money out") || m.includes("send remittance"))
    return { icon: ArrowUpRight, colorClass: "bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400", dotClass: "bg-brand-500" };
  if (m.includes("success"))
    return { icon: CheckCircle2, colorClass: "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400", dotClass: "bg-emerald-500" };
  if (m.includes("fail") || m.includes("error") || m.includes("cancel"))
    return { icon: AlertCircle, colorClass: "bg-rose-50 text-rose-600 dark:bg-rose-500/10 dark:text-rose-400", dotClass: "bg-rose-500" };
  return { icon: Info, colorClass: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400", dotClass: "bg-slate-400" };
}

const PAGE_SIZE = 10;

export default function NotificationsPage() {
  const { t } = useTranslation();
  const { data, isLoading, isError } = useAgentNotifications();
  const { markRead, markAllRead, isRead } = useAgentNotificationState();

  const [filter, setFilter] = useState<Filter>("unread");
  const [page, setPage] = useState(1);

  const allNotifs = useMemo(() => data?.notifications ?? [], [data?.notifications]);

  const unreadCount = useMemo(
    () => allNotifs.filter((n) => !isRead(notifKey(n.message))).length,
    [allNotifs, isRead]
  );

  const filtered = useMemo(() => {
    if (filter === "unread") return allNotifs.filter((n) => !isRead(notifKey(n.message)));
    if (filter === "read")   return allNotifs.filter((n) =>  isRead(notifKey(n.message)));
    return allNotifs;
  }, [allNotifs, filter, isRead]);

  const pageCount  = Math.ceil(filtered.length / PAGE_SIZE);
  const safePage   = Math.min(page, pageCount || 1);
  const pageStart  = (safePage - 1) * PAGE_SIZE;
  const pagedNotifs = filtered.slice(pageStart, pageStart + PAGE_SIZE);

  function handleFilterChange(f: Filter) {
    setFilter(f);
    setPage(1);
  }

  const TABS: { key: Filter; label: string; count?: number }[] = [
    { key: "all",    label: t("agent.notifications.tabAll"),    count: allNotifs.length },
    { key: "unread", label: t("agent.notifications.tabUnread"), count: unreadCount },
    { key: "read",   label: t("agent.notifications.tabRead"),   count: allNotifs.length - unreadCount },
  ];

  return (
    <Container className="max-w-full space-y-6 lg:space-y-8">
      {/* Page Header */}
      <header className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-4">
          <div>
            <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">
              {t("agent.notifications.title")}
            </h1>
            <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
              {t("agent.notifications.subtitle")}
            </p>
          </div>
        </div>

        {allNotifs.length > 0 && unreadCount > 0 && (
          <button
            onClick={() => markAllRead(allNotifs.map((n) => notifKey(n.message)))}
            className="inline-flex h-9 items-center justify-center rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-inset ring-slate-200 transition hover:bg-slate-50 dark:bg-slate-900 dark:text-slate-200 dark:ring-slate-800 dark:hover:bg-slate-800"
          >
            {t("agent.notifications.markAllRead")}
          </button>
        )}
      </header>

      <Card className="overflow-hidden">
        {/* Filter tabs */}
        <div className="flex items-center gap-1 px-6 pt-5 sm:px-7">
          {TABS.map((tab) => {
            const active = filter === tab.key;
            return (
              <button
                key={tab.key}
                onClick={() => handleFilterChange(tab.key)}
                className={`inline-flex items-center gap-2 rounded-lg px-3.5 py-2 text-sm font-semibold transition-colors ${
                  active
                    ? "bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400"
                    : "text-slate-500 hover:bg-slate-100 hover:text-slate-700 dark:text-slate-400 dark:hover:bg-slate-800/60 dark:hover:text-slate-200"
                }`}
              >
                {tab.label}
                {tab.count !== undefined && tab.count > 0 && (
                  <span
                    className={`inline-flex h-5 min-w-[20px] items-center justify-center rounded-full px-1.5 text-xs font-bold ${
                      active
                        ? "bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
                        : "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400"
                    }`}
                  >
                    {tab.count}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        {/* Separator */}
        <div className="mt-4 border-b border-slate-100 dark:border-slate-800/80 sm:mt-5" />

        {/* Rows */}
        <div>
          {isLoading ? (
            Array.from({ length: 5 }).map((_, i) => (
              <div
                key={i}
                className={`flex gap-4 px-6 py-4 sm:px-7 ${i % 2 !== 0 ? "bg-slate-50/60 dark:bg-slate-800/20" : ""}`}
              >
                <div className="h-10 w-10 shrink-0 animate-pulse rounded-full bg-slate-200 dark:bg-slate-800" />
                <div className="flex-1 space-y-2 py-1">
                  <div className="h-4 w-3/4 animate-pulse rounded bg-slate-200 dark:bg-slate-800" />
                  <div className="h-3 w-1/4 animate-pulse rounded bg-slate-200 dark:bg-slate-800" />
                </div>
              </div>
            ))
          ) : isError ? (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <AlertCircle className="mb-4 h-12 w-12 text-rose-500" />
              <h3 className="text-base font-bold text-slate-900 dark:text-white">{t("agent.notifications.failedToLoad")}</h3>
              <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t("agent.notifications.failedSubtitle")}</p>
            </div>
          ) : !filtered.length ? (
            <div className="flex flex-col items-center justify-center py-24 text-center">
              <div className="mb-6 grid h-20 w-20 place-items-center rounded-full bg-slate-50 dark:bg-slate-800/50">
                <Bell className="h-10 w-10 text-slate-300 dark:text-slate-600" />
              </div>
              <h3 className="text-lg font-bold text-slate-900 dark:text-white">
                {filter === "unread" ? t("agent.notifications.noUnread") : filter === "read" ? t("agent.notifications.noRead") : t("agent.notifications.noNotifications")}
              </h3>
              <p className="mt-2 text-sm text-slate-500 dark:text-slate-400">
                {filter !== "all" ? t("agent.notifications.tryFilter") : t("agent.notifications.willAppearHere")}
              </p>
            </div>
          ) : (
            pagedNotifs.map((notif, i) => {
              const date    = new Date(notif.created_at);
              const styles  = getNotificationStyles(notif.message);
              const Icon    = styles.icon;
              const read    = isRead(notifKey(notif.message));
              const striped = i % 2 !== 0;

              return (
                <button
                  key={notif.id}
                  onClick={() => markRead(notifKey(notif.message))}
                  className={`flex w-full items-start gap-4 px-6 py-4 text-left transition-colors sm:px-7 ${
                    striped
                      ? "bg-slate-50/60 hover:bg-brand-50/80 dark:bg-slate-800/20 dark:hover:bg-brand-500/10"
                      : "hover:bg-brand-50/80 dark:hover:bg-brand-500/10"
                  }`}
                >
                  {/* Icon */}
                  <div className={`relative flex h-10 w-10 shrink-0 items-center justify-center rounded-full ${styles.colorClass}`}>
                    <Icon className="h-4.5 w-4.5" />
                    {!read && (
                      <div className={`absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-white dark:border-slate-900 ${styles.dotClass}`} />
                    )}
                  </div>

                  {/* Content */}
                  <div className="min-w-0 flex-1">
                    <p className={`text-sm leading-relaxed ${read ? "font-normal text-slate-500 dark:text-slate-400" : "font-semibold text-slate-800 dark:text-slate-200"}`}>
                      {notif.message}
                    </p>
                    <p className="mt-1 flex items-center gap-2 text-xs font-medium text-slate-400 dark:text-slate-500">
                      <span>{new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric" }).format(date)}</span>
                      <span className="h-1 w-1 rounded-full bg-slate-300 dark:bg-slate-700" />
                      <span dir="ltr">{new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "numeric" }).format(date)}</span>
                    </p>
                  </div>

                  {/* Read/unread pill */}
                  {!read && (
                    <span className="mt-0.5 shrink-0 self-start rounded-full bg-brand-500/10 px-2 py-0.5 text-2xs font-bold uppercase tracking-wide text-brand-600 dark:text-brand-400">
                      {t("agent.notifications.newBadge")}
                    </span>
                  )}
                </button>
              );
            })
          )}
        </div>

        {/* Pagination footer */}
        {filtered.length > PAGE_SIZE && (
          <div className="flex flex-col items-center justify-between gap-4 border-t border-slate-100/80 px-6 py-6 dark:border-white/5 sm:flex-row sm:px-7 sm:py-7">
            <p className="text-xs font-medium text-slate-400">
              {t("agent.notifications.showing")
                .replace("{start}", String(pageStart + 1))
                .replace("{end}", String(Math.min(pageStart + PAGE_SIZE, filtered.length)))
                .replace("{total}", String(filtered.length))}
            </p>
            <Pagination page={safePage} pageCount={pageCount} onPageChange={setPage} />
          </div>
        )}
      </Card>
    </Container>
  );
}
