"use client"

import { useEffect, useState, useRef } from "react"
import { useRouter, usePathname } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Cpu,
  Plus,
  Settings,
  LogOut,
  Wrench,
  Users,
  BookOpen,
  Star,
  Heart,
  MessageCircle,
  Share,
  Edit,
  Copy,
  Eye,
  Calendar,
  Trophy,
  Trash2,
} from "lucide-react"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"

import { useAuth } from "@/contexts/supabase-auth-context"
import { mockBuilds } from "@/lib/mock-data"
import { supabase } from "@/lib/supabase"
import { swal } from "@/lib/sweetalert"
import { time } from "console"
import { formatCurrency } from "@/lib/currency"

export default function DashboardPage() {
  const { user, logout, isLoading } = useAuth()
  const router = useRouter()
  const pathname = usePathname()
  const [activeTab, setActiveTab] = useState("overview")

  const [userBuilds, setUserBuilds] = useState<any[]>([])
  const [likedBuilds, setLikedBuilds] = useState<any[]>([])
  const [totalLikes, setTotalLikes] = useState(0)
  const [loadingBuilds, setLoadingBuilds] = useState(false)
  const [loadingLikes, setLoadingLikes] = useState(false)
  const [recentActivity, setRecentActivity] = useState<any[]>([]);
  const [followers, setFollowers] = useState<any[]>([]);
  const [following, setFollowing] = useState<any[]>([]);
  const [deleteBuildId, setDeleteBuildId] = useState<number | null>(null)
  const [sharePopupOpen, setSharePopupOpen] = useState(false)
  const [shareUrl, setShareUrl] = useState("")
  const [pageLoading, setPageLoading] = useState(true)
  const [topBuilds, setTopBuilds] = useState<any[]>([]);
  const [followModalOpen, setFollowModalOpen] = useState(false);
  const [followTab, setFollowTab] = useState<"followers" | "following">("following");
  const [likedTopBuildIds, setLikedTopBuildIds] = useState<number[]>([]);
  const [deletePopupOpen, setDeletePopupOpen] = useState(false)
  const [likeOwnPopupOpen, setLikeOwnPopupOpen] = useState(false);

  const topUserBuildsScrollRef = useRef<HTMLDivElement>(null);
  const topCommunityBuildsScrollRef = useRef<HTMLDivElement>(null);
  const [pauseAutoScroll, setPauseAutoScroll] = useState(false);

  // Auto-scroll for "Your Top Builds" and "Top Community Builds" (pauses on hover)
  useEffect(() => {
    if (pauseAutoScroll) return;
    const scrollStep = 1;
    const scrollInterval = 55;
    const run = (el: HTMLDivElement | null) => {
      if (!el || el.scrollHeight <= el.clientHeight) return;
      el.scrollTop += scrollStep;
      if (el.scrollTop >= el.scrollHeight - el.clientHeight - 1) {
        el.scrollTop = 0;
      }
    };
    const t = setInterval(() => {
      run(topUserBuildsScrollRef.current);
      run(topCommunityBuildsScrollRef.current);
    }, scrollInterval);
    return () => clearInterval(t);
  }, [userBuilds.length, topBuilds.length, pauseAutoScroll]);

  function timeAgo(dateString: string | null) {
    if (!dateString) return "-";
    const now = new Date();
    const date = new Date(dateString);
    const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
    if (seconds < 5) return "just now";
    const intervals: { [key: string]: number } = {
      year: 31536000,
      month: 2592000,
      week: 604800,
      day: 86400,
      hour: 3600,
      minute: 60,
      second: 1,
    };
    for (const key in intervals) {
      const interval = Math.floor(seconds / intervals[key]);
      if (interval >= 1) {
        return `${interval} ${key}${interval !== 1 ? "s" : ""} ago`;
      }
    }
    return "just now";
  }
  
  useEffect(() => {
    if (isLoading) return
    if (!user) router.push("/login")
  }, [isLoading, user, router])

  useEffect(() => {
    if (isLoading || !user) return
    loadDashboard()
    loadTopBuilds().then(async (res) => {
      setTopBuilds(res);

      if (!user || !res.length) return;

      const buildIds = res.map((b: any) => b.build_id);

      const { data } = await supabase
        .from("build_likes")
        .select("build_id")
        .eq("user_id", user.user_id)
        .in("build_id", buildIds);

      if (data) {
        setLikedTopBuildIds(data.map(d => d.build_id));
      }
    });
  }, [isLoading, user])

  const loadDashboard = async () => {
    setPageLoading(true)
    try {
      const userId = user.user_id
      const [
        buildsRes,
        totalLikesRes,
        likedRes,
        followersRes,
        followingRes,
        commentsRes,
      ] = await Promise.all([
        supabase
          .from("builds")
          .select("*, build_types(type_name)")
          .eq("user_id", userId)
          .order("date_created", { ascending: false }),
        supabase
          .from("build_likes")
          .select("builds!inner(build_id)", { count: "exact", head: true })
          .eq("builds.user_id", userId),
        supabase
          .from("build_likes")
          .select("*, builds(*, build_types(type_name))")
          .eq("user_id", userId)
          .order("created_at", { ascending: false }),
        supabase
          .from("followers")
          .select(`
            follower_user_id,
            users!fk_follower (
              user_id,
              user_name,
              avatar_url
            )
          `)
          .eq("user_id", userId),
        supabase
          .from("followers")
          .select("*")
          .eq("follower_user_id", userId),
        supabase
          .from("build_comments")
          .select("*, builds(build_name)")
          .eq("user_id", userId),
      ])
      // BUILDS + STATS
      const buildsWithStats = await fetchBuildsWithStats(buildsRes.data || [])
      setUserBuilds(buildsWithStats)
      // TOTAL LIKES RECEIVED
      setTotalLikes(totalLikesRes.count ?? 0)
      // LIKED BUILDS
      if (likedRes.data) {
        const likedBuildsOnly = likedRes.data.map(r => r.builds)
        const likedWithStats = await fetchBuildsWithStats(likedBuildsOnly)
        setLikedBuilds(
          likedRes.data.map((row, i) => ({
            build: likedWithStats[i],
            liked_at: row.created_at,
          }))
        )
      }
      // FOLLOWERS
      setFollowers(
        (followersRes.data || []).map((f: any) => ({
          user_id: f.users.user_id,
          username: f.users.user_name,
          avatar: f.users.avatar_url,
        }))
      )
      // FOLLOWING (with user info)
      if (followingRes.data?.length) {
        const ids = followingRes.data.map(f => f.user_id)
        const { data: users } = await supabase
          .from("users")
          .select("user_id, user_name, avatar_url")
          .in("user_id", ids)
        setFollowing(
          followingRes.data.map(f => {
            const u = users?.find(x => x.user_id === f.user_id)
            return {
              ...f,
              username: u?.user_name || "Unknown",
              avatar: u?.avatar_url || null,
            }
          })
        )
      } else {
        setFollowing([])
      }
      // RECENT ACTIVITY (built once, correctly)
      const activity: any[] = []
      buildsWithStats.forEach(b =>
        activity.push({
          id: `build_${b.build_id}`,
          description: `You Created '${b.build_name}'`,
          rawTime: b.date_created,
          time: timeAgo(b.date_created),
          icon: Plus,
        })
      )
      likedRes.data?.forEach(l =>
        activity.push({
          id: `like_${l.build_id}`,
          description: `You Liked '${l.builds.build_name}'`,
          rawTime: l.created_at,
          time: timeAgo(l.created_at),
          icon: Heart,
        })
      )
      commentsRes.data?.forEach(c =>
        activity.push({
          id: `comment_${c.comment_id}`,
          description: `You Commented on '${c.builds?.build_name}'`,
          rawTime: c.created_at,
          time: timeAgo(c.created_at),
          icon: MessageCircle,
        })
      )
      activity.sort(
        (a, b) => new Date(b.rawTime).getTime() - new Date(a.rawTime).getTime()
      )
      setRecentActivity(activity)
    } catch (err) {
      console.error("Dashboard load failed:", err)
    } finally {
      setPageLoading(false)
    }
  }

  async function loadTopBuilds() {
    const { data, error } = await supabase
      .rpc("get_top_builds", { limit_count: 3 }); // argument matches the function

    if (error) {
      console.error("RPC Error:", error);
      return [];
    }

    return data;
  }

  const fetchBuildsWithStats = async (builds: any[]) => {
    if (!builds || builds.length === 0) return builds;

    const buildIds = builds.map(b => b.build_id);
    const userIds = builds.map(b => b.user_id);

    // Likes
    const { data: likesData } = await supabase
      .from("build_likes")
      .select("build_id")
      .in("build_id", buildIds);

    // Views
    const { data: viewsData } = await supabase
      .from("build_views")
      .select("build_id")
      .in("build_id", buildIds);

    // Comments
    const { data: commentsData } = await supabase
      .from("build_comments")
      .select("build_id")
      .in("build_id", buildIds);

    // Users info
    const { data: usersData } = await supabase
      .from("users")
      .select("user_id, user_name, avatar_url")
      .in("user_id", userIds);

    // Map counts
    const likeCountMap: Record<number, number> = {};
    const viewCountMap: Record<number, number> = {};
    const commentCountMap: Record<number, number> = {};

    buildIds.forEach(id => {
      likeCountMap[id] = 0;
      viewCountMap[id] = 0;
      commentCountMap[id] = 0;
    });

    likesData?.forEach(like => (likeCountMap[like.build_id]++));
    viewsData?.forEach(view => (viewCountMap[view.build_id]++));
    commentsData?.forEach(comment => (commentCountMap[comment.build_id]++));

    return builds.map(build => {
      const user = usersData?.find(u => u.user_id === build.user_id);
      return {
        ...build,
        likes: likeCountMap[build.build_id] || 0,
        views: viewCountMap[build.build_id] || 0,
        comments: commentCountMap[build.build_id] || 0,
        user_name: user?.user_name || "Unknown",
        avatar_url: user?.avatar_url || null,
      };
    });
  };


  const toggleTopBuildLike = async (buildId: number) => {
    if (!user) return;

    const build = topBuilds.find(b => b.build_id === buildId);
    if (!build) return;

    // 🚨 Prevent liking own build
    if (build.user_id === user.user_id) {
      setLikeOwnPopupOpen(true);
      return;
    }

    const isLiked = likedTopBuildIds.includes(buildId);

    if (isLiked) {
      await supabase
        .from("build_likes")
        .delete()
        .eq("build_id", buildId)
        .eq("user_id", user.user_id);

      setLikedTopBuildIds(prev => prev.filter(id => id !== buildId));

      setTopBuilds(prev =>
        prev.map(b =>
          b.build_id === buildId
            ? { ...b, likes: Math.max((b.likes || 1) - 1, 0) }
            : b
        )
      );
    } else {
      await supabase
        .from("build_likes")
        .insert({
          build_id: buildId,
          user_id: user.user_id,
        });

      setLikedTopBuildIds(prev => [...prev, buildId]);

      setTopBuilds(prev =>
        prev.map(b =>
          b.build_id === buildId
            ? { ...b, likes: (b.likes || 0) + 1 }
            : b
        )
      );

      // Send push notification to the build owner (non-blocking)
      try {
        const payload = {
          userId: build.user_id,
          notificationType: 'buildLike',
          title: `${user.user_name} liked your build`,
          body: `${user.user_name} liked ${build.build_name}`,
          url: `/builds/${buildId}`,
        };

        console.log('Sending push notification payload:', payload);

        const res = await fetch('/api/notifications/send', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });

        const sendResult = await res.json();
        console.log('Push send result:', sendResult);
      } catch (err) {
        console.error('Error sending push notification after like:', err);
      }
    }
  };

  const handleUnlikeBuild = async (buildId: number) => {
    if (!user) return;

    const { error } = await supabase
      .from("build_likes")
      .delete()
      .eq("build_id", buildId)
      .eq("user_id", user.user_id);

    if (error) {
      console.error("Error unliking build:", error);
      return;
    }

    // Remove from liked list immediately (optimistic UI)
    setLikedBuilds(prev => prev.filter(row => row.build.build_id !== buildId));

    // Update total likes stat
    setTotalLikes(prev => Math.max(prev - 1, 0));
  };

  const topUserBuilds = [...userBuilds]
    .sort((a, b) => b.likes - a.likes)
    .slice(0, 3);


  if (isLoading || pageLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center">
        <div className="text-center">
          <Cpu className="h-12 w-12 text-blue-600 mx-auto mb-4 animate-pulse" />
          <p className="text-slate-600 dark:text-slate-400">Loading...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  const handleDeleteBuild = async () => {
    if (!deleteBuildId) return

    const { error } = await supabase
      .from("builds")
      .delete()
      .eq("build_id", deleteBuildId)
      .eq("user_id", user.user_id)

    if (error) {
      console.error("Error deleting build:", error)
      swal.error("Failed to delete build", "Please try again.")
      return
    }

    setUserBuilds((prev) => prev.filter((b) => b.build_id !== deleteBuildId))
    setDeleteBuildId(null)
  }

  // Dynamic achievements based on Supabase data
  const achievements = [
    {
      id: 1,
      name: "First Build",
      description: "Created your first PC build",
      earned: userBuilds.length >= 1,
      icon: Wrench,
    },
    {
      id: 2,
      name: "Community Favorite",
      description: "Received 100+ likes",
      earned: totalLikes >= 100,
      icon: Heart,
    },
    {
      id: 3,
      name: "Build Master",
      description: "Created 10+ builds",
      earned: userBuilds.length >= 10,
      icon: Trophy,
    },
    {
      id: 4,
      name: "Guide Follower",
      description: "Completed a build guide",
      earned: true, // still static
      icon: BookOpen,
    },
  ]

  return (
    
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      <div className="container mx-auto px-4 py-8">
        <div className="mb-8">
          <div className="mb-6">
            <div>
              <h2 className="text-3xl font-bold text-slate-900 dark:text-white mb-2">Dashboard</h2>
              <p className="text-slate-600 dark:text-slate-400">
                Manage your builds, track your progress, and connect with the community.
              </p>
            </div>
          </div>

          {/* User Stats Cards */}
          <div className="grid md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
            <Link href="/mybuilds">
              <Card
              className="border-slate-200 dark:border-slate-700 cursor-pointer hover:shadow-md transition"
              >
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-slate-600 dark:text-slate-400">Total Builds</p>
                      <p className="text-2xl font-bold text-slate-900 dark:text-white">{userBuilds.length}</p>
                    </div>
                    <Wrench className="h-8 w-8 text-blue-600" />
                  </div>
                </CardContent>
              </Card>
            </Link>
            

            <Card className="border-slate-200 dark:border-slate-700 hover:shadow-md transition">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-slate-600 dark:text-slate-400">Total Likes</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">{totalLikes}</p>
                  </div>
                  <Heart className="h-8 w-8 text-red-500" />
                </div>
              </CardContent>
            </Card>

            <Card
              className="border-slate-200 dark:border-slate-700 cursor-pointer hover:shadow-md transition"
              onClick={() => {
                setFollowTab("following")
                setFollowModalOpen(true)
              }}
            >
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-slate-600 dark:text-slate-400">Following</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">
                      {following.length}
                    </p>
                  </div>
                  <Users className="h-8 w-8 text-blue-600" />
                </div>
              </CardContent>
            </Card>

            <Card
              className="border-slate-200 dark:border-slate-700 cursor-pointer hover:shadow-md transition"
              onClick={() => {
                setFollowTab("followers")
                setFollowModalOpen(true)
              }}
            >
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-slate-600 dark:text-slate-400">Followers</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">
                      {followers.length}
                    </p>
                  </div>
                  <Users className="h-8 w-8 text-green-600" />
                </div>
              </CardContent>
            </Card>

            <Card className="border-slate-200 dark:border-slate-700 hover:shadow-md transition">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-slate-600 dark:text-slate-400">Achievements</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">
                      {achievements.filter((a) => a.earned).length}/{achievements.length}
                    </p>
                  </div>
                  <Trophy className="h-8 w-8 text-yellow-600" />
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-5 [&_[role=tab]]:transition-colors [&_[role=tab]]:cursor-pointer [&_[role=tab]]:hover:bg-white/80 [&_[role=tab]]:hover:shadow-sm dark:[&_[role=tab]]:hover:bg-slate-700/60 [&_[role=tab]]:data-[state=inactive]:hover:text-foreground">
            <TabsTrigger value="overview">Overview</TabsTrigger>
            <TabsTrigger value="builds">My Builds</TabsTrigger>
            <TabsTrigger value="liked">Liked Builds</TabsTrigger>
            <TabsTrigger value="achievements">Achievements</TabsTrigger>
            <TabsTrigger value="activity">Activity</TabsTrigger>
          </TabsList>

          <TabsContent value="overview" className="space-y-6">
            <div className="grid lg:grid-cols-3 gap-6">
              {topUserBuilds.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>Your Top Builds</CardTitle>
                    <CardDescription>Your most liked builds</CardDescription>
                  </CardHeader>

                  <CardContent className="p-0">
                    <div
                      ref={topUserBuildsScrollRef}
                      className="overflow-y-auto max-h-70 custom-scrollbar px-6 pb-6"
                      onMouseEnter={() => setPauseAutoScroll(true)}
                      onMouseLeave={() => setPauseAutoScroll(false)}
                    >
                      <div className="space-y-4 pr-2">
                      {topUserBuilds.map((build, index) => (
                        <Card
                          key={build.build_id}
                          className="border-slate-200 dark:border-slate-700 hover:shadow-md transition"
                        >
                          <CardHeader className="pb-2">
                            <div className="flex items-start justify-between">
                              <div>
                                <CardTitle className="text-md">{build.build_name}</CardTitle>
                                <CardDescription className="text-sm text-slate-600 dark:text-slate-400">
                                  {build.description || "No description"}
                                </CardDescription>
                                <div className="mt-2 flex items-center gap-2">
                                  <Link href="/profile" className="flex items-center gap-2">
                                    <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                                      {build.avatar_url ? (
                                        <AvatarImage src={build.avatar_url} alt={build.username} />
                                      ) : (
                                        <AvatarFallback>{build.user_name?.[0] || "U"}</AvatarFallback>
                                      )}
                                    </Avatar>
                                    <span className="text-sm text-slate-700 dark:text-slate-300">{build.user_name || "Unknown"}</span>
                                  </Link>
                                </div>
                              </div>
                              <div className="flex flex-col items-end gap-1 text-xs text-slate-500">
                                <Badge variant="secondary">{formatCurrency(build.total_price || 0)}</Badge>
                                <div className="flex items-center gap-1">
                                  <Calendar className="h-3 w-3" />
                                  <span>{build.date_created ? new Date(build.date_created).toLocaleDateString() : "-"}</span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Eye className="h-3 w-3" />
                                  <span>{(build.views || 0).toLocaleString()} views</span>
                                </div>
                              </div>
                            </div>
                          </CardHeader>

                          <CardContent className="flex items-center text-sm text-slate-600 dark:text-slate-400">
                            <div className="flex items-center gap-4">
                              <div className="flex items-center gap-1">
                                <Heart className="h-4 w-4" />
                                {build.likes}
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-blue-500"
                                  asChild
                                >
                                  <Link href={`/builds/${build.build_id}`}>
                                    <MessageCircle className="h-4 w-4" />
                                    <span>{build.comments || 0}</span>
                                  </Link>
                                </Button>
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-green-500"
                                  onClick={() => {
                                    if (typeof window !== "undefined") {
                                      const url = `${window.location.origin}/builder?share=${build.build_id}`;
                                      setShareUrl(url);
                                      setSharePopupOpen(true);
                                    }
                                  }}
                                >
                                  <Share className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                          </CardContent>

                          <div className="flex gap-2 mt-2 px-6 pb-4">
                            <Button 
                              size="sm" 
                              variant="outline" 
                              asChild 
                              className="flex-1 bg-transparent"
                            >
                              <Link href={`/builder?edit=${build.build_id}`} className="flex items-center justify-center">
                                <Edit className="h-4 w-4 mr-2" />
                                Edit
                              </Link>
                            </Button>

                            <Button 
                              size="sm" 
                              variant="outline" 
                              asChild 
                              className="flex-1 bg-transparent"
                            >
                              <Link href={`/builds/${build.build_id}`} className="flex items-center justify-center">
                                <Eye className="h-4 w-4 mr-2" />
                                View
                              </Link>
                            </Button>
                          </div>
                        </Card>
                      ))}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Top Community Builds Card */}
              <Card>
                <CardHeader>
                  <CardTitle>Top Community Builds</CardTitle>
                  <CardDescription>Most liked builds in the community</CardDescription>
                </CardHeader>
                <CardContent className="p-0">
                  {topBuilds.length === 0 ? (
                    <p className="text-sm text-slate-500 dark:text-slate-400 px-6 pb-6">
                      No builds available yet.
                    </p>
                  ) : (
                    <div
                      ref={topCommunityBuildsScrollRef}
                      className="overflow-y-auto max-h-70 custom-scrollbar px-6 pb-6"
                      onMouseEnter={() => setPauseAutoScroll(true)}
                      onMouseLeave={() => setPauseAutoScroll(false)}
                    >
                    <div className="space-y-4 pr-2">
                      {topBuilds.map((build: any) => {
                        const isTopCommunityBuildLiked = likedTopBuildIds.includes(build.build_id);
                        return (
                          <Card
                          key={build.build_id}
                          className="border-slate-200 dark:border-slate-700 hover:shadow-md transition"
                        >
                          <CardHeader className="pb-2">
                            <div className="flex items-start justify-between">
                              <div>
                                <CardTitle className="text-md">{build.build_name}</CardTitle>
                                <CardDescription className="text-sm text-slate-600 dark:text-slate-400">
                                  {build.description || "No description"}
                                </CardDescription>
                                <div className="mt-2 flex items-center gap-2">
                                  <Link href={`/profile/${build.user_id}`} className="flex items-center gap-2">
                                    <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                                      {build.avatar_url ? (
                                        <AvatarImage src={build.avatar_url} alt={build.username} />
                                      ) : (
                                        <AvatarFallback>{build.user_name?.[0] || "U"}</AvatarFallback>
                                      )}
                                    </Avatar>
                                    <span className="text-sm text-slate-700 dark:text-slate-300">{build.user_name || "Unknown"}</span>
                                  </Link>
                                </div>
                              </div>
                              <div className="flex flex-col items-end gap-1 text-xs text-slate-500">
                                <Badge variant="secondary">{formatCurrency(build.total_price || 0)}</Badge>
                                <div className="flex items-center gap-1">
                                  <Calendar className="h-3 w-3" />
                                  <span>{build.date_created ? new Date(build.date_created).toLocaleDateString() : "-"}</span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Eye className="h-3 w-3" />
                                  <span>{(build.views || 0).toLocaleString()} views</span>
                                </div>
                              </div>
                            </div>

                        
                          </CardHeader>
                          <CardContent className="flex items-center gap-4 text-sm text-slate-600 dark:text-slate-400">
                            <div className="flex items-center gap-4">
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className={`h-auto p-0 flex items-center gap-1 text-sm transition-colors ${
                                    isTopCommunityBuildLiked
                                      ? "text-red-500 hover:text-red-600"
                                      : "text-slate-500 hover:text-red-500"
                                  }`}
                                  onClick={() => toggleTopBuildLike(build.build_id)}
                                >
                                  <Heart className={`h-4 w-4 ${isTopCommunityBuildLiked ? "fill-current" : ""}`} />
                                  <span>{build.likes || 0}</span>
                                </Button>
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-blue-500"
                                  asChild
                                >
                                  <Link href={`/builds/${build.build_id}`}>
                                    <MessageCircle className="h-4 w-4" />
                                    <span>{build.comments || 0}</span>
                                  </Link>
                                </Button>
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-green-500"
                                  onClick={() => {
                                    if (typeof window !== "undefined") {
                                      const url = `${window.location.origin}/builder?share=${build.build_id}`;
                                      setShareUrl(url);
                                      setSharePopupOpen(true);
                                    }
                                  }}
                                >
                                  <Share className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                          </CardContent>
                          <div className="flex gap-2 mt-2 px-6 pb-4">
                            <Button 
                              size="sm" 
                              variant="outline" 
                              asChild 
                              className="flex-1 bg-transparent"
                            >
                              <Link href={`/builder?edit=${build.build_id}`} className="flex items-center justify-center">
                                <Edit className="h-4 w-4 mr-2" />
                                Edit
                              </Link>
                            </Button>

                            <Button 
                              size="sm" 
                              variant="outline" 
                              asChild 
                              className="flex-1 bg-transparent"
                            >
                              <Link href={`/builds/${build.build_id}`} className="flex items-center justify-center">
                                <Eye className="h-4 w-4 mr-2" />
                                View
                              </Link>
                            </Button>
                          </div>
                        </Card>
                        )
                      })}
                    </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              <Card className="flex flex-col h-full">
                <CardHeader>
                  <CardTitle>Recent Activity</CardTitle>
                  <CardDescription>Your recent activities</CardDescription>
                </CardHeader>
                <CardContent className="overflow-y-auto max-h-70 custom-scrollbar">
                  <div className="space-y-4">
                    {recentActivity.slice(0, 5).map((activity) => (
                      <div key={activity.id} className="flex items-start gap-3">
                        <activity.icon className="h-4 w-4 text-slate-500 mt-1" />
                        <div className="flex-1">
                          <p className="text-sm text-slate-900 dark:text-white">{activity.description}</p>
                          <p className="text-xs text-slate-500">{activity.time}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          <TabsContent value="builds" className="space-y-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>My Builds ({userBuilds.length})</CardTitle>
                    <CardDescription>Your saved PC configurations</CardDescription>
                  </div>
                  <Button asChild>
                    <Link href="/builder">
                      <Plus className="h-4 w-4 mr-2" />
                      New Build
                    </Link>
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                {userBuilds.length === 0 ? (
                  <div className="text-center py-12">
                    <Wrench className="h-12 w-12 text-slate-400 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-slate-900 dark:text-white mb-2">No builds yet</h3>
                    <p className="text-slate-600 dark:text-slate-400 mb-4">
                      Start building your first PC configuration
                    </p>
                    <Button asChild>
                      <Link href="/builder">Create Your First Build</Link>
                    </Button>
                  </div>
                ) : (
                  <div className="grid md:grid-cols-2 gap-6">
                    {userBuilds.slice(0, 4).map((build) => (
                      <Card key={build.build_id} className="border-slate-200 dark:border-slate-700 hover:shadow-lg transition">
                        <CardHeader className="pb-3">
                          <div className="flex items-start justify-between">
                            <div>
                              <CardTitle className="text-md">{build.build_name}</CardTitle>
                              <CardDescription className="text-sm text-slate-600 dark:text-slate-400">
                                {build.description || "No description"}
                              </CardDescription>
                              <div className="mt-2 flex items-center gap-2">
                                <Link href="/profile" className="flex items-center gap-2">
                                  <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                                    {build.avatar_url ? (
                                      <AvatarImage src={build.avatar_url} alt={build.username} />
                                    ) : (
                                      <AvatarFallback>{build.user_name?.[0] || "U"}</AvatarFallback>
                                    )}
                                  </Avatar>
                                  <span className="text-sm text-slate-700 dark:text-slate-300">{build.user_name || "Unknown"}</span>
                                </Link>
                              </div>
                            </div>
                            <div className="flex flex-col items-end gap-1 text-xs text-slate-500">
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-7 w-7 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20"
                                onClick={() => {
                                  setDeleteBuildId(build.build_id)
                                  setDeletePopupOpen(true)
                                }}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>                              
                              <Badge variant="secondary">{formatCurrency(build.total_price || 0)}</Badge>
                              <div className="flex items-center gap-1">
                                <Calendar className="h-3 w-3" />
                                <span>{build.date_created ? new Date(build.date_created).toLocaleDateString() : "-"}</span>
                              </div>
                              <div className="flex items-center gap-1">
                                <Eye className="h-3 w-3" />
                                <span>{(build.views || 0).toLocaleString()} views</span>
                              </div>
                            </div>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-4">
                          <div className="flex flex-wrap gap-1">
                            {build.build_types?.type_name && (
                              <Badge variant="outline" className="text-xs">
                                {build.build_types.type_name}
                              </Badge>
                            )}
                          </div>

                          <div className="flex items-center justify-between text-sm text-slate-600 dark:text-slate-400">
                            <div className="flex items-center gap-4">
                              <div className="flex items-center gap-1">
                                <Heart className="h-4 w-4" />
                                {build.likes}
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-blue-500"
                                  asChild
                                >
                                  <Link href={`/builds/${build.build_id}`}>
                                    <MessageCircle className="h-4 w-4" />
                                    <span>{build.comments || 0}</span>
                                  </Link>
                                </Button>
                              </div>
                              <div className="flex items-center gap-1">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 text-slate-500 hover:text-green-500"
                                  onClick={() => {
                                    if (typeof window !== "undefined") {
                                      const url = `${window.location.origin}/builder?share=${build.build_id}`;
                                      setShareUrl(url);
                                      setSharePopupOpen(true);
                                    }
                                  }}
                                >
                                  <Share className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                          </div>

                          <div className="flex gap-2">
                            <Button size="sm" variant="outline" asChild className="flex-1 bg-transparent">
                              <Link href={`/builder?edit=${build.build_id}`}>
                                <Edit className="h-4 w-4 mr-2" />
                                Edit
                              </Link>
                            </Button>
                            <Button size="sm" variant="outline" asChild className="flex-1 bg-transparent">
                              <Link href={`/builds/${build.build_id}`}>
                                <Eye className="h-4 w-4 mr-2" />
                                View
                              </Link>
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                    

                  </div>
                )}
                {userBuilds.length > 4 && (
                  <div className="mt-6 text-center">
                    <Button asChild variant="outline">
                      <Link href="/mybuilds">
                        More
                      </Link>
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="liked" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Liked Builds ({likedBuilds.length})</CardTitle>
                <CardDescription>Builds you've liked from the community</CardDescription>
              </CardHeader>
              <CardContent>
                {likedBuilds.length === 0 ? (
                  <div className="text-center py-12">
                    <Heart className="h-12 w-12 text-slate-400 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-slate-900 dark:text-white mb-2">
                      No liked builds yet
                    </h3>
                    <p className="text-slate-600 dark:text-slate-400 mb-4">
                      Explore the community and like builds that inspire you
                    </p>
                    <Button asChild>
                      <Link href="/builds">Browse Community Builds</Link>
                    </Button>
                  </div>
                ) : (
                  <div className="grid md:grid-cols-2 gap-6">
                    {likedBuilds.slice(0, 4).map((row: any) => {
                      const build = row.build;
                      return (
                        <Card key={build.build_id} className="border-slate-200 dark:border-slate-700 hover:shadow-lg transition">
                          <CardHeader className="pb-3">
                            <div className="flex items-start justify-between">
                              <div>
                                <CardTitle className="text-md">{build.build_name}</CardTitle>
                                <CardDescription className="text-sm text-slate-600 dark:text-slate-400">
                                  {build.description || "No description"}
                                </CardDescription>
                                <div className="mt-2 flex items-center gap-2">
                                  <Link href={`/profile/${build.user_id}`} className="flex items-center gap-2">
                                    <Avatar className="h-8 w-8 hover:ring-2 hover:ring-blue-500 transition">
                                      {build.avatar_url ? (
                                        <AvatarImage src={build.avatar_url} alt={build.username} />
                                      ) : (
                                        <AvatarFallback>{build.user_name?.[0] || "U"}</AvatarFallback>
                                      )}
                                    </Avatar>
                                    <span className="text-sm text-slate-700 dark:text-slate-300">{build.user_name || "Unknown"}</span>
                                  </Link>
                                </div>
                              </div>
                              <div className="flex flex-col items-end gap-1 text-xs text-slate-500">
                                <Badge variant="secondary">{formatCurrency(build.total_price || 0)}</Badge>
                                <div className="flex items-center gap-1">
                                  <Calendar className="h-3 w-3" />
                                  <span>{build.date_created ? new Date(build.date_created).toLocaleDateString() : "-"}</span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Eye className="h-3 w-3" />
                                  <span>{(build.views || 0).toLocaleString()} views</span>
                                </div>
                              </div>
                            </div>
                          </CardHeader>
                          <CardContent className="space-y-4">
                            <div className="flex flex-wrap gap-1">
                              {build.build_types?.type_name && (
                                <Badge variant="outline" className="text-xs">
                                  {build.build_types.type_name}
                                </Badge>
                              )}
                            </div>

                            <div className="flex items-center justify-between text-sm text-slate-600 dark:text-slate-400">
                              <div className="flex items-center gap-4">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-auto p-0 flex items-center gap-1 text-sm transition-colors text-red-500 hover:text-red-600"
                                  onClick={() => handleUnlikeBuild(build.build_id)}
                                  title="Unlike"
                                >
                                  <Heart className="h-4 w-4 fill-current" />
                                  <span>{build.likes || 0}</span>
                                </Button>
                                <div className="flex items-center gap-1">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-auto p-0 text-slate-500 hover:text-blue-500"
                                    asChild
                                  >
                                    <Link href={`/builds/${build.build_id}`}>
                                      <MessageCircle className="h-4 w-4" />
                                      <span>{build.comments || 0}</span>
                                    </Link>
                                  </Button>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-auto p-0 text-slate-500 hover:text-green-500"
                                    onClick={() => {
                                      if (typeof window !== "undefined") {
                                        const url = `${window.location.origin}/builder?share=${build.build_id}`;
                                        setShareUrl(url);
                                        setSharePopupOpen(true);
                                      }
                                    }}
                                  >
                                    <Share className="h-4 w-4" />
                                  </Button>
                                </div>
                              </div>
                            </div>

                            <div className="flex gap-2">
                              <Button size="sm" variant="outline" asChild className="flex-1 bg-transparent">
                                <Link href={`/builder?clone=${build.build_id}`}>
                                  <Copy className="h-4 w-4 mr-2" />
                                  Clone
                                </Link>
                              </Button>
                              <Button size="sm" variant="outline" asChild className="flex-1 bg-transparent">
                                <Link href={`/builds/${build.build_id}`}>
                                  <Eye className="h-4 w-4 mr-2" />
                                  View
                                </Link>
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      )
                    })}
                  </div>
                )}
                {likedBuilds.length > 4 && (
                  <div className="mt-6 text-center">
                    <Button asChild variant="outline">
                      <Link href="/likedbuilds">
                        More
                      </Link>
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>


          <TabsContent value="achievements" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Achievements</CardTitle>
                <CardDescription>Track your progress and unlock new badges</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid md:grid-cols-2 gap-6">
                  {achievements.map((achievement) => (
                    <Card
                      key={achievement.id}
                      className={`border-slate-200 dark:border-slate-700 ${
                        achievement.earned ? "bg-green-50 dark:bg-green-900/20" : "opacity-60"
                      }`}
                    >
                      <CardContent className="p-4">
                        <div className="flex items-center gap-3">
                          <achievement.icon
                            className={`h-8 w-8 ${achievement.earned ? "text-green-600" : "text-slate-400"}`}
                          />
                          <div>
                            <h3 className="font-medium">{achievement.name}</h3>
                            <p className="text-sm text-slate-600 dark:text-slate-400">{achievement.description}</p>
                          </div>
                          {achievement.earned && <Badge className="ml-auto bg-green-600">Earned</Badge>}
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="activity" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Activity Timeline</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="max-h-[450px] overflow-y-auto pr-2 space-y-6 custom-scrollbar">
                  {recentActivity.map((activity, index) => (
                    <div key={activity.id} className="flex items-start gap-4">
                      <div className="flex flex-col items-center">
                        <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-full">
                          <activity.icon className="h-4 w-4 text-blue-600" />
                        </div>
                        {index < recentActivity.length - 1 && (
                          <div className="w-px h-8 bg-slate-200 dark:bg-slate-700 mt-2" />
                        )}
                      </div>
                      <div className="flex-1 pb-4">
                        <p className="text-sm text-slate-900 dark:text-white">
                          {activity.description}
                        </p>
                        <p className="text-xs text-slate-500 mt-1">
                          {activity.time}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
      <AlertDialog open={deleteBuildId !== null} onOpenChange={() => setDeleteBuildId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete build?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete your build.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={handleDeleteBuild}
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      {/* Share Popup */}
      {sharePopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-black/50">
          <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg p-6 w-80 max-w-sm text-center">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-2">Share Build</h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              Copy the link below to share this build with others.
            </p>
            <div className="flex items-center gap-2 mb-4">
              <Input value={shareUrl} readOnly className="flex-1 text-sm" />
               <Button
                size="sm"
                onClick={async () => {
                  try {
                    await navigator.clipboard.writeText(shareUrl)
                    swal.success("Link copied!", "Link copied to clipboard.")
                  } catch (err) {
                    console.error(err)
                    swal.error("Failed to copy link", "Please copy manually: " + shareUrl)
                  }
                }}
              >
                Copy
              </Button>
            </div>
            <button
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
              onClick={() => setSharePopupOpen(false)}
            >
              Close
            </button>
          </div>
        </div>
      )}
      {/* Followers / Following Modal */}
      <Dialog open={followModalOpen} onOpenChange={setFollowModalOpen}>
        <DialogContent className="sm:max-w-lg w-full h-[450px] flex flex-col">
          <DialogHeader>
            <DialogTitle>Connections</DialogTitle>
          </DialogHeader>

          <Tabs
            value={followTab}
            onValueChange={setFollowTab}
            className="flex flex-col flex-1 overflow-hidden"
          >
            {/* Tabs triggers stay at top */}
            <TabsList className="grid grid-cols-2 w-full sticky top-0 bg-white dark:bg-slate-900 z-10 border-b border-slate-300 dark:border-slate-700">
              <TabsTrigger
                value="following"
                className="text-sm font-semibold text-slate-700 dark:text-slate-200 data-[state=active]:bg-slate-100 dark:data-[state=active]:bg-slate-800 data-[state=active]:text-slate-900 dark:data-[state=active]:text-white"
              >
                Following
              </TabsTrigger>
              <TabsTrigger
                value="followers"
                className="text-sm font-semibold text-slate-700 dark:text-slate-200 data-[state=active]:bg-slate-100 dark:data-[state=active]:bg-slate-800 data-[state=active]:text-slate-900 dark:data-[state=active]:text-white"
              >
                Followers
              </TabsTrigger>
            </TabsList>

            {/* Scrollable area */}
            <div className="flex-1 overflow-y-auto mt-2 px-2 pb-2 custom-scrollbar">
              {followTab === "following" && (
                <div className="space-y-3">
                  {following.length === 0 ? (
                    <p className="text-sm text-slate-500">Not following anyone yet.</p>
                  ) : (
                    following.map((f) => (
                      <Link
                        key={f.user_id}
                        href={`/profile/${f.user_id}`}
                        className="flex items-center gap-3 p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded"
                        onClick={() => setFollowModalOpen(false)}
                      >
                        <Avatar>
                          {f.avatar ? <AvatarImage src={f.avatar} /> : <AvatarFallback>{f.username[0]}</AvatarFallback>}
                        </Avatar>
                        <p className="text-sm font-medium text-slate-900 dark:text-white">{f.username}</p>
                      </Link>
                    ))
                  )}
                </div>
              )}

              {followTab === "followers" && (
                <div className="space-y-3">
                  {followers.length === 0 ? (
                    <p className="text-sm text-slate-500">No followers yet.</p>
                  ) : (
                    followers.map((f) => (
                      <Link
                        key={f.user_id}
                        href={`/profile/${f.user_id}`}
                        className="flex items-center gap-3 p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded"
                        onClick={() => setFollowModalOpen(false)}
                      >
                        <Avatar>
                          {f.avatar ? <AvatarImage src={f.avatar} /> : <AvatarFallback>{f.username[0]}</AvatarFallback>}
                        </Avatar>
                        <p className="text-sm font-medium text-slate-900 dark:text-white">{f.username}</p>
                      </Link>
                    ))
                  )}
                </div>
              )}
            </div>
          </Tabs>
        </DialogContent>
      </Dialog>
      {/* Popup for trying to like own build */}
      {likeOwnPopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-black/50">
          <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg p-6 w-80 max-w-sm text-center">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-2">Oops!</h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              You cannot like your own build.
            </p>
            <button
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
              onClick={() => setLikeOwnPopupOpen(false)}
            >
              OK
            </button>
          </div>
        </div>
      )}
      {deletePopupOpen && buildToDelete && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-black/50">
          <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg p-6 w-80 max-w-sm text-center">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-2">Confirm Delete</h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              Are you sure you want to delete "<strong>{buildToDelete.build_name}</strong>"? This action cannot be undone.
            </p>
            <div className="flex justify-center gap-4">
              <button
                className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition"
                onClick={handleDeleteBuild}
              >
                Delete
              </button>
              <button
                className="px-4 py-2 bg-gray-300 text-slate-900 rounded hover:bg-gray-400 transition"
                onClick={() => setDeletePopupOpen(false)}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
