"use client";

import { useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import { Link } from "@/i18n/navigation";
import { useAdminNotificationPage, type Notification, type NotificationType } from "@/hooks/useAdminNotifications";

const NOTIFICATION_TITLE_ES: Record<string, string> = {
  "Subscription Cancelled": "Suscripción Cancelada",
  "Subscription Canceled": "Suscripción Cancelada",
  "New Subscription": "Nueva Suscripción",
  "Subscription Renewed": "Suscripción Renovada",
  "Subscription Expired": "Suscripción Expirada",
  "Subscription Updated": "Suscripción Actualizada",
  "Screening Completed": "Evaluación Completada",
  "Screening Complete": "Evaluación Completa",
  "New User": "Nuevo Usuario",
  "New User Registration": "Nuevo Registro de Usuario",
  "New Lead": "Nuevo Prospecto",
  "New Support Ticket": "Nuevo Ticket de Soporte",
  "Support Ticket Updated": "Ticket de Soporte Actualizado",
  "New Client Added": "Nuevo Cliente Agregado",
  "Client Added": "Cliente Agregado",
  "System Notification": "Notificación del Sistema",
};

export default function AdminNotifications() {
  const t = useTranslations();
  const locale = useLocale();
  const [currentPage, setCurrentPage] = useState(1);
  const [typeFilter, setTypeFilter] = useState<NotificationType | "">("");
  const [readFilter, setReadFilter] = useState<"" | "read" | "unread">("");
  const [deleteConfirmUuid, setDeleteConfirmUuid] = useState<string | null>(null);

  const {
    notifications,
    unreadCount,
    totalCount,
    totalPages,
    isLoading,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    isMarkingAllAsRead,
    isDeleting,
    refetch,
  } = useAdminNotificationPage({
    page: currentPage,
    limit: 50,
    ...(typeFilter && { type: typeFilter }),
    ...(readFilter && { is_read: readFilter === "read" }),
  });

  const getNotificationIcon = (type: NotificationType) => {
    switch (type) {
      case 'lead':
        return (
          <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
            </svg>
          </div>
        );
      case 'support':
        return (
          <div className="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-orange-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
          </div>
        );
      case 'user':
        return (
          <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </div>
        );
      case 'screening_complete':
        return (
          <div className="w-10 h-10 rounded-full bg-teal-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-teal-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
          </div>
        );
      case 'client_added':
        return (
          <div className="w-10 h-10 rounded-full bg-cyan-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-cyan-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7.5v3m0 0v3m0-3h3m-3 0h-3m-2.25-4.125a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zM4 19.235v-.11a6.375 6.375 0 0112.75 0v.109A12.318 12.318 0 0110.374 21c-2.331 0-4.512-.645-6.374-1.766z" />
            </svg>
          </div>
        );
      case 'subscription':
        return (
          <div className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
            </svg>
          </div>
        );
      case 'system':
      default:
        return (
          <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </div>
        );
    }
  };

  const getTypeLabel = (type: NotificationType) => {
    switch (type) {
      case 'lead':
        return t("admin.notifications.typeLead");
      case 'support':
        return t("admin.notifications.typeSupport");
      case 'user':
        return t("admin.notifications.typeUser");
      case 'screening_complete':
        return t("admin.notifications.typeScreeningComplete");
      case 'client_added':
        return t("admin.notifications.typeClientAdded");
      case 'subscription':
        return t("admin.notifications.typeSubscription");
      case 'system':
        return t("admin.notifications.typeSystem");
      default:
        return String(type).replace(/_/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase());
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString(locale === 'es' ? 'es-ES' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getNotificationLink = (notification: Notification) => {
    if (!notification.reference_id || !notification.reference_type) {
      return null;
    }

    switch (notification.reference_type) {
      case 'leads':
        return "/admin/lead";
      case 'support-tickets':
        return "/admin/support";
      case 'users':
        return "/admin/users";
      case 'subscriptions':
        return "/admin/subscription";
      default:
        return null;
    }
  };

  const handleMarkAsRead = (notification: Notification) => {
    if (!notification.is_read) {
      markAsRead(notification.uuid);
    }
  };

  const handleDelete = (uuid: string) => {
    setDeleteConfirmUuid(uuid);
  };

  const renderPagination = () => {
    const pages: (number | string)[] = [];

    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, '...', totalPages - 1, totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 2, '...', totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }

    return pages.map((page, index) => (
      typeof page === 'number' ? (
        <button
          key={index}
          onClick={() => setCurrentPage(page)}
          className={`w-8 h-8 rounded-lg text-sm font-medium cursor-pointer ${
            currentPage === page
              ? 'bg-gray-100 text-gray-900'
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          {page}
        </button>
      ) : (
        <span key={index} className="px-2 text-gray-400">{page}</span>
      )
    ));
  };

  // Only show full-page loading on initial load, not on filter changes
  const showFullPageLoading = isLoading && notifications.length === 0 && !typeFilter && !readFilter;

  return (
    <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Notifications Card */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
        {/* Header */}
        <div className="p-5 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-gray-900">
                {t("admin.notifications.title")}
                {totalCount > 0 && (
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    ({totalCount} {t("admin.notifications.total")})
                  </span>
                )}
              </h3>
              {unreadCount > 0 && (
                <p className="text-sm text-gray-500 mt-1">
                  {unreadCount} {t("admin.notifications.unread")}
                </p>
              )}
            </div>
            <div className="flex items-center gap-3">
              {/* Type Filter */}
              <select
                value={typeFilter}
                onChange={(e) => {
                  setTypeFilter(e.target.value as NotificationType | "");
                  setCurrentPage(1);
                }}
                className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[140px] cursor-pointer"
              >
                <option value="">{t("admin.notifications.allTypes")}</option>
                <option value="lead">{t("admin.notifications.typeLead")}</option>
                <option value="support">{t("admin.notifications.typeSupport")}</option>
                <option value="user">{t("admin.notifications.typeUser")}</option>
                <option value="screening_complete">{t("admin.notifications.typeScreeningComplete")}</option>
                <option value="client_added">{t("admin.notifications.typeClientAdded")}</option>
                <option value="subscription">{t("admin.notifications.typeSubscription")}</option>
                <option value="system">{t("admin.notifications.typeSystem")}</option>
              </select>

              {/* Read/Unread Filter */}
              <select
                value={readFilter}
                onChange={(e) => {
                  setReadFilter(e.target.value as "" | "read" | "unread");
                  setCurrentPage(1);
                }}
                className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
              >
                <option value="">{t("admin.notifications.allStatus")}</option>
                <option value="unread">{t("admin.notifications.unreadOnly")}</option>
                <option value="read">{t("admin.notifications.readOnly")}</option>
              </select>

              {/* Mark All as Read */}
              {unreadCount > 0 && (
                <button
                  onClick={() => markAllAsRead()}
                  disabled={isMarkingAllAsRead}
                  className="px-4 py-2 bg-[#3B9EC9] text-white text-sm font-medium rounded-lg hover:bg-[#2B8EB9] transition disabled:opacity-50 cursor-pointer"
                >
                  {isMarkingAllAsRead ? t("admin.notifications.marking") : t("admin.notifications.markAllRead")}
                </button>
              )}

              {/* Refresh */}
              <button
                onClick={() => refetch()}
                className="p-2 border border-gray-200 rounded-lg text-gray-600 hover:bg-gray-50 transition cursor-pointer"
                title={t("admin.notifications.refresh")}
              >
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
              </button>
            </div>
          </div>
        </div>

        {/* Notifications List */}
        <div className="divide-y divide-gray-100">
          {showFullPageLoading ? (
            <div className="flex items-center justify-center py-16">
              <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#3B9EC9]"></div>
            </div>
          ) : notifications.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-gray-500">
              <svg className="w-16 h-16 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
              </svg>
              <p className="text-lg font-medium">{t("admin.notifications.noNotifications")}</p>
              <p className="text-sm text-gray-400 mt-1">{t("admin.notifications.noNotificationsDesc")}</p>
            </div>
          ) : (
            notifications.map((notification: any) => {
              const link = getNotificationLink(notification);
              return (
                <div
                  key={notification.uuid}
                  className={`flex items-start gap-4 p-5 hover:bg-gray-50 transition ${
                    !notification.is_read ? "bg-blue-50/30" : ""
                  }`}
                >
                  {/* Icon */}
                  {getNotificationIcon(notification.type)}

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-4">
                      <div>
                        <div className="flex items-center gap-2">
                          <h4 className={`text-sm ${!notification.is_read ? "font-semibold text-gray-900" : "font-medium text-gray-700"}`}>
                            {locale === 'es' ? ((notification as any).title_es || NOTIFICATION_TITLE_ES[notification.title] || notification.title) : notification.title}
                          </h4>
                          {!notification.is_read && (
                            <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                          )}
                        </div>
                        <p className="text-sm text-gray-500 mt-1">{locale === 'es' ? ((notification as any).message_es || notification.message) : notification.message}</p>
                        <div className="flex items-center gap-3 mt-2">
                          <span className="text-xs text-gray-400">{formatDate(notification.created_at)}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full ${
                            notification.type === 'lead' ? 'bg-blue-100 text-blue-600' :
                            notification.type === 'support' ? 'bg-orange-100 text-orange-600' :
                            notification.type === 'user' ? 'bg-green-100 text-green-600' :
                            notification.type === 'screening_complete' ? 'bg-teal-100 text-teal-600' :
                            notification.type === 'client_added' ? 'bg-cyan-100 text-cyan-600' :
                            notification.type === 'subscription' ? 'bg-purple-100 text-purple-600' :
                            'bg-gray-100 text-gray-600'
                          }`}>
                            {getTypeLabel(notification.type)}
                          </span>
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="flex items-center gap-2">
                        {link && (
                          <Link
                            href={link}
                            onClick={() => handleMarkAsRead(notification)}
                            className="p-2 text-gray-400 hover:text-[#3B9EC9] hover:bg-gray-100 rounded-lg transition cursor-pointer"
                            title={t("admin.notifications.view")}
                          >
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                            </svg>
                          </Link>
                        )}
                        {!notification.is_read && (
                          <button
                            onClick={() => markAsRead(notification.uuid)}
                            className="p-2 text-gray-400 hover:text-green-600 hover:bg-gray-100 rounded-lg transition cursor-pointer"
                            title={t("admin.notifications.markRead")}
                          >
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                            </svg>
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(notification.uuid)}
                          disabled={isDeleting}
                          className="p-2 text-gray-400 hover:text-red-600 hover:bg-gray-100 rounded-lg transition disabled:opacity-50 cursor-pointer"
                          title={t("admin.notifications.delete")}
                        >
                          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="px-5 py-4 border-t border-gray-200 flex items-center justify-between">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              {t("admin.common.previous")}
            </button>

            <div className="flex items-center gap-1">
              {renderPagination()}
            </div>

            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              {t("admin.common.next")}
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
          </div>
        )}
      </div>
      {/* Delete Confirmation Modal */}
      {deleteConfirmUuid && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/40" onClick={() => setDeleteConfirmUuid(null)} />
          <div className="relative bg-white rounded-2xl shadow-xl w-full max-w-sm p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
                <svg className="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </div>
              <h2 className="text-base font-semibold text-gray-900">{t("admin.notifications.delete")}</h2>
            </div>
            <p className="text-sm text-gray-500 mb-6">{t("admin.notifications.confirmDelete")}</p>
            <div className="flex gap-3">
              <button
                onClick={() => setDeleteConfirmUuid(null)}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 border border-gray-200 rounded-xl hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.common.cancel")}
              </button>
              <button
                onClick={() => { deleteNotification(deleteConfirmUuid); setDeleteConfirmUuid(null); }}
                disabled={isDeleting}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-red-500 rounded-xl hover:bg-red-600 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
              >
                {t("admin.notifications.delete")}
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}
