import { useNavigate } from "react-router-dom";
import { motion } from "motion/react";
import { useCallback, useEffect, useRef } from "react";
import { usePageTracking } from "../../hooks/usePageTracking";
import { useInbox } from "../context/InboxContext";
import { FeedHeader } from "./feed/FeedHeader";
import { getMessageStyle } from "../../utils/messageUtils";
import { AppBackground } from "./shared/AppBackground";
import { backgroundImages } from "../../config/backgroundConfig";
import { BottomNav } from "./BottomNav";

export function MessagesPage() {
  const navigate = useNavigate();
  usePageTracking("پیام‌ها");
  const { messages, loading, markMessagesAsRead } = useInbox();
  const hasMarkedAsReadRef = useRef(false);

  const handleBack = useCallback(() => {
    navigate("/");
  }, [navigate]);

  // Mark all unread messages as read when page is opened (only once)
  useEffect(() => {
    if (!loading && messages.length > 0 && !hasMarkedAsReadRef.current) {
      const unreadStageIds = messages
        .filter((msg) => msg.status === "خوانده نشده")
        .map((msg) => String(msg.stageID));

      if (unreadStageIds.length > 0) {
        hasMarkedAsReadRef.current = true;
        markMessagesAsRead(unreadStageIds);
      }
    }
  }, [loading, messages, markMessagesAsRead]);

  return (
    <div className="min-h-screen w-full relative overflow-hidden">
      <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.messages} />

      {/* Content */}
      <div className="relative z-10 max-w-md mx-auto">
        {/* Header */}
        <FeedHeader topicTitle="پیام‌ها" onBack={handleBack} />

        {/* Messages List - Scrollable */}
        <div
          className="fixed top-0 left-0 right-0 bottom-0 max-w-md mx-auto overflow-hidden"
          style={{
            paddingTop: "110px",
            zIndex: 1,
          }}
        >
          <div
            className="h-full overflow-y-auto relative px-[20px] pt-[48px] pb-[128px]"
            style={{
              scrollbarWidth: "none",
              msOverflowStyle: "none",
              maskImage: "linear-gradient(to bottom, transparent 0%, black 60px)",
              WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 60px)",
            }}
          >
            {loading ? (
              <div className="flex items-center justify-center h-full">
                <div className="text-white text-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
                  <p>در حال بارگذاری پیام‌ها...</p>
                </div>
              </div>
            ) : messages.length === 0 ? (
              <div className="flex items-center justify-center h-full">
                <div className="text-white text-center">
                  <p className="text-lg">پیامی وجود ندارد</p>
                </div>
              </div>
            ) : (
              <div className="space-y-4" dir="rtl">
                {messages.map((message, index) => {
                  const messageStyle = getMessageStyle(message.kind);
                  const isUnread = message.status === "خوانده نشده";

                  return (
                    <motion.div
                      key={`${message.user_id}-${index}`}
                      initial={{ opacity: 0, x: -50 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: index * 0.1, duration: 0.4 }}
                      className="relative"
                    >
                      <div
                        className="rounded-3xl p-5 backdrop-blur-sm"
                        style={{
                          background: messageStyle.gradient,
                          border: `1.5px solid ${messageStyle.border}`,
                          boxShadow: messageStyle.shadow,
                          opacity: isUnread ? 1 : 0.85,
                        }}
                      >
                        {/* Unread Badge */}
                        {isUnread && (
                          <div
                            className="absolute top-3 left-3 w-3 h-3 rounded-full"
                            style={{
                              background: "linear-gradient(135deg, #FF4444 0%, #CC0000 100%)",
                              boxShadow: "0 0 8px rgba(255, 68, 68, 0.8)",
                            }}
                          />
                        )}

                        <div className="flex items-start gap-4">
                          {/* Icon */}
                          <div
                            className="flex-shrink-0 w-12 h-12 rounded-full flex items-center justify-center text-white"
                            style={{
                              background: messageStyle.gradient,
                              boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                            }}
                          >
                            {messageStyle.icon}
                          </div>

                          {/* Content */}
                          <div className="flex-1">
                            <h3 className="text-white font-bold text-base mb-2">{message.title}</h3>
                            <p className="text-white/80 text-sm leading-relaxed">{message.Message}</p>
                          </div>
                        </div>
                      </div>
                    </motion.div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Bottom fade gradient */}
          <div
            className="absolute bottom-0 left-0 right-0 h-16 pointer-events-none"
            style={{
              background:
                "linear-gradient(180deg, transparent 0%, rgba(46, 27, 61, 0.82) 50%, rgba(35, 24, 62, 1) 100%)",
            }}
          />
        </div>
      </div>

      <style>{`
        /* Hide scrollbar for Chrome, Safari and Opera */
        .h-full.overflow-y-auto::-webkit-scrollbar {
          display: none;
        }
      `}</style>

      <BottomNav />
    </div>
  );
}
