"use client";

import { useState, useCallback } from "react";
import { useNotifications } from "@/features/notifications/hooks/use-notifications";
import { AdminLayout } from "@/components/admin-layout";
import { NotificationList } from "@/features/notifications/components/notification-list";
import { Button } from "@/components/ui/button";
import { CheckCheck, Bell, Shield } from "lucide-react";
import { useAccess } from "@/features/auth/hooks/use-access";
import type { SystemRole } from "@/features/manage-users/dtos/manage-users.dto";

// ============================================
// Role Display Config for Notifications
// ============================================

const ROLE_NOTIFICATION_CONFIG: Record<
  SystemRole,
  {
    label: string;
    color: string;
    bgColor: string;
    borderColor: string;
    description: string;
  }
> = {
  super_admin: {
    label: "Super Admin",
    color: "text-purple-600",
    bgColor: "bg-purple-50",
    borderColor: "border-purple-200",
    description: "All system notifications",
  },
  it_team: {
    label: "IT Team",
    color: "text-blue-600",
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
    description: "Company and system notifications",
  },
  delivery_management: {
    label: "Delivery Management",
    color: "text-orange-600",
    bgColor: "bg-orange-50",
    borderColor: "border-orange-200",
    description: "Delivery and dispatch notifications",
  },
  department_user: {
    label: "Community User",
    color: "text-emerald-600",
    bgColor: "bg-emerald-50",
    borderColor: "border-emerald-200",
    description: "Order and community notifications",
  },
};

// ============================================
// Notifications Page
// P1: Calls hook only. Never call service, adapter, or apiClient directly.
// P3: Always handle: loading → skeleton | error → message | empty → empty state.
// P4: Never import service / adapter / apiClient.
// ============================================

export default function NotificationsPage() {
  const [page, setPage] = useState(1);
  const { role, roleName } = useAccess();
  const roleConfig = ROLE_NOTIFICATION_CONFIG[role as SystemRole] ?? { ...ROLE_NOTIFICATION_CONFIG.department_user, label: roleName, description: "Your notifications" };

  // H1: Calls hook only
  const {
    notifications,
    isLoading,
    error,
    markAsRead,
    markAllAsRead,
  } = useNotifications();

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

  // --- Handlers ---
  const handleMarkAsRead = useCallback(
    (id: string) => {
      markAsRead(id);
    },
    [markAsRead]
  );

  const handleMarkAllAsRead = useCallback(() => {
    markAllAsRead();
  }, [markAllAsRead]);

  return (
    <AdminLayout>
      {/* Error State */}
      {error && !isLoading && notifications.length === 0 && (
        <div className="mb-6 rounded-xl border border-red-200 bg-red-50 p-4">
          <p className="text-sm text-red-600">{error}</p>
        </div>
      )}

      {/* Page Header with Role Info */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex min-w-0 items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 border border-blue-200">
            <Bell className="h-5 w-5 text-blue-600" />
          </div>
          <div className="min-w-0">
            <h1 className="text-2xl font-bold text-gray-900">Notifications</h1>
            <div className="flex flex-wrap items-center gap-2">
              <p className="text-sm text-gray-500">
                {roleConfig.description}
              </p>
              {unreadCount > 0 && (
                <span className="inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
                  {unreadCount} unread
                </span>
              )}
            </div>
          </div>
        </div>

        {/* Role Badge + Mark All as Read */}
        <div className="flex flex-wrap items-center gap-2 sm:justify-end">
          <span
            className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium ${roleConfig.bgColor} ${roleConfig.borderColor} ${roleConfig.color}`}
          >
            <Shield className="h-3 w-3" />
            {roleConfig.label}
          </span>
          {unreadCount > 0 && (
            <Button
              variant="secondary"
              size="sm"
              onClick={handleMarkAllAsRead}
              disabled={isLoading}
            >
              <CheckCheck className="mr-2 h-4 w-4" />
              Mark all as read
            </Button>
          )}
        </div>
      </div>

      {/* P2: Sub-components receive typed DTOs as props */}
      <NotificationList
        notifications={notifications}
        isLoading={isLoading}
        onMarkAsRead={handleMarkAsRead}
        audienceRole={role}
      />
    </AdminLayout>
  );
}
