import { displayValue, formatDateTime, displayMessage, statusLabel } from "@/lib/display-format";
import { orderStatusLabel } from "@/lib/order-status";
// ============================================
// Notification List Component
// P2: Sub-components receive typed DTOs as props.
// ============================================

import { Bell, Check, CheckCheck, Clock, Package, Truck, CircleCheck, UserPlus, UserCog, UserMinus } from "lucide-react";
import type { NotificationResponseDTO, NotificationStatus } from "../dtos/notification.dto";

// ============================================
// Status Config
// ============================================

const STATUS_CONFIG: Record<
  NotificationStatus,
  { label: string; color: string; icon: typeof Bell }
> = {
  ordered: {
    label: statusLabel("ordered"),
    color: "bg-blue-100 text-blue-700 border-blue-200",
    icon: Package,
  },
  processing: {
    label: statusLabel("processing"),
    color: "bg-yellow-100 text-yellow-700 border-yellow-200",
    icon: Clock,
  },
  dispatched: {
    label: statusLabel("dispatched"),
    color: "bg-purple-100 text-purple-700 border-purple-200",
    icon: Truck,
  },
  delivered: {
    label: statusLabel("delivered"),
    color: "bg-green-100 text-green-700 border-green-200",
    icon: CircleCheck,
  },
  cancelled: { label: statusLabel("cancelled"), color: "bg-red-100 text-red-700 border-red-200", icon: Bell },
  user_added: {
    label: "User Added",
    color: "bg-emerald-100 text-emerald-700 border-emerald-200",
    icon: UserPlus,
  },
  user_updated: {
    label: "User Updated",
    color: "bg-amber-100 text-amber-700 border-amber-200",
    icon: UserCog,
  },
  user_removed: {
    label: "User Removed",
    color: "bg-red-100 text-red-700 border-red-200",
    icon: UserMinus,
  },
};

// ============================================
// Component Props
// ============================================

interface NotificationListProps {
  notifications: NotificationResponseDTO[];
  isLoading: boolean;
  onMarkAsRead: (id: string) => void;
  audienceRole?: string | null;
}

// ============================================
// Notification List Component
// ============================================

export function NotificationList({
  notifications,
  isLoading,
  onMarkAsRead,
  audienceRole = null,
}: NotificationListProps) {
  // --- Loading Skeleton ---
  if (isLoading) {
    return (
      <div className="space-y-3">
        {Array.from({ length: 5 }).map((_, i) => (
          <div
            key={i}
            className="animate-pulse rounded-xl border border-gray-200 bg-white p-4"
          >
            <div className="flex items-start gap-4">
              <div className="h-10 w-10 rounded-lg bg-gray-200" />
              <div className="flex-1 space-y-2">
                <div className="h-4 w-3/4 rounded bg-gray-200" />
                <div className="h-3 w-1/2 rounded bg-gray-200" />
              </div>
              <div className="h-6 w-20 rounded-full bg-gray-200" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  // --- Empty State ---
  if (notifications.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center rounded-xl border border-gray-200 bg-white py-16">
        <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-gray-100">
          <Bell className="h-8 w-8 text-gray-400" />
        </div>
        <h3 className="text-lg font-medium text-gray-900">No notifications</h3>
        <p className="mt-1 text-sm text-gray-500">
          Notifications will appear here.
        </p>
      </div>
    );
  }

  // --- Notification List ---
  return (
    <div className="space-y-3">
      {notifications.map((notification) => {
        const config = STATUS_CONFIG[notification.status];
        const StatusIcon = config.icon;
        const isOrderNotification = ["ordered", "processing", "dispatched", "delivered", "cancelled"].includes(notification.status);
        const audienceLabel = isOrderNotification ? orderStatusLabel(notification.status, audienceRole) : config.label;
        const audienceMessage = isOrderNotification && notification.orderNumber
          ? `Order ${notification.orderNumber} is ${audienceLabel.toLowerCase()}.`
          : notification.message;

        return (
          <div
            key={notification.id}
            className={`relative rounded-xl border bg-white p-4 transition-colors ${
              notification.read
                ? "border-gray-200"
                : "border-blue-200 bg-blue-50/30"
            }`}
          >
            <div className="flex items-start gap-4">
              {/* Status Icon */}
              <div
                className={`flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg border ${config.color}`}
              >
                <StatusIcon className="h-5 w-5" />
              </div>

              {/* Content */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <p
                    className={`text-sm font-medium ${
                      notification.read ? "text-gray-700" : "text-gray-900"
                    }`}
                  >
                    {displayValue(notification.orderNumber)}
                  </p>
                  <span
                    className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${config.color}`}
                  >
                    {audienceLabel}
                  </span>
                </div>
                <p className="mt-1 text-sm text-gray-500">
                  {displayValue(notification.companyName)}
                </p>
                {audienceMessage && (
                  <p className="mt-1 text-sm text-gray-600">
                    {displayMessage(audienceMessage)}
                  </p>
                )}
                <p className="mt-1 text-xs text-gray-400">
                  {formatDateTime(notification.createdAt)}
                </p>
              </div>

              {/* Mark as Read Button */}
              {!notification.read && (
                <button
                  onClick={() => onMarkAsRead(notification.id)}
                  className="flex-shrink-0 rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                  title="Mark as read"
                >
                  <Check className="h-4 w-4" />
                </button>
              )}

              {/* Read indicator */}
              {notification.read && (
                <div className="flex-shrink-0 rounded-lg p-2 text-green-500">
                  <CheckCheck className="h-4 w-4" />
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}
