"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { CheckCheck } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/primitives";
import { FilterSelect } from "@/components/ui/data-table";
import { EmptyState } from "@/components/ui/states";
import { NotificationIcon } from "./notification-item";
import { relativeTime, fmtDate } from "@/lib/dates";
import { markNotificationsRead } from "@/lib/actions/settings";
export interface NotificationDto {
  id: string;
  type: string;
  title: string;
  body: string;
  priority: string;
  href: string | null;
  readAt: string | null;
  createdAt: string;
}

const TYPE_LABEL: Record<string, string> = { NEW_RESERVATION: "New reservation", RESERVATION_MODIFIED: "Reservation modified", RESERVATION_CANCELLED: "Cancellation", PRICE_CHANGED: "Price change", UPCOMING_CHECKIN: "Check-in", UPCOMING_CHECKOUT: "Check-out", PAYMENT_DUE: "Payment due", PAYMENT_RECORDED: "Payment", CONTRACT_MISSING: "Contract", CUSTOMER_ID_MISSING: "ID missing", APARTMENT_NEEDS_CLEANING: "Cleaning", CLEANING_COMPLETED: "Cleaning done", MAINTENANCE_ALERT: "Maintenance", NEW_EXPENSE: "Expense", TASK_ASSIGNED: "Task", WORKER_ACTIVITY: "Worker activity", COMMISSION_CREATED: "Commission", COMMISSION_APPROVED: "Commission approved", COMMISSION_PAID: "Commission paid", SECURITY_ALERT: "Security" };

export function NotificationsList({ items }: { items: NotificationDto[] }) {
  const router = useRouter();
  const [tab, setTab] = React.useState<"all" | "unread">("all");
  const [type, setType] = React.useState("");
  const [prio, setPrio] = React.useState("");
  const list = items.filter((n) => (tab === "all" || !n.readAt) && (!type || n.type === type) && (!prio || n.priority === prio));
  const groups = list.reduce<Record<string, NotificationDto[]>>((m, n) => {
    const d = new Date(n.createdAt);
    const today = new Date();
    const key = d.toDateString() === today.toDateString() ? "Today" : d.toDateString() === new Date(today.getTime() - 86_400_000).toDateString() ? "Yesterday" : fmtDate(d, { style: "long" });
    (m[key] = m[key] ?? []).push(n);
    return m;
  }, {});
  async function markAll() {
    await markNotificationsRead("all");
    router.refresh();
  }
  async function markOne(id: string) {
    await markNotificationsRead([id]);
    router.refresh();
  }
  const types = [...new Set(items.map((n) => n.type))];
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-2">
        <Tabs value={tab} onValueChange={(v) => setTab(v as typeof tab)}>
          <TabsList variant="pill" className="h-9">
            <TabsTrigger value="all" className="py-1.5 text-xs" count={items.length}>
              All
            </TabsTrigger>
            <TabsTrigger value="unread" className="py-1.5 text-xs" count={items.filter((n) => !n.readAt).length}>
              Unread
            </TabsTrigger>
          </TabsList>
        </Tabs>
        <FilterSelect value={type} onChange={setType} placeholder="All types" options={types.map((t) => ({ value: t, label: TYPE_LABEL[t] ?? t }))} />
        <FilterSelect value={prio} onChange={setPrio} placeholder="All priorities" options={[{ value: "CRITICAL", label: "Critical" }, { value: "HIGH", label: "High" }, { value: "NORMAL", label: "Normal" }, { value: "LOW", label: "Low" }]} />
        <Button variant="ghost" size="sm" className="ml-auto" onClick={markAll} disabled={!items.some((n) => !n.readAt)}>
          <CheckCheck /> Mark all as read
        </Button>
      </div>
      {list.length === 0 ? (
        <div className="surface">
          <EmptyState title={tab === "unread" ? "You're all caught up" : "No notifications"} description="Reservations, check-ins, payments and alerts will appear here." />
        </div>
      ) : (
        Object.entries(groups).map(([day, ns]) => (
          <section key={day}>
            <h3 className="mb-1.5 px-1 text-2xs font-semibold uppercase tracking-wider text-fg-subtle">{day}</h3>
            <ul className="surface divide-y divide-border">
              {ns.map((n) => (
                <li key={n.id} className={cn(!n.readAt && "bg-primary/[0.04]")}>
                  <Link href={n.href ?? "#"} onClick={() => !n.readAt && markOne(n.id)} className="flex gap-3 px-4 py-3 transition hover:bg-surface-2">
                    <NotificationIcon type={n.type} priority={n.priority} />
                    <span className="min-w-0 flex-1">
                      <span className={cn("block text-sm leading-snug", !n.readAt ? "font-semibold" : "")}>{n.title}</span>
                      <span className="block text-sm text-fg-muted">{n.body}</span>
                      <span className="mt-1 block text-2xs text-fg-subtle">
                        {relativeTime(n.createdAt)} · {TYPE_LABEL[n.type] ?? n.type}
                        {n.priority === "CRITICAL" || n.priority === "HIGH" ? <span className={cn("ml-2 rounded-full px-1.5", n.priority === "CRITICAL" ? "bg-negative-50 text-negative-700" : "bg-warning-50 text-warning-700")}>{n.priority.toLowerCase()}</span> : null}
                      </span>
                    </span>
                    {!n.readAt ? <span className="mt-2 size-2 shrink-0 rounded-full bg-primary" /> : null}
                  </Link>
                </li>
              ))}
            </ul>
          </section>
        ))
      )}
    </div>
  );
}
