"use client";

import {
  Bell,
  Calendar,
  ClipboardList,
  Table2,
  UserCheck,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import type { NotificationType, PlatformNotification } from "@/data/platform-mock";
import { useOpsVenueId } from "@/stores/operations/operations-store";
import { useOpsNotificationActions, useVenueNotifications } from "@/stores/platform/use-platform-selectors";
import { cn } from "@/lib/utils";

import { OperationsHeader } from "../_components/operations-header";

const ICONS: Record<NotificationType, typeof Bell> = {
  guest_arrived: UserCheck,
  table_freed: Table2,
  reservation_updated: ClipboardList,
  waiting_assigned: Calendar,
  arrival_reminder: Bell,
  booking_received: ClipboardList,
};

export default function NotificationsPage() {
  const venueId = useOpsVenueId();
  const notifications = useVenueNotifications(venueId);
  const { markNotificationRead: markRead, markAllRead } = useOpsNotificationActions();

  const unread = notifications.filter((n) => !n.read).length;

  return (
    <>
      <OperationsHeader title="Notifications" subtitle="Operational alerts for this service period" />
      <div className="flex-1 overflow-auto p-4 md:p-6">
        {unread > 0 && (
          <div className="mb-4 flex justify-end">
            <Button variant="outline" className="h-10" onClick={markAllRead}>
              Mark all read
            </Button>
          </div>
        )}
        <div className="space-y-2">
          {notifications.map((n) => (
            <NotificationRow key={n.id} notification={n} onRead={() => markRead(n.id)} />
          ))}
        </div>
      </div>
    </>
  );
}

function NotificationRow({
  notification: n,
  onRead,
}: {
  notification: PlatformNotification;
  onRead: () => void;
}) {
  const Icon = ICONS[n.type];
  return (
    <Card
      className={cn(
        "cursor-pointer border-0 shadow-sm transition-colors",
        !n.read && "ring-1 ring-amber-400/40 bg-amber-50/30 dark:bg-amber-950/10",
      )}
      onClick={onRead}
    >
      <CardContent className="flex gap-4 p-4">
        <div
          className={cn(
            "flex size-11 shrink-0 items-center justify-center rounded-lg",
            n.read ? "bg-muted" : "bg-amber-500/15 text-amber-700",
          )}
        >
          <Icon className="size-5" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-start justify-between gap-2">
            <p className={cn("font-semibold", !n.read && "text-foreground")}>{n.title}</p>
            <span className="shrink-0 text-xs text-muted-foreground">{n.time}</span>
          </div>
          <p className="mt-0.5 text-sm text-muted-foreground">{n.message}</p>
        </div>
        {!n.read && <span className="size-2 shrink-0 self-center rounded-full bg-amber-500" />}
      </CardContent>
    </Card>
  );
}
