// components/dashboard/right-sidebar.tsx
"use client";

import React, { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { useDispatch, useSelector } from "react-redux";
import { usePathname, useRouter } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  TrendingUp,
  ChevronRight,
  Settings,
  Sparkles,
  FileText,
  Shield,
  Users,
} from "lucide-react";
import { RootState } from "@/lib/store/store";
import {
  topFiveCategories,
  topIdeaCreators,
  postsForHomePage,
} from "@/lib/api/client";
import {
  setSelectedCategory,
  setShowAllTrendingPosts,
  setTrendingPosts,
  setAllTrendingPosts,
} from "@/lib/store/slices/userSlice";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

const categoryColors = [
  "bg-primary/20 text-primary",
  "bg-accent/20 text-accent",
  "bg-chart-3/20 text-chart-3",
  "bg-chart-4/20 text-chart-4",
  "bg-chart-5/20 text-chart-5",
  "bg-secondary/50 text-foreground",
];

const innovatorColors = [
  "bg-primary",
  "bg-accent",
  "bg-chart-3",
  "bg-chart-4",
  "bg-chart-5",
  "bg-secondary",
];

const getUserTypeBadge = (creator: any) => {
  if (
    creator.userType === "business" ||
    creator.isBusinessUser ||
    creator.accountType === "business"
  ) {
    return { label: "Business", color: "bg-amber-500 text-white" };
  }

  if (
    creator.userType === "investor" ||
    creator.isInvestor ||
    creator.accountType === "investor"
  ) {
    return { label: "Investor", color: "bg-emerald-500 text-white" };
  }

  return { label: "Innovator", color: "bg-primary text-white" };
};

const getInitials = (name: string | null | undefined) => {
  if (!name || typeof name !== "string" || name.trim() === "") return "U";
  return name
    .split(" ")
    .map((word) => word[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

const timeAgo = (date: string) => {
  if (!date) return "Just now";

  const now = new Date();
  const past = new Date(date);

  if (isNaN(past.getTime())) return "Just now";

  const diffMs = now.getTime() - past.getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);
  const diffMonth = Math.floor(diffDay / 30);
  const diffYear = Math.floor(diffMonth / 12);

  if (diffSec < 60) return "Just now";
  if (diffMin < 60) return `${diffMin} min ago`;
  if (diffHour < 24) return `${diffHour} hour${diffHour > 1 ? "s" : ""} ago`;
  if (diffDay < 30) return `${diffDay} day${diffDay > 1 ? "s" : ""} ago`;
  if (diffMonth < 12)
    return `${diffMonth} month${diffMonth > 1 ? "s" : ""} ago`;
  return `${diffYear} year${diffYear > 1 ? "s" : ""} ago`;
};

const CategorySkeleton = () => (
  <div className="rounded-2xl glass glass-border p-5">
    <div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-4"></div>
    <div className="flex flex-wrap gap-2">
      {[...Array(5)].map((_, i) => (
        <div
          key={i}
          className="h-8 w-20 bg-gray-200 dark:bg-gray-700 rounded-xl animate-pulse"
        ></div>
      ))}
    </div>
  </div>
);

const TrendingSkeleton = () => (
  <div className="rounded-2xl glass glass-border p-5">
    <div className="flex justify-between items-center mb-4">
      <div className="flex items-center gap-2">
        <div className="h-4 w-4 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
        <div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
      </div>
      <div className="h-3 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
    </div>
    <div className="space-y-4">
      {[...Array(3)].map((_, i) => (
        <div key={i} className="space-y-2">
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
            <div className="h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
            <div className="h-3 w-8 bg-gray-200 dark:bg-gray-700 rounded animate-pulse ml-auto"></div>
          </div>
          <div className="h-3 w-full bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
          <div className="h-2 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
        </div>
      ))}
    </div>
  </div>
);

const TopCreatorsSkeleton = () => (
  <div className="rounded-2xl glass glass-border p-5">
    <div className="h-4 w-28 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-4"></div>
    <div className="flex items-center justify-center gap-3">
      {[...Array(4)].map((_, i) => (
        <div key={i} className="flex flex-col items-center gap-1">
          <div className="w-12 h-12 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
          <div className="h-3 w-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
        </div>
      ))}
    </div>
  </div>
);

export function RightSidebar() {
  const dispatch = useDispatch();
  const router = useRouter();
  const pathname = usePathname();

  const { accessToken, currentCustomer } = useSelector(
    (state: RootState) => state.user,
  );

  const customer = currentCustomer?.customer || currentCustomer;
  const userType = customer?.isBusinessUser
    ? "business"
    : customer?.isInvestor
      ? "investor"
      : "individual";

  const [trendingCategories, setTrendingCategories] = useState<any[]>([]);
  const [trendingPosts, setTrendingPostsState] = useState<any[]>([]);
  const [topCreators, setTopCreators] = useState<any[]>([]);
  const [loadingCategories, setLoadingCategories] = useState(true);
  const [loadingTrending, setLoadingTrending] = useState(true);
  const [loadingCreators, setLoadingCreators] = useState(true);

  let cachedCategories: any = null;
  let cachedTrendingPosts: any = null;
  let cachedCreators: any = null;
  let lastFetchTime = 0;
  const CACHE_DURATION = 5 * 60 * 1000;

  const fetchTrendingCategories = useCallback(async () => {
    if (!accessToken) return;

    if (cachedCategories && Date.now() - lastFetchTime < CACHE_DURATION) {
      setTrendingCategories(cachedCategories);
      setLoadingCategories(false);
      return;
    }

    try {
      const result = await topFiveCategories(
        accessToken,
        process.env.NEXT_PUBLIC_SECURITY_KEY,
      );
      if (result?.success) {
        cachedCategories = result.data || [];
        setTrendingCategories(cachedCategories);
      }
    } catch (error) {
      console.error("Error fetching categories:", error);
    } finally {
      setLoadingCategories(false);
    }
  }, [accessToken]);

  const fetchTrendingPosts = useCallback(async () => {
    if (!accessToken) return;

    if (cachedTrendingPosts && Date.now() - lastFetchTime < CACHE_DURATION) {
      setTrendingPostsState(cachedTrendingPosts);
      dispatch(setTrendingPosts(cachedTrendingPosts));
      setLoadingTrending(false);
      return;
    }

    try {
      setLoadingTrending(true);
      const result = await postsForHomePage(
        "most-liked",
        accessToken,
        "",
        1,
        5,
        process.env.NEXT_PUBLIC_SECURITY_KEY,
      );
      if (result?.success && result.posts?.length > 0) {
        let posts = result.posts;
        posts = posts.sort((a: any, b: any) => {
          const likesA = a.likes || a.counts?.likes || 0;
          const likesB = b.likes || b.counts?.likes || 0;
          return likesB - likesA;
        });
        const formattedPosts = posts.slice(0, 3).map((post: any) => ({
          _id: post._id,
          postID: post._id,
          description: post.description,
          media: post.attachments || [],
          counts: { likes: post.likes, dislikes: post.dislikes },
          customer: {
            _id: post.customerID?._id,
            fullName: post.customerID?.name,
            imageURL: post.customerID?.avatar,
            userName: post.customerID?.username,
            country: post.customerID?.country,
            countryFlag: post.customerID?.countryFlag,
          },
          timeAgo: post.timeAgo,
          likeCount: post.likes,
          dislikeCount: post.dislikes,
        }));
        cachedTrendingPosts = formattedPosts;
        lastFetchTime = Date.now();
        setTrendingPostsState(formattedPosts);
        dispatch(setTrendingPosts(formattedPosts));
      } else {
        setTrendingPostsState([]);
      }
    } catch (error) {
      console.error("Error fetching trending posts:", error);
    } finally {
      setLoadingTrending(false);
    }
  }, [accessToken, dispatch]);

  const fetchTopCreators = useCallback(async () => {
    if (!accessToken) return;

    if (cachedCreators && Date.now() - lastFetchTime < CACHE_DURATION) {
      setTopCreators(cachedCreators);
      setLoadingCreators(false);
      return;
    }

    try {
      const result = await topIdeaCreators(
        accessToken,
        process.env.NEXT_PUBLIC_SECURITY_KEY,
      );

      console.log("Top Creators Result:", result);
console.log("Blocked business user ID should be:", "69ce3fc9ec789111ec55db26");
console.log("Returned creators:", result?.topCreators?.map(c => ({ id: c._id, name: c.fullName, type: c.userType })));
      
      if (result?.success) {
        cachedCreators = result.topCreators || [];
        setTopCreators(cachedCreators);
      }
    } catch (error) {
      console.error("Error fetching creators:", error);
    } finally {
      setLoadingCreators(false);
    }
  }, [accessToken]);

  const handleCategoryClick = (category: any) => {
    const categoryData = {
      _id: category._id,
      mainCategoryName: category.mainCategoryName,
    };

    if (pathname !== "/home") {
      dispatch(setSelectedCategory(categoryData));
      router.push("/home");
    } else {
      if (currentCustomer?.selectedCategory?._id === category._id) {
        dispatch(setSelectedCategory(null));
      } else {
        dispatch(setSelectedCategory(categoryData));
      }
    }
  };

  // ✅ View All - NO LOADING STATE, NO REFRESH
  const handleViewAllTrending = useCallback(async () => {
    if (!accessToken) return;

    // Check if we already have trending posts in cache
    const existingPosts = trendingPosts.length > 0;
    
    if (existingPosts) {
      // If we already have posts, just show them without fetching
      dispatch(setAllTrendingPosts(trendingPosts));
      dispatch(setShowAllTrendingPosts(true));
      if (pathname !== "/home") {
        router.push("/home");
      }
      return;
    }

    // Only fetch if no posts exist
    try {
      const result = await postsForHomePage(
        "most-liked",
        accessToken,
        "",
        1,
        20,
        process.env.NEXT_PUBLIC_SECURITY_KEY,
      );
      
      if (result?.success && result.posts?.length > 0) {
        let posts = result.posts;
        posts = posts.sort((a: any, b: any) => {
          const likesA = a.likes || a.counts?.likes || 0;
          const likesB = b.likes || b.counts?.likes || 0;
          return likesB - likesA;
        });
        
        const formattedPosts = posts.map((post: any) => ({
          _id: post._id,
          postID: post._id,
          description: post.description,
          media: post.attachments || [],
          counts: { likes: post.likes, dislikes: post.dislikes },
          customer: {
            _id: post.customerID?._id,
            fullName: post.customerID?.name,
            imageURL: post.customerID?.avatar,
            userName: post.customerID?.username,
            country: post.customerID?.country,
            countryFlag: post.customerID?.countryFlag,
          },
          timeAgo: post.timeAgo,
          likeCount: post.likes,
          dislikeCount: post.dislikes,
        }));
        
        dispatch(setAllTrendingPosts(formattedPosts));
        dispatch(setShowAllTrendingPosts(true));
      }
    } catch (error) {
      console.error("Error fetching all trending posts:", error);
    }

    if (pathname !== "/home") {
      router.push("/home");
    }
  }, [accessToken, dispatch, pathname, router, trendingPosts]);

  const handlePostClick = (postId: string) => {
    router.push(`/idea/${postId}`);
  };

  useEffect(() => {
    if (accessToken) {
      fetchTrendingCategories();
      fetchTrendingPosts();
      fetchTopCreators();
    }
  }, [
    accessToken,
    fetchTrendingCategories,
    fetchTrendingPosts,
    fetchTopCreators,
  ]);

  const getCategoryColor = (index: number) => {
    return categoryColors[index % categoryColors.length];
  };

  const getInnovatorColor = (index: number) => {
    return innovatorColors[index % innovatorColors.length];
  };

  return (
    <aside className="sticky top-20 w-80 space-y-6 overflow-y-auto custom-scrollbar max-h-[calc(100vh-5rem)]">
      {loadingCategories ? (
        <CategorySkeleton />
      ) : trendingCategories.length > 0 ? (
        <div className="rounded-2xl glass glass-border p-5">
          <h3 className="mb-4 text-sm dark:text-white font-bold uppercase tracking-wider text-muted-foreground">
            Explore Categories
          </h3>
          <div className="flex flex-wrap gap-2">
            {trendingCategories.map((cat, index) => (
              <button
                key={cat._id}
                onClick={() => handleCategoryClick(cat)}
                className={`px-3 py-2 dark:text-white text-xs font-medium rounded-xl cursor-pointer transition-all hover:scale-105 ${
                  currentCustomer?.selectedCategory?._id === cat._id
                    ? "bg-primary text-primary-foreground"
                    : getCategoryColor(index)
                }`}
              >
                {cat.mainCategoryName}
              </button>
            ))}
          </div>
        </div>
      ) : null}

      {loadingCreators ? (
        <TopCreatorsSkeleton />
      ) : topCreators.length > 0 ? (
        <div className="rounded-2xl glass glass-border p-5">
          <h3 className="mb-4 text-sm dark:text-white font-bold uppercase tracking-wider text-muted-foreground">
            Top Contributors
          </h3>
          <div className="flex items-center justify-center gap-6">
            {topCreators.slice(0, 4).map((creator, idx) => {
              const badge = getUserTypeBadge(creator);

              return (
                <Link
                  key={creator._id || idx}
                  href={`/${creator.userName}`}
                  className="flex flex-col items-center gap-1.5 group cursor-pointer"
                >
                  <div className="relative">
                    {creator.imageURL && creator.imageURL.trim() !== "" ? (
                      <div className="w-12 h-12 rounded-full overflow-hidden ring-2 ring-border group-hover:ring-primary transition-all">
                        <Image
                          src={`${BASE_URL}/uploads/${creator.imageURL}`}
                          alt={creator.fullName || "User"}
                          width={48}
                          height={48}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    ) : (
                      <div
                        className={`flex h-12 w-12 items-center justify-center rounded-full ${getInnovatorColor(
                          idx,
                        )} text-white font-bold text-sm transition-transform group-hover:scale-110`}
                      >
                        {getInitials(creator.fullName)}
                      </div>
                    )}
                    <span
                      className={`absolute -top-1 -right-1 text-[8px] px-1.5 py-[2px] rounded-full shadow-sm ${badge.color}`}
                    >
                      {badge.label}
                    </span>
                  </div>
                  <span className="text-[10px] text-muted-foreground text-center truncate max-w-[60px]">
                    {creator.fullName?.split(" ")[0] || "User"}
                  </span>
                </Link>
              );
            })}
          </div>
        </div>
      ) : null}

      {loadingTrending ? (
        <TrendingSkeleton />
      ) : trendingPosts.length > 0 ? (
        <div className="rounded-2xl glass glass-border p-5">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <TrendingUp className="h-4 w-4 text-accent" />
              <h3 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">
                Trending Now
              </h3>
            </div>
            <button
              onClick={handleViewAllTrending}
              className="flex cursor-pointer items-center gap-1 text-xs font-medium text-primary hover:underline"
            >
              View All <ChevronRight className="h-3 w-3" />
            </button>
          </div>

          <div className="space-y-4">
            {trendingPosts.map((post, idx) => (
              <div
                key={post._id || idx}
                onClick={() => handlePostClick(post._id || post.postID)}
                className="group cursor-pointer rounded-xl bg-secondary/30 p-3 transition-all hover:bg-secondary/50"
              >
                <div className="flex items-center gap-2 mb-2">
                  <Avatar className="h-6 w-6">
                    {post.customer?.imageURL ? (
                      <AvatarImage
                        src={`${BASE_URL}/uploads/${post.customer.imageURL}`}
                        alt={post.customer?.fullName || "User"}
                      />
                    ) : null}
                    <AvatarFallback className="text-[10px] bg-primary/20 text-primary font-bold">
                      {getInitials(post.customer?.fullName)}
                    </AvatarFallback>
                  </Avatar>
                  <span className="text-sm font-medium text-foreground truncate max-w-[100px]">
                    {post.customer?.fullName?.split(" ")[0] || "User"}
                  </span>
                   {/* ✅ FIX: Show flag image, not URL text */}
  {post.customer?.countryFlag && (
    <img 
      src={post.customer.countryFlag}
      alt="flag"
      className="w-4 h-4  object-contain "
      onError={(e) => {
        // If image fails to load, hide it
        (e.target as HTMLImageElement).style.display = 'none';
      }}
    />
  )}
                  <span className="ml-auto text-[10px] text-muted-foreground">
                    {post.timeAgo}
                  </span>
                </div>
                <p className="text-sm dark:text-white text-muted-foreground line-clamp-2">
                  {post.description || "No description"}
                </p>
                <div className="mt-2 flex items-center gap-3 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Image
                      src="/icons/like_unfilled.svg"
                      alt="like"
                      width={14}
                      height={14}
                      className="dark:bg-white rounded-full"
                    />
                    {post.likeCount || 0}
                  </span>
                  <span className="flex items-center gap-1">
                    <Image
                      src="/icons/dislike_unfilled.svg"
                      alt="dislike"
                      width={14}
                      height={14}
                      className="dark:bg-white rounded-full"
                    />
                    {post.dislikeCount || 0}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : null}

      <div className="rounded-2xl glass glass-border p-5">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-bold dark:text-white uppercase tracking-wider text-muted-foreground">
            Quick Links
          </h3>
        </div>
        <div className="space-y-2 ">
          <Link
            href="/get-started"
            className="flex w-full items-center dark:text-white gap-3 rounded-xl px-3 py-2.5 text-sm text-primary hover:bg-primary/10 transition-all"
          >
            <Sparkles className="h-4 w-4" />
            Get Started Guide
          </Link>
          <Link
            href="/settings/profile"
            className="flex w-full items-center dark:text-white gap-3 rounded-xl px-3 py-2.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-all"
          >
            <Settings className="h-4 w-4" />
            Profile Settings
          </Link>
          <Link
            href="/terms-and-conditions"
            target="_blank"
            rel="noopener noreferrer"
            className="flex w-full items-center dark:text-white gap-3 rounded-xl px-3 py-2.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-all"
          >
            <FileText className="h-4 w-4" />
            Terms & Conditions
          </Link>
          <Link
            href="/privacy-policy"
            target="_blank"
            rel="noopener noreferrer"
            className="flex w-full items-center dark:text-white gap-3 rounded-xl px-3 py-2.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-all"
          >
            <Shield className="h-4 w-4" />
            Privacy Policy
          </Link>
          <Link
            href="/community-guidelines"
            target="_blank"
            rel="noopener noreferrer"
            className="flex w-full items-center dark:text-white gap-3 rounded-xl px-3 py-2.5 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-all"
          >
            <Users className="h-4 w-4" />
            Community Guidelines
          </Link>
        </div>
      </div>
    </aside>
  );
}