"use client"

import React, { useState, useEffect } from "react"
import { use } from "react"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Separator } from "@/components/ui/separator"
import { MapPin, Share, LinkIcon, Calendar, Eye, Cpu, Monitor, Heart, MessageCircle, User } from "lucide-react"
import { supabase } from "@/lib/supabase"
import { Button } from "@/components/ui/button"
import { formatCurrency } from "@/lib/currency"
import { useAuth } from "@/contexts/supabase-auth-context"
import { swal } from "@/lib/sweetalert"

interface ProfilePageProps {
  params: Promise<{ id: string }>
}

export default function ProfilePage({ params }: ProfilePageProps) {
  const { id: userId } = use(params)

  const [isFollowing, setIsFollowing] = useState(false)
  const [userProfile, setUserProfile] = useState<any>(null)
  const [userBuilds, setUserBuilds] = useState<any[]>([])
  const [followers, setFollowers] = useState<number>(0)
  const [following, setFollowing] = useState<number>(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { user } = useAuth()
  const [sharePopup, setSharePopup] = useState<string | null>(null)
  const [likedBuilds, setLikedBuilds] = useState<number[]>([])
  const [likeOwnPopup, setLikeOwnPopup] = useState(false)

  useEffect(() => {
    if (!user) return

    const fetchLikedBuilds = async () => {
      const { data, error } = await supabase
        .from("build_likes")
        .select("build_id")
        .eq("user_id", user.user_id)

      if (!error && data) {
        setLikedBuilds(data.map((row) => row.build_id))
      }
    }

    fetchLikedBuilds()
  }, [user])

  useEffect(() => {
    if (!userBuilds || userBuilds.length === 0) return;

    const fetchViews = async () => {
      const buildIds = userBuilds.map((b) => b.build_id);

      const { data: viewsData, error } = await supabase
        .from("build_views")
        .select("build_id, user_id", { count: "exact" }) // get all rows
        .in("build_id", buildIds);

      if (error) {
        console.error("Failed to fetch build views:", error);
        return;
      }

      // Count views per build
      const viewsMap: Record<string, number> = {};
      buildIds.forEach((id) => (viewsMap[id] = 0));
      viewsData?.forEach((row: any) => {
        viewsMap[row.build_id] = (viewsMap[row.build_id] || 0) + 1;
      });

      // Update builds with views
      setUserBuilds((prev) =>
        prev.map((b) => ({
          ...b,
          views: viewsMap[b.build_id] || 0,
        }))
      );
    };

    fetchViews();
  }, [userBuilds]);


  useEffect(() => {
    if (!userBuilds || userBuilds.length === 0) return

    const fetchLikesCount = async () => {
      const buildIds = userBuilds.map((b) => b.build_id)

      const { data: likes, error } = await supabase
        .from("build_likes")
        .select("build_id")
        .in("build_id", buildIds)

      if (!error && likes) {
        const counts: Record<string, number> = {}
        buildIds.forEach((id) => (counts[id] = 0))
        likes.forEach((like: any) => {
          counts[like.build_id] = (counts[like.build_id] || 0) + 1
        })

        setUserBuilds((prev) =>
          prev.map((b) => ({ ...b, likesCount: counts[b.build_id] || 0 }))
        )
      }
    }

    fetchLikesCount()
  }, [userBuilds.length]) // run once after builds are fetched

  useEffect(() => {
    if (!userBuilds || userBuilds.length === 0) return;

    const fetchCommentsCount = async () => {
      const buildIds = userBuilds.map((b) => b.build_id);

      const { data: comments, error } = await supabase
        .from("build_comments")
        .select("build_id", { count: "exact" })
        .in("build_id", buildIds);

      if (error) {
        console.error("Failed to fetch comments:", error);
        return;
      }

      const counts: Record<number, number> = {};
      buildIds.forEach((id) => (counts[id] = 0));
      comments?.forEach((comment: any) => {
        counts[comment.build_id] = (counts[comment.build_id] || 0) + 1;
      });

      setUserBuilds((prev) =>
        prev.map((b) => ({ ...b, comments: counts[b.build_id] || 0 }))
      );
    };

    fetchCommentsCount();
  }, [userBuilds.length]);

  // Check if already following
  useEffect(() => {
    if (!user?.user_id || user.user_id === Number(userId)) return

    const checkFollowing = async () => {
      const { data } = await supabase
        .from("followers")
        .select("*")
        .eq("user_id", userId)
        .eq("follower_user_id", user?.user_id)
       .single()
      setIsFollowing(!!data)
    }

    checkFollowing()
  }, [user?.user_id, userId])

  // Follow/unfollow handler
  const handleFollow = async () => {
    if (!user?.user_id) return;

    // 🚫 Prevent self-follow
    if (user.user_id === Number(userId)) {
      return;
    }

    try {
      if (isFollowing) {
        // Unfollow
        const { error: unfollowError } = await supabase
          .from("followers")
          .delete()
          .eq("user_id", userId)
          .eq("follower_user_id", user.user_id);

        if (unfollowError) {
          console.error("Failed to unfollow:", unfollowError);
          return;
        }

        setIsFollowing(false);
        setFollowers((prev) => Math.max(prev - 1, 0));

      } else {
        // Follow
        const { error: followError } = await supabase
          .from("followers")
          .insert({
            user_id: userId,
            follower_user_id: user.user_id,
            created_at: new Date().toISOString(),
          });

        if (followError) {
          console.error("Failed to follow:", followError);
          return;
        }

        setIsFollowing(true);
        setFollowers((prev) => prev + 1);

        // Create follow notification
        const { error: notifError } = await supabase
          .from("notifications")
          .insert({
            user_id: userId,
            actor_user_id: user.user_id,
            type: "follow",
          });

        if (!notifError) {
          // Send push notification to the followed user (non-blocking)
          try {
            const payload = {
              userId: userId,
              notificationType: 'followers',
              title: `${user.user_name} started following you`,
              body: `${user.user_name} is now following you`,
              url: `/profile/${user.user_id}`,
            };

            console.log('Sending push notification for new follower (from profile):', 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 for follower (from profile):', sendResult);
          } catch (err) {
            console.error('Error sending push notification for follower:', err);
          }
        }
      }
    } catch (err) {
      console.error("Follow action failed:", err);
    }
  };


  // Fetch profile, builds, followers/following
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        const { data: profile, error: profileError } = await supabase
          .from("users")
          .select("*")
          .eq("user_id", userId)
          .single()

        if (profileError || !profile) {
          setError("User not found")
          return
        }

        // load privacy settings from dedicated table, fallback to column
        let privacySettings: any = {}
        try {
          const { data: priv, error: privError } = await supabase
            .from('privacy_settings')
            .select('*')
            .eq('user_id', userId)
            .maybeSingle();
          if (!privError && priv) {
            privacySettings = { profilePublic: priv.profile_public, showBuilds: priv.show_builds };
          } else {
            privacySettings =
              typeof profile.privacy_settings === "string"
                ? JSON.parse(profile.privacy_settings)
                : profile.privacy_settings || {};
          }
        } catch (e) {
          console.error('Error fetching privacy settings for profile page:', e);
          privacySettings =
            typeof profile.privacy_settings === "string"
              ? JSON.parse(profile.privacy_settings)
              : profile.privacy_settings || {};
        }
        setUserProfile({
          ...profile,
          privacy_settings: privacySettings,
        })

        if (!privacySettings?.profilePublic) {
          setError("This profile is private")
          return
        }

        const { data: builds, error: buildsError } = await supabase
          .from("builds")
          .select("*")
          .eq("user_id", userId)

        if (!buildsError && builds) {
          setUserBuilds(builds)
        }

        const { count: followersCount } = await supabase
          .from("followers")
          .select("*", { count: "exact", head: true })
          .eq("user_id", userId)

        setFollowers(followersCount || 0)

        const { count: followingCount } = await supabase
          .from("followers")
          .select("*", { count: "exact", head: true })
          .eq("follower_user_id", userId)

        setFollowing(followingCount || 0)

      } catch (err: any) {
        console.error(err)
        setError("Failed to load user profile")
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [userId, user?.user_id])


  if (loading) {
    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-20 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 profile...</p>
        </div>
      </div>
    )
  }
  if (error || !userProfile) {
    if (error === "This profile is private") {
      return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 px-4">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center shadow-sm">
            <div className="mb-4 text-4xl">🔒</div>
            <h2 className="text-2xl font-semibold mb-2 text-slate-900 dark:text-white">
              This profile is private
            </h2>
            <p className="text-sm text-slate-600 dark:text-slate-400">
              The user has chosen to keep their profile hidden.
            </p>
            <Button asChild className="mt-4">
              <Link href="/dashboard">Back to Dashboard</Link>
            </Button>
          </div>
        </div>
      )
    } else {
      return (
        <div className="min-h-screen flex items-center justify-center text-red-500">
          {error || "Failed to load profile"}
        </div>
      )
    }
  }

  // Like build handler
  const handleLike = async (build: any) => {
    if (!user) {
      swal.info("Login required", "Please log in to like builds.");
      return
    }

    const isLiked = likedBuilds.includes(build.build_id)

    // prevent liking own build
    if (build.user_id === user.user_id) {
      setLikeOwnPopup(true)
      return
    }

    if (isLiked) {
      // UNLIKE
      const { error: deleteLikeError } = await supabase
        .from("build_likes")
        .delete()
        .eq("build_id", build.build_id)
        .eq("user_id", user.user_id)

      if (!deleteLikeError) {
        setLikedBuilds((prev) => prev.filter((id) => id !== build.build_id))
        setUserBuilds((prev) =>
          prev.map((b) =>
            b.build_id === build.build_id
              ? { ...b, likesCount: Math.max((b.likesCount || 1) - 1, 0) }
              : b
          )
        )

        // remove notification
        await supabase
          .from("notifications")
          .delete()
          .eq("type", "like")
          .eq("build_id", build.build_id)
          .eq("actor_user_id", user.user_id)
          .eq("user_id", build.user_id)
      }
    } else {
      // LIKE
      const { error: insertLikeError } = await supabase
        .from("build_likes")
        .insert({
          build_id: build.build_id,
          user_id: user.user_id,
        })

      if (!insertLikeError) {
        setLikedBuilds((prev) => [...prev, build.build_id])
        setUserBuilds((prev) =>
          prev.map((b) =>
            b.build_id === build.build_id
              ? { ...b, likesCount: (b.likesCount || 0) + 1 }
              : b
          )
        )

        // create notification
        if (user.user_id !== build.user_id) {
          await supabase.from("notifications").insert({
            user_id: build.user_id,      // owner
            actor_user_id: user.user_id, // liker
            type: "like",
            build_id: build.build_id,
            is_read: false,
          })

          // 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/${build.build_id}`,
            };

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

            fetch('/api/notifications/send', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(payload),
            })
              .then(res => res.json().then(r => console.log('Push send result (profile):', r)).catch(() => {}))
              .catch(err => console.error('Error sending push (profile):', err));
          } catch (err) {
            console.error('Error preparing push send (profile):', err);
          }
        }
      }
    }
  }




  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 max-w-6xl">
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Profile Overview */}
          <Card className="lg:col-span-1">
            <CardHeader className="text-center">
              <div className="relative mx-auto mb-4">
                <Avatar className="h-24 w-24">
                  {userProfile.avatar_url ? (
                    <AvatarImage src={userProfile.avatar_url} />
                  ) : (
                    <AvatarFallback className="text-2xl">
                      {userProfile.user_name ? userProfile.user_name.charAt(0).toUpperCase() : "?"}
                    </AvatarFallback>
                  )}
                </Avatar>
              </div>
              <CardTitle>{userProfile.user_name}</CardTitle>
              <p className="text-sm text-slate-600 dark:text-slate-400">{userProfile.email}</p>
            </CardHeader>

            <CardContent className="space-y-4">
              <p className="text-center text-sm text-slate-600 dark:text-slate-400">{userProfile.bio}</p>
              <Separator />

              <div className="space-y-2 text-sm">
                <div className="flex items-center gap-2">
                  <MapPin className="h-4 w-4 text-slate-500" />
                  <span>{userProfile.location}</span>
                </div>
                <div className="flex items-center gap-2">
                  <LinkIcon className="h-4 w-4 text-slate-500" />
                  <a href={userProfile.website} className="text-blue-600 hover:underline">
                    {userProfile.website}
                  </a>
                </div>
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-slate-500" />
                  <span>Joined {new Date(userProfile.created_at).toLocaleDateString()}</span>
                </div>
              </div>

              <Separator />

              <div className="grid grid-cols-3 gap-4 text-center">
                <div>
                  <p className="text-lg font-bold text-slate-900 dark:text-white">{userBuilds?.length || 0}</p>
                  <p className="text-xs text-slate-600 dark:text-slate-400">Builds</p>
                </div>
                <div>
                  <p className="text-lg font-bold text-slate-900 dark:text-white">{following}</p>
                  <p className="text-xs text-slate-600 dark:text-slate-400">Following</p>
                </div>
                <div>
                  <p className="text-lg font-bold text-slate-900 dark:text-white">{followers}</p>
                  <p className="text-xs text-slate-600 dark:text-slate-400">Followers</p>
                </div>
              </div>

              {/* Follow Button */}
              {user?.user_id && user?.user_id !== Number(userId) && (
                <div className="mt-4 text-center">
                  <Button
                    onClick={handleFollow}
                    variant={isFollowing ? "default" : "outline"}
                    className="w-full"
                  >
                    <User className="h-4 w-4 mr-2" />
                    {isFollowing ? "Following" : "Follow"}
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
          {/* Builds Section */}
          <div className="lg:col-span-2">
            {/* Section Title */}
            <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-4">Builds</h2>
            {/* Builds List */}
            <div
              className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-4 sm:gap-6 items-start"
            >
              {userProfile?.privacy_settings?.showBuilds === false ? (
                <div className="text-center py-12 lg:col-span-2">
                  <h3 className="text-lg font-medium text-slate-900 dark:text-white">
                    Builds are private
                  </h3>
                  <p className="text-slate-600 dark:text-slate-400">
                    This user has hidden their builds.
                  </p>
                </div>

              ) : (!userBuilds || userBuilds.length === 0) ? (

                <div className="text-center py-12 lg:col-span-2">
                  <h3 className="text-lg font-medium text-slate-900 dark:text-white">No builds yet</h3>
                  <p className="text-slate-600 dark:text-slate-400">This user hasn’t shared any builds yet.</p>
                </div>
              ) : (
                userBuilds.map((build, index) => {
                  const cpuComponent = build.build_components?.find((bc: any) =>
                    bc.components?.component_categories?.category_name === "CPU"
                  )
                  const isLiked = likedBuilds.includes(build.build_id)
                  const gpuComponent = build.build_components?.find((bc: any) =>
                    bc.components?.component_categories?.category_name === "GPU"
                  )
                  const totalPrice = Number(build.total_price) || 0;

                  return (
                    <Card
                      key={build.build_id ?? index}
                      className="border-slate-200 dark:border-slate-700 hover:shadow-lg transition-all duration-200 group"
                    >
                      <CardHeader className="pb-3 flex justify-between items-start">
                        <div>
                          <CardTitle className="text-lg group-hover:text-blue-600 transition-colors">
                            {build.build_name}
                          </CardTitle>
                        </div>
                        <div className="text-right">
                          <p className="text-sm font-semibold text-blue-600">{formatCurrency(totalPrice)}</p>
                          <div className="flex items-center gap-1 mt-1 text-xs text-slate-500">
                            <Eye className="h-3 w-3" />
                            <span>{(build.views || 0).toLocaleString()} views</span>
                          </div>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-2">
                          {build.description || 'PC Build'}
                        </p>

                        <div className="space-y-1.5">
                          {cpuComponent && (
                            <div className="flex items-center gap-2 text-xs">
                              <Cpu className="h-3 w-3 text-blue-500" />
                              <span className="text-slate-600 dark:text-slate-400 truncate">
                                {cpuComponent.components?.component_name}
                              </span>
                            </div>
                          )}
                          {gpuComponent && (
                            <div className="flex items-center gap-2 text-xs">
                              <Monitor className="h-3 w-3 text-green-500" />
                              <span className="text-slate-600 dark:text-slate-400 truncate">
                                {gpuComponent.components?.component_name}
                              </span>
                            </div>
                          )}
                        </div>

                        <div className="flex items-center justify-between pt-2 border-t border-slate-100 dark:border-slate-700">
                          <div className="flex items-center gap-2 text-xs text-slate-500">
                            <Button
                              variant="ghost"
                              size="sm"
                              className={`h-auto p-0 flex items-center gap-1 text-sm transition-colors ${
                                isLiked ? "text-red-500 hover:text-red-600" : "text-slate-500 hover:text-red-500"
                              }`}
                              onClick={() => handleLike(build)}
                            >
                              <Heart className={`h-4 w-4 ${isLiked ? "fill-current text-red-500" : ""}`} />
                              <span>{build.likesCount || 0}</span>
                            </Button>

                            <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>

                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-auto p-0 text-slate-500 hover:text-green-500"
                              onClick={() => setSharePopup(`${window.location.origin}/builds/${build.build_id}`)}
                            >
                              <Share className="h-4 w-4" />
                            </Button>
                          </div>
                          <Link href={`/builds/${build.build_id}`} className="text-xs">
                            <Button size="sm" variant="outline">
                              View Build
                            </Button>
                          </Link>
                        </div>
                      </CardContent>
                    </Card>
                  )
                })
              )}
            </div>
          </div>
        </div>
      </div>
      {/* Share popup */}
      {sharePopup && (
        <div className="fixed inset-0 flex items-center justify-center bg-black/50 z-50">
          <div className="bg-white dark:bg-slate-800 p-6 rounded-md max-w-sm text-center">
            <h3 className="mb-2 font-semibold text-slate-900 dark:text-white">Share Build</h3>
            <input type="text" readOnly value={sharePopup} className="w-full mb-4 p-2 border rounded text-sm" />
            <div className="flex justify-center gap-4">
              <button
                onClick={async () => {
                  try {
                    await navigator.clipboard.writeText(sharePopup)
                    swal.success("Link copied!", "Link copied to clipboard.")
                  } catch (err) {
                    console.error(err)
                    swal.error("Failed to copy link", "Please copy manually: " + sharePopup)
                  }
                }}
                className="px-4 py-2 bg-blue-600 text-white rounded"
              >
                Copy
              </button>
              <button onClick={() => setSharePopup(null)} className="px-4 py-2 border rounded">Close</button>
            </div>
          </div>
        </div>
      )}
      {/* Like Own Build Popup */}
      {likeOwnPopup && (
        <div className="fixed inset-0 flex items-center justify-center bg-black/50 z-50">
          <div className="bg-white dark:bg-slate-800 p-6 rounded-md max-w-sm text-center">
            <h3 className="mb-2 font-semibold text-slate-900 dark:text-white">Oops!</h3>
            <p className="mb-4 text-sm text-slate-600 dark:text-slate-400">
              You cannot like your own build.
            </p>
            <button
              onClick={() => setLikeOwnPopup(false)}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
            >
              OK
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
