"use client";

import { useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import { Link } from "@/i18n/navigation";
import { useIndividualNotificationPage, type IndividualNotification, type IndividualNotificationType } from "@/hooks/useIndividualNotifications";

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 IndividualNotifications() {
  const t = useTranslations("individual.notifications");
  const tCommon = useTranslations("individual.subscription");
  const locale = useLocale();
  const [currentPage, setCurrentPage] = useState(1);
  const [readFilter, setReadFilter] = useState<"" | "read" | "unread">("");

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

  const getNotificationIcon = (type: IndividualNotificationType) => {
    switch (type) {
      case 'screening':
        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="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 '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 '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 'payment':
        return (
          <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center">
            <svg className="w-5 h-5 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
        );
      case 'system':
      default:
        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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
        );
    }
  };

  const getTypeLabel = (type: IndividualNotificationType) => {
    switch (type) {
      case 'screening':
        return t("typeScreening");
      case 'support':
        return t("typeSupport");
      case 'subscription':
        return t("typeSubscription");
      case 'payment':
        return t("typePayment");
      case 'system':
        return t("typeSystem");
      default:
        return type;
    }
  };

  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: IndividualNotification) => {
    if (!notification.reference_id || !notification.reference_type) {
      return null;
    }

    switch (notification.reference_type) {
      case 'screenings':
        return `/individual/screening/${notification.reference_id}/reports`;
      case 'subscriptions':
        return "/individual/subscription";
      default:
        return null;
    }
  };

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

  const handleDelete = (uuid: string) => {
    if (confirm(t("confirmDelete"))) {
      deleteNotification(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 && !readFilter;

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-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 flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  {t("title")}
                  {totalCount > 0 && (
                    <span className="ml-2 text-sm font-normal text-gray-500">
                      ({totalCount} {t("total")})
                    </span>
                  )}
                </h3>
                {unreadCount > 0 && (
                  <p className="text-sm text-gray-500 mt-1">
                    {unreadCount} {t("unread")}
                  </p>
                )}
              </div>
              <div className="flex flex-wrap items-center gap-3">
                {/* 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]"
                >
                  <option value="">{t("allStatus")}</option>
                  <option value="unread">{t("unreadOnly")}</option>
                  <option value="read">{t("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("marking") : t("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("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("noNotifications")}</p>
                <p className="text-sm text-gray-400 mt-1">{t("noNotificationsDesc")}</p>
              </div>
            ) : (
              notifications.map((notification: IndividualNotification) => {
                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 === 'screening' ? 'bg-blue-100 text-blue-600' :
                              notification.type === 'support' ? 'bg-orange-100 text-orange-600' :
                              notification.type === 'subscription' ? 'bg-purple-100 text-purple-600' :
                              notification.type === 'payment' ? 'bg-emerald-100 text-emerald-600' :
                              'bg-green-100 text-green-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"
                              title={t("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("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("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>
                {tCommon("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"
              >
                {tCommon("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>
      </div>
    </main>
  );
}
