"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Cpu, Heart, MessageCircle, Share, Search, Monitor, Users, Eye, BarChart3, ShoppingCart, Calendar, Trash2, Pencil } from "lucide-react"
import { buildService, buildComponentService } from "@/lib/database"
import { formatCurrency, PRICE_RANGES } from "@/lib/currency"
import { useAuth } from "@/contexts/supabase-auth-context"
import { supabase } from "@/lib/supabase"
import { swal } from "@/lib/sweetalert"

interface BuildWithDetails {
  build_id: number
  build_name: string
  date_created: string
  user_id: number
  build_type_id: number
  users: {
    user_id: number
    user_name: string
    email: string
    avatar_url: string
  }
  build_types: {
    build_type_id: number
    type_name: string
  }
  components?: any[]
  totalPrice?: number
  likes?: number
  comments?: number
  views?: number
  description?: string
}

export default function BuildsPage() {
  const { user, isLoading: authLoading } = useAuth()
  const pathname = usePathname()
  const [builds, setBuilds] = useState<BuildWithDetails[]>([])
  const [statistics, setStatistics] = useState({ totalBuilders: 0, totalBuilds: 0, totalLikes: 0 })
  const [searchTerm, setSearchTerm] = useState("")
  const [sortBy, setSortBy] = useState("popular")
  const [priceFilter, setPriceFilter] = useState("all")
  const [likedBuilds, setLikedBuilds] = useState<number[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [likeOwnPopupOpen, setLikeOwnPopupOpen] = useState(false)
  const [sharePopupOpen, setSharePopupOpen] = useState(false)
  const [shareUrl, setShareUrl] = useState("")
  const [deletePopupOpen, setDeletePopupOpen] = useState(false)
  const [buildToDelete, setBuildToDelete] = useState<BuildWithDetails | null>(null)
  const [loadingTimeout, setLoadingTimeout] = useState(false)

  // Safety: stop showing loading after 12s so the page never stays stuck
  useEffect(() => {
    if (!authLoading && !user) return
    if (!loading && builds.length > 0) return
    const t = setTimeout(() => setLoadingTimeout(true), 12000)
    return () => clearTimeout(t)
  }, [authLoading, user, loading, builds.length])

  // Fetch builds and statistics (only when user is available)
  useEffect(() => {
    if (!user) {
      setLoading(false)
      setLoadingTimeout(false)
      return
    }
    setLoadingTimeout(false)
    fetchBuilds()
    fetchStatistics()

    const buildsChannel = supabase
      .channel('builds-changes')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'builds' }, () => {
        fetchBuilds()
        fetchStatistics()
      })
      .subscribe()

    return () => {
      supabase.removeChannel(buildsChannel)
    }
  }, [pathname, user])

  // Fetch user's liked builds
  useEffect(() => {
    if (!user) return;
    const fetchLiked = async () => {
      const { data, error } = await supabase
        .from("build_likes")
        .select("build_id")
        .eq("user_id", user.user_id)
      if (!error && data) setLikedBuilds(data.map((r) => r.build_id))
    }
    fetchLiked()
  }, [user])

  const fetchBuilds = async () => {
    if (!user) return;
    try {
      setLoading(true);
      setError(null);

      const { data: userBuilds, error } = await supabase
        .from("builds")
        .select(`
          build_id,
          build_name,
          date_created,
          user_id,
          build_type_id,
          total_price,
          description,
          users:user_id (
            user_id,
            user_name,
            email,
            avatar_url
          ),
          build_types:build_type_id (
            build_type_id,
            type_name
          )
        `)
        .eq("user_id", user.user_id);

      if (error) throw error;
      const list = userBuilds ?? [];

      if (list.length === 0) {
        setBuilds([]);
        return;
      }

      const buildIds = list.map((b) => b.build_id);

      // Batch fetch likes, comments, views (3 queries total instead of 3 per build)
      const [likesRes, commentsRes, viewsRes] = await Promise.all([
        supabase.from("build_likes").select("build_id").in("build_id", buildIds),
        supabase.from("build_comments").select("build_id").in("build_id", buildIds),
        supabase.from("build_views").select("build_id").in("build_id", buildIds),
      ]);

      const countByBuild = (rows: { build_id: number }[] | null) => {
        const map: Record<number, number> = {};
        buildIds.forEach((id) => (map[id] = 0));
        (rows ?? []).forEach((r) => (map[r.build_id] = (map[r.build_id] ?? 0) + 1));
        return map;
      };

      const likesMap = countByBuild(likesRes.data);
      const commentsMap = countByBuild(commentsRes.data);
      const viewsMap = countByBuild(viewsRes.data);

      const buildsWithDetails = list.map((build) => ({
        ...build,
        totalPrice: Number(build.total_price || 0),
        likes: likesMap[build.build_id] ?? 0,
        comments: commentsMap[build.build_id] ?? 0,
        views: viewsMap[build.build_id] ?? 0,
      }));

      setBuilds(buildsWithDetails);
    } catch (err: any) {
      console.error(err);
      setError(err.message || "Failed to load builds");
    } finally {
      setLoading(false);
    }
  };

  const fetchStatistics = async () => {
    try {
      if (!user) return;

      // 1️⃣ Get all build IDs owned by the user
      const { data: userBuilds, error: buildsError } = await supabase
        .from("builds")
        .select("build_id")
        .eq("user_id", user.user_id);

      if (buildsError) throw buildsError;

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

      // 2️⃣ Count total builds
      const totalBuilds = buildIds.length;

      if (buildIds.length === 0) {
        setStatistics({
          totalBuilders: 1,
          totalBuilds: 0,
          totalLikes: 0,
        });
        return;
      }

      // 3️⃣ Count likes from build_likes (THIS IS THE FIX)
      const { count: totalLikes, error: likesError } = await supabase
        .from("build_likes")
        .select("*", { count: "exact", head: true })
        .in("build_id", buildIds);

      if (likesError) throw likesError;

      // 4️⃣ Keep existing builder stats
      const stats = await buildService.getStatistics();

      setStatistics({
        ...stats,
        totalBuilds,
        totalLikes: totalLikes || 0,
      });
    } catch (err) {
      console.error("Error fetching statistics:", err);
    }
  };


  const handleLike = async (build: BuildWithDetails) => {
    if (!user) return;
    const isLiked = likedBuilds.includes(build.build_id);

    // ❌ Prevent liking your own build
    if (build.users?.user_id === user.user_id) {
      setLikeOwnPopupOpen(true)
      return
    }

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

      if (!error) {
        setLikedBuilds(prev => prev.filter(id => id !== build.build_id));
        setBuilds(prev =>
          prev.map(b => b.build_id === build.build_id ? { ...b, likes: (b.likes || 1) - 1 } : b)
        );
      }
    } else {
      const { error } = await supabase
        .from("build_likes")
        .insert({ build_id: build.build_id, user_id: user.user_id });

      if (!error) {
        setLikedBuilds(prev => [...prev, build.build_id]);
        setBuilds(prev =>
          prev.map(b => b.build_id === build.build_id ? { ...b, likes: (b.likes || 0) + 1 } : b)
        );
        // Send push notification to 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 (mybuilds):', 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 (mybuilds):', r)).catch(() => {}))
            .catch(err => console.error('Error sending push (mybuilds):', err));
        } catch (err) {
          console.error('Error preparing push send (mybuilds):', err);
        }
      }
    }
  };

  const handleDeleteBuild = async () => {
    if (!buildToDelete) return;

    try {
      const { error } = await supabase
        .from("builds")
        .delete()
        .eq("build_id", buildToDelete.build_id);

      if (error) throw error;

      // Remove from local state
      setBuilds(prev => prev.filter(b => b.build_id !== buildToDelete.build_id));
      setDeletePopupOpen(false);
      setBuildToDelete(null);
    } catch (err: any) {
      console.error("Failed to delete build:", err);
      swal.error("Failed to delete build", err.message);
    }
  };


  const getFilteredBuilds = (): BuildWithDetails[] => {
    let filtered = builds.filter(
      b => b.build_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
           b.build_types?.type_name.toLowerCase().includes(searchTerm.toLowerCase())
    )
    if (priceFilter !== "all") {
      filtered = filtered.filter(build => {
        const price = build.totalPrice || 0
        switch (priceFilter) {
          case "budget": return price < PRICE_RANGES.budget.max
          case "mid": return price >= PRICE_RANGES.mid.min && price < PRICE_RANGES.mid.max
          case "high": return price >= PRICE_RANGES.high.min
          default: return true
        }
      })
    }
    switch (sortBy) {
      case "recent": return filtered.sort((a, b) => new Date(b.date_created).getTime() - new Date(a.date_created).getTime())
      case "price-low": return filtered.sort((a, b) => (a.totalPrice || 0) - (b.totalPrice || 0))
      case "price-high": return filtered.sort((a, b) => (b.totalPrice || 0) - (a.totalPrice || 0))
      case "likes": return filtered.sort((a, b) => (b.likes || 0) - (a.likes || 0))
      default: return filtered.sort((a, b) => (b.likes || 0) - (a.likes || 0))
    }
  }

  const filteredBuilds = getFilteredBuilds()
  const formatNumber = (num: number) => num.toLocaleString()

  // Full-page loading only while we don't know auth yet
  if (authLoading) {
    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...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    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-slate-400 mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">Sign in to see your builds</h2>
          <p className="text-slate-600 dark:text-slate-400 mb-4">Log in or create an account to view and manage your PC builds.</p>
          <Button asChild>
            <Link href="/login">Log in</Link>
          </Button>
        </div>
      </div>
    )
  }

  // From here we have user: show page shell; loading only in list area
  const listLoading = loading && builds.length === 0 && !loadingTimeout
  const listError = loadingTimeout && builds.length === 0 && !error

  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">
        {error && (
          <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <p className="text-red-800 dark:text-red-200">{error}</p>
          </div>
        )}

        {/* Stats */}
        <div className="mb-8">
          <div className="flex items-center gap-6 text-sm text-slate-600 dark:text-slate-400">
            <div className="flex items-center gap-1">
              <Cpu className="h-4 w-4" />
              <span>{formatNumber(statistics.totalBuilds)} builds</span>
            </div>
            <div className="flex items-center gap-1">
              <Heart className="h-4 w-4" />
              <span>{formatNumber(statistics.totalLikes)} likes</span>
            </div>
          </div>
        </div>

        <div className="flex flex-col lg:flex-row gap-4 mb-8">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
            <Input
              placeholder="Search builds, components, or tags..."
              className="pl-10"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <div className="flex gap-2">
            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="Sort by" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="popular">Most Popular</SelectItem>
                <SelectItem value="recent">Most Recent</SelectItem>
                <SelectItem value="likes">Most Liked</SelectItem>
                <SelectItem value="price-low">Price: Low to High</SelectItem>
                <SelectItem value="price-high">Price: High to Low</SelectItem>
              </SelectContent>
            </Select>
            <Select value={priceFilter} onValueChange={setPriceFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="Price" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Prices</SelectItem>
                <SelectItem value="budget">{PRICE_RANGES.budget.label}</SelectItem>
                <SelectItem value="mid">{PRICE_RANGES.mid.label}</SelectItem>
                <SelectItem value="high">{PRICE_RANGES.high.label}</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {listError ? (
          <div className="py-12 text-center">
            <Cpu className="h-12 w-12 text-slate-400 mx-auto mb-4" />
            <p className="text-slate-700 dark:text-slate-300 font-medium mb-1">Taking longer than usual</p>
            <p className="text-slate-600 dark:text-slate-400 text-sm mb-4">Check your connection or try again.</p>
            <Button
              onClick={() => {
                setLoadingTimeout(false)
                setLoading(true)
                fetchBuilds()
                fetchStatistics()
              }}
            >
              Try again
            </Button>
          </div>
        ) : listLoading ? (
          <div className="py-12 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 builds...</p>
          </div>
        ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-2 gap-6">
          {filteredBuilds.map((build) => {
            const creator = build.users
            const isLiked = likedBuilds.includes(build.build_id)
            const cpuComponent = build.components?.find((bc: any) => 
              bc.components?.component_categories?.category_name === 'CPU'
            )
            const gpuComponent = build.components?.find((bc: any) => 
              bc.components?.component_categories?.category_name === 'GPU'
            )

            return (
              <Card
                key={build.build_id}
                className="border-slate-200 dark:border-slate-700 hover:shadow-lg transition-all duration-200 group"
              >
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <CardTitle className="text-lg group-hover:text-blue-600 transition-colors">
                        {build.build_name}
                      </CardTitle>
                      <div className="flex items-center gap-2 mt-2">
                        <Avatar className="h-6 w-6">
                          <Avatar className="h-6 w-6">
                            <AvatarImage src={creator?.avatar_url || "/placeholder.svg"} />
                            <AvatarFallback className="text-xs">
                              {creator?.user_name?.charAt(0).toUpperCase() || "U"}
                            </AvatarFallback>
                          </Avatar>
                          <span className="text-sm text-slate-600 dark:text-slate-400">
                            {creator?.user_name || "Unknown"}
                          </span>

                        </Avatar>
                        <span className="text-sm text-slate-600 dark:text-slate-400">
                          {creator?.user_name || "Unknown"}
                        </span>
                      </div>
                    </div>
                    <div className="text-right 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={() => {
                          setBuildToDelete(build)
                          setDeletePopupOpen(true)
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                      <Badge variant="secondary" className="font-semibold">
                        {formatCurrency(build.totalPrice || 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 mt-1 text-xs text-slate-500">
                        <Eye className="h-3 w-3" />
                        <span>{(build.views || 0).toLocaleString()} views</span>
                      </div>
                    </div>
                  </div>
                </CardHeader>

                <CardContent className="space-y-4">
                  <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-2">
                    {build?.description || 'PC Build'}
                  </p>

                  {/* Build tags */}
                  <div className="flex flex-wrap gap-1">
                    <Badge variant="outline" className="text-xs">
                      {build.build_types?.type_name || 'build'}
                    </Badge>
                  </div>

                  {/* Key components */}
                  <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>

                  {/* Actions */}
                  <div className="flex items-center justify-between pt-2 border-t border-slate-100 dark:border-slate-700">
                    <div className="flex items-center gap-3">
                      <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" : ""}`} />
                        <span>{build.likes}</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={() => {
                          const url =
                            typeof window !== "undefined"
                              ? `${window.location.origin}/builder?share=${build.build_id}`
                              : ""

                          setShareUrl(url)
                          setSharePopupOpen(true)
                        }}
                      >
                        <Share className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button 
                        size="sm" 
                        variant="default"
                        className="text-xs"
                        asChild
                      >
                        <Link href={`/purchase/${build.build_id}`}>
                          <ShoppingCart className="h-3 w-3 mr-1" />
                          Purchase
                        </Link>
                      </Button>
                      <Button size="sm" variant="outline" asChild className="text-xs bg-transparent">
                        <Link href={`/compare?add=${build.build_id}`}>
                          <BarChart3 className="h-3 w-3 mr-1" />
                          Compare
                        </Link>
                      </Button>
                      <Button size="sm" variant="outline" asChild className="text-xs bg-transparent">
                        <Link href={`/builder?edit=${build.build_id}`}>
                          <Pencil className="h-3 w-3 mr-1" />
                          Edit
                        </Link>
                      </Button>
                      <Button size="sm" variant="outline" asChild className="text-xs bg-transparent">
                        <Link href={`/builds/${build.build_id}`}>View Details</Link>
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
        )}

        {filteredBuilds.length === 0 && !loading && (
          <div className="text-center py-12">
            <Cpu 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 found</h3>
            <p className="text-slate-600 dark:text-slate-400 mb-4">Try adjusting your search terms or filters</p>
            <Button asChild>
              <Link href="/builder">Create your first build</Link>
            </Button>
          </div>
        )}
      </div>
      {/* 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>
      )}
      {/* 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>
      )}
      {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>
  )
}
