"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { apiFetch, formatApiMsg } from "@/lib/api";
import { refreshUnreadNotificationCount } from "@/lib/notifications/count";
import {
  normalizeNotificationData,
  resolveNotificationRouteData,
  routeForNotificationType,
} from "@/lib/notifications/routes";
import { toast } from "sonner";

export interface NotificationData {
  id: string;
  type: string;
  title: string;
  body: string;
  body_ar?: string;
  is_read: boolean;
  created_at: string;
  action_url?: string;
  data?: {
    type?: string;
    model_id?: string | number;
    params?: Record<string, unknown>;
    title_key?: string;
    body_key?: string;
  };
  template_data?: Record<string, any>;
}

export interface NotificationsPagination {
  total_items: number;
  count_items: number;
  per_page: number;
  total_pages: number;
  current_page: number;
  next_page_url: string | null;
  perv_page_url: string | null;
}

export interface NotificationsResponse {
  notifications: {
    data: NotificationData[];
    pagination: NotificationsPagination;
  };
}

interface NotificationItemProps {
  notification: NotificationData;
  onDeleteOptimistic: (id: string) => void;
  onReadOptimistic: (id: string) => void;
}

interface NotificationPresentation {
  icon: string;
  colorClass: string;
  bgClass: string;
  targetRoute: string | null;
}

function resolveNotificationBody(notification: NotificationData): string {
  const templateData = normalizeNotificationData(notification.template_data);
  if (Object.keys(templateData).length > 0) {
    let resolved = notification.body;
    for (const [key, value] of Object.entries(templateData)) {
      resolved = resolved.replace(new RegExp(`:${key}`, "g"), String(value));
    }
    return resolved;
  }
  if (notification.body_ar) {
    return notification.body_ar;
  }
  return notification.body;
}

function getNotificationPresentation(
  notification: NotificationData,
): NotificationPresentation {
  const targetRoute = routeForNotificationType(
    notification.type,
    resolveNotificationRouteData(notification),
  );

  switch (notification.type) {
    case "settlement_accepted":
    case "settlement_transferred":
    case "settlement_invoice_ready":
    case "settlement_objection_resolved":
      return {
        icon: "ri-checkbox-circle-fill",
        colorClass: "text-green-500",
        bgClass: "bg-green-500/10",
        targetRoute,
      };
    case "settlement_rejected":
      return {
        icon: "ri-close-circle-fill",
        colorClass: "text-red-500",
        bgClass: "bg-red-500/10",
        targetRoute,
      };
    case "scooters_assigned":
      return {
        icon: "ri-e-bike-fill",
        colorClass: "text-[#FCD704]",
        bgClass: "bg-[#FCD704]/10",
        targetRoute,
      };
    case "blocked":
      return {
        icon: "ri-forbid-fill",
        colorClass: "text-red-500",
        bgClass: "bg-red-500/10",
        targetRoute,
      };
    case "entity_update_approved":
      return {
        icon: "ri-user-settings-fill",
        colorClass: "text-green-500",
        bgClass: "bg-green-500/10",
        targetRoute,
      };
    case "entity_update_rejected":
      return {
        icon: "ri-user-settings-fill",
        colorClass: "text-red-500",
        bgClass: "bg-red-500/10",
        targetRoute,
      };
    case "investor_verification_result": {
      const status = notification.template_data?.status;
      const isApproved =
        status === "approved" || status === "active" || status === "verified";
      if (isApproved) {
        return {
          icon: "ri-shield-check-fill",
          colorClass: "text-green-500",
          bgClass: "bg-green-500/10",
          targetRoute,
        };
      }
      return {
        icon: "ri-error-warning-fill",
        colorClass: "text-[#FCD704]",
        bgClass: "bg-[#FCD704]/10",
        targetRoute,
      };
    }
    case "entity_approved":
      return {
        icon: "ri-user-settings-fill",
        colorClass: "text-green-500",
        bgClass: "bg-green-500/10",
        targetRoute,
      };
    case "entity_rejected":
      return {
        icon: "ri-user-settings-fill",
        colorClass: "text-red-500",
        bgClass: "bg-red-500/10",
        targetRoute,
      };
    case "entity_needs_approval":
      return {
        icon: "ri-user-settings-fill",
        colorClass: "text-blue-400",
        bgClass: "bg-blue-400/10",
        targetRoute,
      };
    case "admin_notify":
      return {
        icon: "ri-information-fill",
        colorClass: "text-blue-400",
        bgClass: "bg-blue-400/10",
        targetRoute,
      };
    case "complain_status_changed":
      return {
        icon: "ri-customer-service-2-fill",
        colorClass: "text-blue-400",
        bgClass: "bg-blue-400/10",
        targetRoute,
      };
    default:
      if (targetRoute === "/profile") {
        return {
          icon: "ri-user-settings-fill",
          colorClass: "text-green-500",
          bgClass: "bg-green-500/10",
          targetRoute,
        };
      }
      if (targetRoute) {
        return {
          icon: "ri-customer-service-2-fill",
          colorClass: "text-blue-400",
          bgClass: "bg-blue-400/10",
          targetRoute,
        };
      }
      return {
        icon: "ri-notification-3-fill",
        colorClass: "text-gray-400",
        bgClass: "bg-white/5",
        targetRoute: null,
      };
  }
}

export default function NotificationItem({
  notification,
  onDeleteOptimistic,
  onReadOptimistic,
}: Readonly<NotificationItemProps>) {
  const router = useRouter();
  const [isDeleting, setIsDeleting] = useState(false);
  const bodyText = resolveNotificationBody(notification);
  const { icon, colorClass, bgClass, targetRoute } =
    getNotificationPresentation(notification);
  const activateItem = () => {
    if (!notification.is_read) {
      onReadOptimistic(notification.id);
      apiFetch(`/provider/notifications/${notification.id}/read`, {
        method: "PATCH",
        successCase: () => {
          void refreshUnreadNotificationCount();
        },
        errorCase: (res) => {
          // Failure handled silently for optimism, or toast error
          toast.error(formatApiMsg(res.msg) || "تعذّر تعليم الإشعار كمقروء");
        },
      });
    }

    if (targetRoute) {
      router.push(targetRoute);
    }
  };

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (isDeleting) return;

    setIsDeleting(true);
    // Optimistically remove from list
    onDeleteOptimistic(notification.id);

    apiFetch(`/provider/delete-notification/${notification.id}`, {
      method: "DELETE",
      successCase: () => {
        void refreshUnreadNotificationCount();
      },
      errorCase: (res) => {
        // If it fails, ideally we'd re-add it, but for simplicity we'll just toast
        toast.error(formatApiMsg(res.msg) || "تعذّر حذف الإشعار");
        setIsDeleting(false);
      },
    }).finally(() => {
      // setIsDeleting(false); // No need if optimistically removed and component unmounts
    });
  };

  return (
    <div
      className={`relative p-5 rounded-2xl flex items-start gap-4 transition-colors
        ${notification.is_read ? "bg-[#1E2128]" : "bg-[#2A2D36] border border-white/5 hover:bg-[#323640]"}
        ${isDeleting ? "opacity-50 pointer-events-none" : ""}
      `}
    >
      {/* Unread dot indicator */}
      {!notification.is_read && (
        <span className="absolute top-4 right-4 w-2 h-2 rounded-full bg-[#FCD704]" />
      )}

      <button
        type="button"
        onClick={activateItem}
        className="flex flex-1 items-start gap-4 min-w-0 text-right border-0 bg-transparent p-0 cursor-pointer"
      >
        {/* Icon */}
        <div className={`w-12 h-12 flex items-center justify-center rounded-xl flex-shrink-0 ${bgClass}`}>
          <i className={`${icon} ${colorClass} text-xl`} />
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0 pr-2">
          <div className="flex items-start justify-between gap-4 mb-1">
            <h3 className={`font-bold text-sm truncate ${notification.is_read ? "text-gray-300" : "text-white"}`}>
              {notification.title}
            </h3>
            <span className="text-gray-500 text-xs whitespace-nowrap pt-0.5">
              {notification.created_at}
            </span>
          </div>
          <p className={`text-sm leading-relaxed ${notification.is_read ? "text-gray-500" : "text-gray-300"}`}>
            {bodyText}
          </p>
        </div>
      </button>

      {/* Delete Action */}
      <button
        type="button"
        onClick={handleDelete}
        className="delete-btn w-9 h-9 flex items-center justify-center rounded-xl text-gray-500 hover:bg-white/5 hover:text-red-400 transition-colors flex-shrink-0"
        aria-label="حذف الإشعار"
      >
        {isDeleting ? (
          <i className="ri-loader-4-line animate-spin text-base" />
        ) : (
          <i className="ri-delete-bin-line text-base" />
        )}
      </button>
    </div>
  );
}
