"use client";

import { useState } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import {
  usePractitionerNotificationControllerGetNotificationsV1 as usePractitionerNotificationsGet,
  usePractitionerNotificationControllerGetUnreadCountV1 as usePractitionerNotificationsUnreadCount,
  usePractitionerNotificationControllerMarkAsReadV1 as usePractitionerNotificationsMarkAsRead,
  usePractitionerNotificationControllerMarkAllAsReadV1 as usePractitionerNotificationsMarkAllAsRead,
} from "@/api/user/practitioner-notifications/practitioner-notifications";

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 NotificationsPage() {
  const router = useRouter();
  const t = useTranslations();
  const locale = useLocale();
  const queryClient = useQueryClient();
  const [filter, setFilter] = useState<"all" | "unread">("all");
  const [page, setPage] = useState(1);

  // Fetch notifications from API
  const { data: notificationsData, isLoading } = usePractitionerNotificationsGet(
    filter === "unread"
      ? { page, limit: 20, is_read: false }
      : { page, limit: 20 }
  );
  const rawData = notificationsData as any;
  const notifications: any[] =
    Array.isArray(rawData?.data) ? rawData.data :
    Array.isArray(rawData?.data?.data) ? rawData.data.data :
    Array.isArray(rawData?.data?.items) ? rawData.data.items :
    Array.isArray(rawData) ? rawData : [];
  const meta = rawData?.meta || rawData?.data?.meta;
  const totalPages = meta?.totalPages || 1;
  const totalItems = meta?.totalItems || notifications.length;

  // Fetch unread count from API
  const { data: unreadData } = usePractitionerNotificationsUnreadCount();
  const unreadCount: number = (unreadData as any)?.data?.unread_count ?? (unreadData as any)?.unread_count ?? 0;

  // Mark as read mutation
  const markAsReadMutation = usePractitionerNotificationsMarkAsRead({
    mutation: {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['/v1/practitioner/notifications'] });
        queryClient.invalidateQueries({ queryKey: ['/v1/practitioner/notifications/unread-count'] });
      },
    },
  });

  // Mark all as read mutation
  const markAllAsReadMutation = usePractitionerNotificationsMarkAllAsRead({
    mutation: {
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ['/v1/practitioner/notifications'] });
        queryClient.invalidateQueries({ queryKey: ['/v1/practitioner/notifications/unread-count'] });
      },
    },
  });

  const formatTimeAgo = (dateStr: string): string => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMins < 1) return t("practitioner.notifications.justNow");
    if (diffMins < 60) return `${diffMins} ${t("practitioner.notifications.minutesAgo")}`;
    if (diffHours < 24) return `${diffHours} ${t("practitioner.notifications.hoursAgo")}`;
    return `${diffDays} ${t("practitioner.notifications.daysAgo")}`;
  };

  const handleMarkAsRead = (id: string) => {
    markAsReadMutation.mutate({ id });
  };

  const handleMarkAllAsRead = () => {
    markAllAsReadMutation.mutate();
  };

  const handleNotificationClick = (notification: any) => {
    if (!notification.is_read) {
      handleMarkAsRead(String(notification.uuid || notification.id));
    }

    const data = notification.data || {};
    switch (notification.type) {
      case "screening_complete":
        if (data.client_id && data.screening_id) {
          router.push(`/practitioner/report/${data.client_id}/${data.screening_id}`);
        }
        break;
      case "system":
      case "client_added":
        router.push("/practitioner/clients");
        break;
      case "subscription":
        router.push("/practitioner/subscription");
        break;
    }
  };

  const getNotificationIcon = (type: string) => {
    switch (type) {
      case "screening_complete":
        return (
          <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
            </svg>
          </div>
        );
      case "system":
        return (
          <div className="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
        );
      case "client_added":
        return (
          <div className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <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-12 h-12 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
        );
      default:
        return (
          <div className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0">
            <svg className="w-6 h-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
            </svg>
          </div>
        );
    }
  };

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Page Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-4">
            <button
              onClick={() => router.push("/practitioner")}
              className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition cursor-pointer"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
              </svg>
            </button>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {t("practitioner.notifications.title")}
              </h1>
              <p className="text-sm text-gray-500 mt-1">
                {unreadCount > 0
                  ? (unreadCount > 1
                      ? t("practitioner.notifications.unreadCountPlural", { count: unreadCount })
                      : t("practitioner.notifications.unreadCount", { count: unreadCount }))
                  : t("practitioner.notifications.allCaughtUp")
                }
              </p>
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-3">
            {unreadCount > 0 && (
              <button
                onClick={handleMarkAllAsRead}
                className="px-4 py-2 text-sm font-medium text-[#3B9EC9] hover:text-[#2D8AB5] transition cursor-pointer"
              >
                {t("practitioner.notifications.markAllRead")}
              </button>
            )}
          </div>
        </div>

        {/* Filter Tabs */}
        <div className="flex items-center gap-4 mb-6 border-b border-gray-200">
          <button
            onClick={() => { setFilter("all"); setPage(1); }}
            className={`pb-3 px-1 text-sm font-medium border-b-2 transition cursor-pointer ${
              filter === "all"
                ? "text-[#3B9EC9] border-[#3B9EC9]"
                : "text-gray-500 border-transparent hover:text-gray-700"
            }`}
          >
            {t("practitioner.notifications.all")} ({totalItems})
          </button>
          <button
            onClick={() => { setFilter("unread"); setPage(1); }}
            className={`pb-3 px-1 text-sm font-medium border-b-2 transition cursor-pointer ${
              filter === "unread"
                ? "text-[#3B9EC9] border-[#3B9EC9]"
                : "text-gray-500 border-transparent hover:text-gray-700"
            }`}
          >
            {t("practitioner.notifications.unread")} ({unreadCount})
          </button>
        </div>

        {/* Notifications List */}
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
          {isLoading ? (
            <div className="flex items-center justify-center py-16">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
            </div>
          ) : notifications.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 px-4">
              <div className="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                <svg className="w-10 h-10 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                </svg>
              </div>
              <p className="text-lg font-medium text-gray-900 mb-1">
                {filter === "unread" ? t("practitioner.notifications.noUnreadNotifications") : t("practitioner.notifications.noNotifications")}
              </p>
              <p className="text-sm text-gray-500">
                {filter === "unread" ? t("practitioner.notifications.noUnreadNotificationsDesc") : t("practitioner.notifications.noNotificationsDesc")}
              </p>
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {notifications.map((notification: any) => (
                <button
                  key={notification.id}
                  onClick={() => handleNotificationClick(notification)}
                  className={`w-full flex items-start gap-4 p-5 text-left hover:bg-gray-50 transition cursor-pointer ${
                    !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>
                        <p className={`text-base font-semibold ${!notification.is_read ? "text-gray-900" : "text-gray-700"}`}>
                          {locale === 'es' ? ((notification as any).title_es || NOTIFICATION_TITLE_ES[notification.title] || notification.title) : notification.title}
                        </p>
                        <p className="text-sm text-gray-500 mt-1">
                          {locale === 'es' ? ((notification as any).message_es || notification.message) : notification.message}
                        </p>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        {!notification.is_read && (
                          <span className="w-2.5 h-2.5 rounded-full bg-red-500"></span>
                        )}
                        <p className="text-xs text-gray-400 whitespace-nowrap">
                          {notification.created_at ? formatTimeAgo(notification.created_at) : ""}
                        </p>
                      </div>
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between mt-6">
            <button
              onClick={() => setPage(Math.max(1, page - 1))}
              disabled={page === 1}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
            >
              <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("practitioner.notifications.previous")}
            </button>
            <span className="text-sm text-gray-500">
              {t("practitioner.notifications.pageOf", { page, totalPages })}
            </span>
            <button
              onClick={() => setPage(Math.min(totalPages, page + 1))}
              disabled={page === totalPages}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition"
            >
              {t("practitioner.notifications.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>
    </main>
  );
}
