"use client";

import { useState } from "react";
import Link from "next/link";
import {
  Activity,
  Bell,
  CheckCheck,
  CreditCard,
  Pill,
  Settings,
  UserPlus,
} from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  DEMO_ADMIN_NOTIFICATIONS,
  type AdminNotification,
  type AdminNotificationType,
} from "@/data/admin-notifications";
import { cn } from "@/lib/utils";

const TYPE_CONFIG: Record<
  AdminNotificationType,
  { icon: typeof Bell; label: string; color: string }
> = {
  glp1_review: { icon: Pill, label: "GLP-1", color: "bg-amber-100 text-amber-700" },
  new_user: { icon: UserPlus, label: "User", color: "bg-blue-100 text-blue-700" },
  payment: { icon: CreditCard, label: "Payment", color: "bg-emerald-100 text-emerald-700" },
  lead: { icon: Activity, label: "Lead", color: "bg-violet-100 text-violet-700" },
  system: { icon: Settings, label: "System", color: "bg-gray-100 text-gray-700" },
};

function formatTime(iso: string) {
  const d = new Date(iso);
  const now = new Date("2026-05-22T12:00:00Z");
  const diffMs = now.getTime() - d.getTime();
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  if (diffHours < 1) return "Just now";
  if (diffHours < 24) return `${diffHours}h ago`;
  const diffDays = Math.floor(diffHours / 24);
  if (diffDays < 7) return `${diffDays}d ago`;
  return d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
}

export default function AdminNotificationsPage() {
  const [notifications, setNotifications] = useState<AdminNotification[]>(
    DEMO_ADMIN_NOTIFICATIONS,
  );
  const [filter, setFilter] = useState<"all" | "unread">("all");

  const unreadCount = notifications.filter((n) => !n.read).length;
  const displayed =
    filter === "unread" ? notifications.filter((n) => !n.read) : notifications;

  const markAllRead = () => {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    toast.success("All notifications marked as read");
  };

  const markRead = (id: string) => {
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, read: true } : n)),
    );
  };

  return (
    <div className="space-y-6 p-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Notifications</h1>
          <p className="text-sm text-gray-500 mt-1">
            System alerts, GLP-1 reviews, payments, and lead activity.
          </p>
        </div>
        {unreadCount > 0 && (
          <Button
            variant="outline"
            size="sm"
            onClick={markAllRead}
            className="shrink-0"
          >
            <CheckCheck className="h-4 w-4 mr-1.5" />
            Mark all as read
          </Button>
        )}
      </div>

      {/* Summary */}
      <div className="grid gap-3 sm:grid-cols-3">
        <Card>
          <CardContent className="pt-5 pb-4">
            <p className="text-2xl font-bold text-gray-900">{notifications.length}</p>
            <p className="text-xs text-gray-500 mt-0.5">Total notifications</p>
          </CardContent>
        </Card>
        <Card className="border-amber-200 bg-amber-50/50">
          <CardContent className="pt-5 pb-4">
            <p className="text-2xl font-bold text-amber-700">{unreadCount}</p>
            <p className="text-xs text-amber-700/80 mt-0.5">Unread</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5 pb-4">
            <p className="text-2xl font-bold text-gray-900">
              {notifications.filter((n) => n.type === "glp1_review" && !n.read).length}
            </p>
            <p className="text-xs text-gray-500 mt-0.5">GLP-1 pending action</p>
          </CardContent>
        </Card>
      </div>

      {/* Filter tabs */}
      <div className="flex gap-2">
        <Button
          size="sm"
          variant={filter === "all" ? "default" : "outline"}
          className={cn(filter === "all" && "bg-teal-600 hover:bg-teal-700")}
          onClick={() => setFilter("all")}
        >
          All ({notifications.length})
        </Button>
        <Button
          size="sm"
          variant={filter === "unread" ? "default" : "outline"}
          className={cn(filter === "unread" && "bg-teal-600 hover:bg-teal-700")}
          onClick={() => setFilter("unread")}
        >
          Unread ({unreadCount})
        </Button>
      </div>

      {/* Notification list */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-semibold flex items-center gap-2">
            <Bell className="h-4 w-4 text-teal-600" />
            Activity feed
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {displayed.length === 0 ? (
            <div className="px-6 py-12 text-center text-sm text-gray-500">
              No {filter === "unread" ? "unread " : ""}notifications.
            </div>
          ) : (
            <ul className="divide-y divide-gray-100">
              {displayed.map((notif) => {
                const config = TYPE_CONFIG[notif.type];
                const Icon = config.icon;
                return (
                  <li
                    key={notif.id}
                    className={cn(
                      "flex gap-4 px-6 py-4 transition-colors hover:bg-gray-50/80",
                      !notif.read && "bg-teal-50/30",
                    )}
                  >
                    <div
                      className={cn(
                        "flex h-10 w-10 shrink-0 items-center justify-center rounded-full",
                        config.color,
                      )}
                    >
                      <Icon className="h-4 w-4" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-start justify-between gap-2">
                        <p
                          className={cn(
                            "text-sm font-semibold text-gray-900",
                            !notif.read && "text-teal-900",
                          )}
                        >
                          {notif.title}
                        </p>
                        <span className="shrink-0 text-xs text-gray-400">
                          {formatTime(notif.createdAt)}
                        </span>
                      </div>
                      <p className="text-sm text-gray-500 mt-0.5 line-clamp-2">
                        {notif.message}
                      </p>
                      <div className="flex items-center gap-2 mt-2">
                        <Badge variant="outline" className="text-xs capitalize">
                          {config.label}
                        </Badge>
                        {!notif.read && (
                          <span className="h-2 w-2 rounded-full bg-teal-500" />
                        )}
                        {notif.href && (
                          <Link
                            href={notif.href}
                            className="text-xs font-medium text-teal-600 hover:text-teal-700"
                            onClick={() => markRead(notif.id)}
                          >
                            View details →
                          </Link>
                        )}
                        {!notif.read && (
                          <button
                            type="button"
                            onClick={() => {
                              markRead(notif.id);
                              toast.info("Marked as read");
                            }}
                            className="text-xs text-gray-400 hover:text-gray-600 ml-auto"
                          >
                            Mark read
                          </button>
                        )}
                      </div>
                    </div>
                  </li>
                );
              })}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
