// components/dashboard/notifications-content.tsx
'use client';

import React, { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import Image from "next/image";
import axios from "axios";
import {
  Bell,
  Heart,
  MessageCircle,
  Repeat,
  UserPlus,
  Clock,
  RefreshCw,
  Check,
  Loader,
  Bookmark,
  Sparkles
} from "lucide-react";
import { RootState } from "@/lib/store/store";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
const SECURITY_KEY = process.env.NEXT_PUBLIC_SECURITY_KEY;

// Types
interface Notification {
  _id: string;
  activityType: string;
  message?: string;
  isRead: boolean;
  createdAt: string;
  timeAgo?: string;
  navigationId?: string;
  navigationPath?: string;
  senderName?: string;
  senderProfilePic?: string;
  metadata?: {
    senderName?: string;
    postDescription?: string;
    [key: string]: any;
  };
}

interface NotificationsPageData {
  mainImage?: string;
  pageTitle?: string;
  description?: string;
}

interface LogoImage {
  securityKey?: string;
  [key: string]: any;
}

interface NotificationsContentProps {
  notificationsPageData: NotificationsPageData;
  logoImage: LogoImage;
}

const getImageUrl = (path: string) => {
  if (!path) return "";
  if (path.startsWith("http")) return path;
  return `${BASE_URL}/uploads/${path.replace(/^\//, "")}`;
};

const NotificationsContent = ({ notificationsPageData, logoImage }: NotificationsContentProps) => {
  const router = useRouter();
  const { currentCustomer, accessToken } = useSelector((state: RootState) => state.user);
  
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [unreadCount, setUnreadCount] = useState(0);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [markingRead, setMarkingRead] = useState(false);

  const bgImage = notificationsPageData?.mainImage
    ? getImageUrl(notificationsPageData.mainImage)
    : null;

  // Fetch notifications
  const fetchNotifications = useCallback(async (pageNum = 1) => {
    if (!accessToken) {
      router.push("/login");
      return;
    }

    try {
      if (pageNum === 1) {
        setLoading(true);
      } else {
        setLoadingMore(true);
      }



      const response = await axios.get(
        `${BASE_URL}/notification/customerNotifications`,
        {
          params: {
            page: pageNum,
            limit: 20,
            userSchema: "customer",
          },
          headers: {
            "x-security-key": SECURITY_KEY,
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );


      if (response.data.success) {
        const newNotifications = response.data.data.notifications || [];
        const formattedNotifications = newNotifications.map((notif: any) => ({
          ...notif,
          timeAgo: formatTimeAgo(notif.createdAt)
        }));

        if (pageNum === 1) {
          setNotifications(formattedNotifications);
        } else {
          setNotifications(prev => [...prev, ...formattedNotifications]);
        }
        setHasMore(response.data.data.pagination?.hasMore || false);
        setPage(pageNum);
      }
    } catch (error: any) {
      console.error("Error fetching notifications:", error);
      if (error.response?.status === 401) {
        router.push("/login");
      }
    } finally {
      setLoading(false);
      setLoadingMore(false);
      setRefreshing(false);
    }
  }, [accessToken, router]);

  // Fetch notification count
  const fetchNotificationCount = useCallback(async () => {
    if (!accessToken) return;

    try {
      const response = await axios.get(
        `${BASE_URL}/notification/customerNotificationCount`,
        {
          headers: {
            "x-security-key": SECURITY_KEY,
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data.success) {
        setUnreadCount(response.data.data || 0);
      }
    } catch (error) {
      console.error("Error fetching notification count:", error);
    }
  }, [accessToken]);

  // Mark all as read
  const markAllAsRead = async () => {
    if (!accessToken || notifications.length === 0) return;

    setMarkingRead(true);
    try {
      const response = await axios.put(
        `${BASE_URL}/notification/markAllAsRead`,
        {},
        {
          headers: {
            "x-security-key": SECURITY_KEY,
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      if (response.data.success) {
        setNotifications(prev =>
          prev.map(notif => ({ ...notif, isRead: true }))
        );
        setUnreadCount(0);
      }
    } catch (error) {
      console.error("Error marking all as read:", error);
    } finally {
      setMarkingRead(false);
    }
  };

  // Mark single as read
  const markAsRead = async (notificationId: string) => {
    try {
      setNotifications(prev =>
        prev.map(notif =>
          notif._id === notificationId ? { ...notif, isRead: true } : notif
        )
      );
      if (unreadCount > 0) {
        setUnreadCount(prev => prev - 1);
      }
    } catch (error) {
      console.error("Error marking as read:", error);
    }
  };

  // Format time ago
  const formatTimeAgo = (date: string) => {
    const now = new Date();
    const past = new Date(date);
    const diffMs = now.getTime() - past.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return "Just now";
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
    return past.toLocaleDateString();
  };

  const getNotificationIcon = (type: string) => {
  switch (type) {
     case "welcome":
      return <Sparkles className="w-5 h-5 text-green-500" />;
    case "postLike":
      return <Heart className="w-5 h-5 text-red-500 fill-red-500" />;
    case "postDislike":
      return <Heart className="w-5 h-5 text-gray-500" />;
    case "postSave":
      return <Bookmark className="w-5 h-5 text-blue-500 fill-blue-500" />;  // 👈 Add Bookmark icon
    case "postUnsave":
      return <Bookmark className="w-5 h-5 text-gray-500" />;  // 👈 Empty bookmark
    case "comment":
      return <MessageCircle className="w-5 h-5 text-blue-500" />;
    case "commentReply":
      return <Repeat className="w-5 h-5 text-green-500" />;
    case "postMention":
      return <UserPlus className="w-5 h-5 text-purple-500" />;
    default:
      return <Bell className="w-5 h-5 text-yellow-500" />;
  }
};
  // // Get notification icon
  // const getNotificationIcon = (type: string) => {
  //   switch (type) {
  //     case "postLike":
  //       return <Heart className="w-5 h-5 text-red-500 fill-red-500" />;
  //     case "comment":
  //       return <MessageCircle className="w-5 h-5 text-blue-500" />;
  //     case "commentReply":
  //       return <Repeat className="w-5 h-5 text-green-500" />;
  //     case "postMention":
  //       return <UserPlus className="w-5 h-5 text-purple-500" />;
  //     default:
  //       return <Bell className="w-5 h-5 text-yellow-500" />;
  //   }
  // };


const getNotificationMessage = (notification: Notification) => {
  // ✅ For welcome notifications, don't append senderName again
  if (notification.activityType === "welcome") {
    return notification.message || "Welcome to CheckUrIdea! 🎉";
  }
  
  const senderName = notification.senderName || notification.metadata?.senderName || "Someone";

  switch (notification.activityType) {
    case "postLike":
      return `${senderName} liked your post`;
    case "postDislike":
      return `${senderName} disliked your post`;
    case "postSave":
      return `${senderName} saved your post`;
    case "postUnsave":
      return `${senderName} removed your post from saved`;
    case "comment":
      return `${senderName} commented on your post`;
    case "commentReply":
      return `${senderName} replied to your comment`;
    case "postMention":
      return `${senderName} mentioned you in a post`;
    default:
      return notification.message || "New notification";
  }
};

  // Get notification message
  // const getNotificationMessage = (notification: Notification) => {
  //   const senderName = notification.senderName || notification.metadata?.senderName || "Someone";

  //   switch (notification.activityType) {
  //     case "postLike":
  //       return `${senderName} liked your post`;
  //     case "comment":
  //       return `${senderName} commented on your post`;
  //     case "commentReply":
  //       return `${senderName} replied to your comment`;
  //     case "postMention":
  //       return `${senderName} mentioned you`;
  //     default:
  //       return notification.message || "New notification";
  //   }
  // };

  // Handle notification click
  const handleNotificationClick = (notification: Notification) => {
    if (!notification) return;

    if (!notification.isRead) {
      markAsRead(notification._id);
    }

    if (notification.navigationId) {
      router.push(`/idea/${notification.navigationId}`);
    } else if (notification.navigationPath) {
      router.push(notification.navigationPath);
    }
  };

  // Load more
  const loadMore = () => {
    if (!loadingMore && hasMore) {
      fetchNotifications(page + 1);
    }
  };

  // Refresh
  const handleRefresh = () => {
    setRefreshing(true);
    fetchNotifications(1);
    fetchNotificationCount();
  };

  // Initial fetch
  useEffect(() => {
    if (!currentCustomer && !accessToken) {
      router.push("/login");
      return;
    }

    fetchNotifications();
    fetchNotificationCount();

    // Refresh count every 30 seconds
    const interval = setInterval(() => {
      fetchNotificationCount();
    }, 30000);

    return () => clearInterval(interval);
  }, [currentCustomer, accessToken, fetchNotifications, fetchNotificationCount, router]);

  if (!currentCustomer && !accessToken) {
    return null;
  }

  return (
    <div className="w-full">
      <div className="flex flex-col gap-5">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground">Notifications</h1>
            <p className="text-sm text-muted-foreground mt-1">
              {loading ? "Loading..." : 
               unreadCount > 0 ? `${unreadCount} unread notification${unreadCount !== 1 ? 's' : ''}` : 
               'All caught up!'}
            </p>
          </div>

          <div className="flex items-center gap-2">
            {unreadCount > 0 && (
              <button
                onClick={markAllAsRead}
                disabled={markingRead}
                className="flex items-center gap-2 px-3 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50"
              >
                <Check className="w-4 h-4" />
                {markingRead ? "Marking..." : "Mark All Read"}
              </button>
            )}

            <button
              onClick={handleRefresh}
              disabled={refreshing}
              className="p-2 bg-secondary rounded-lg hover:bg-secondary/80 transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`} />
            </button>
          </div>
        </div>

        {/* Loading State */}
        {loading && page === 1 ? (
          <div className="space-y-3">
            {[1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="p-4 rounded-xl border bg-card animate-pulse">
                <div className="flex gap-3">
                  <div className="w-10 h-10 rounded-full bg-muted"></div>
                  <div className="flex-1 space-y-2">
                    <div className="h-4 bg-muted rounded w-3/4"></div>
                    <div className="h-3 bg-muted rounded w-1/2"></div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : notifications.length === 0 ? (
          // Empty State
          <div className="flex flex-col items-center justify-center min-h-[400px] bg-card rounded-xl border p-8">
            {bgImage ? (
              <Image
                width={300}
                height={200}
                src={bgImage}
                alt="No notifications"
                className="w-64 h-48 object-contain mb-6"
                priority
              />
            ) : (
              <Bell className="w-16 h-16 text-muted-foreground mb-4" />
            )}
            <p className="text-xl font-semibold text-foreground mb-2">
              No notifications yet
            </p>
            <p className="text-muted-foreground text-center">
              When someone likes or comments on your posts, you'll see it here.
            </p>
          </div>
        ) : (
          // Notifications List
          <>
            <div className="space-y-3">
              {notifications.map((notification) => (
                <div
                  key={notification._id}
                  onClick={() => handleNotificationClick(notification)}
                  className={`p-4 rounded-xl flex items-start gap-3 w-full border bg-card hover:shadow-md transition-all cursor-pointer ${
                    !notification.isRead ? "border-primary/30 bg-primary/5" : "border-border"
                  }`}
                >
                  {/* Icon */}
                  <div className="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center bg-secondary">
                    {notification.senderProfilePic ? (
                      <img
                        src={getImageUrl(notification.senderProfilePic)}
                        alt={notification.senderName || "Sender"}
                        className="w-full h-full rounded-full object-cover"
                      />
                    ) : (
                      getNotificationIcon(notification.activityType)
                    )}
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap justify-between items-start gap-2">
                      <p className="text-sm text-foreground">
                        <span className="font-semibold">
                          {notification.senderName || notification.metadata?.senderName || "Someone"}
                        </span>{" "}
                        <span className="text-muted-foreground">
                          {getNotificationMessage(notification)}
                        </span>
                      </p>
                      <span className="text-xs text-muted-foreground whitespace-nowrap flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {notification.timeAgo}
                      </span>
                    </div>

                    {notification.metadata?.postDescription && (
                      <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                        "{notification.metadata.postDescription}"
                      </p>
                    )}

                    {!notification.isRead && (
                      <div className="mt-2">
                        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-primary/20 text-primary">
                          New
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>

            {/* Load More */}
            {hasMore && (
              <div className="text-center pt-4 pb-6">
                <button
                  onClick={loadMore}
                  disabled={loadingMore}
                  className="px-6 py-2.5 bg-secondary hover:bg-secondary/80 text-foreground rounded-lg disabled:opacity-50 transition-colors"
                >
                  {loadingMore ? (
                    <span className="flex items-center gap-2">
                      <Loader className="w-4 h-4 animate-spin" />
                      Loading...
                    </span>
                  ) : (
                    "Load More"
                  )}
                </button>
              </div>
            )}

            {/* End Message */}
            {!hasMore && notifications.length > 0 && (
              <div className="text-center py-6">
                <p className="text-muted-foreground text-sm">
                  You've seen all notifications
                </p>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default NotificationsContent;