'use client';

import { cn } from "@/lib/utils"
import { 
  MapPin, 
  Link as LinkIcon, 
  Calendar, 
  BadgeCheck, 
  UserPlus,
  UserCheck,
  MoreHorizontal,
  Share2,
  Flag,
  Sparkles,
  Lock,
  Lightbulb,
  Loader2,
  CheckCircle,
  User,
  Ban,
  MapPinned
} from "lucide-react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { useState, useEffect } from "react"
import { useSelector } from "react-redux"
import { RootState } from "@/lib/store/store"
import { reportProfile, checkReportStatus, followUser, 
  unfollowUser, 
  checkFollowingStatus, 
  getFollowersCount,
  getFollowingCount,
  blockAccountCustomer,
  fetchBlockedProfiles
} from "@/lib/api/client"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { getAllAccountTypes } from '@/lib/api/client';

interface ProfileHeaderProps {
  name: string
  username: string
  avatar: string
  bio: string
  location?: string
  website?: string
  joinedDate: string
  isVerified?: boolean
   designation?: string 
  address?: string  
  isPremium?: boolean
  userType: "individual" | "business" | "investor"
  aiMatchScore?: number
  stats: {
    ideas?: number
    likes?: number
    dislikes?: number
    investments?: number
    deals?: number
  }
  badges?: string[]
  userId?: string
  userModel?: string
}

const userTypeConfig = {
  individual: {
    label: "Individual",
    color: "bg-primary",
    textColor: "text-primary",
    borderColor: "border-primary/30",
    bgGlow: "bg-primary/10",
  },
  business: {
    label: "Business",
    color: "bg-amber-500",
    textColor: "text-amber-400",
    borderColor: "border-amber-500/30",
    bgGlow: "bg-amber-500/10",
  },
  investor: {
    label: "Investor",
    color: "bg-emerald-500",
    textColor: "text-emerald-400",
    borderColor: "border-emerald-500/30",
    bgGlow: "bg-emerald-500/10",
  },
}

export function ProfileHeader({
  name,
  username,
  avatar,
  bio,
  location,
  website,
  joinedDate,
  isVerified,
    designation, 
  address,   
  isPremium = false,
  userType,
  aiMatchScore = 0,
  stats,
  badges,
  userId,
  userModel,
}: ProfileHeaderProps) {
  const config = userTypeConfig[userType]
  const showCollaboration = isPremium && aiMatchScore >= 70
  

  const { accessToken, currentCustomer } = useSelector((state: RootState) => state.user)
  const router = useRouter()
  
  const loggedInUserId = currentCustomer?.customer?._id || currentCustomer?._id
  const isOwnProfile = loggedInUserId === userId

  const [accountTypes, setAccountTypes] = useState<any[]>([]);

  
  // Report states
  const [isReporting, setIsReporting] = useState(false)
  const [hasReported, setHasReported] = useState(false)
  const [showReportConfirm, setShowReportConfirm] = useState(false)
  const [isCheckingReport, setIsCheckingReport] = useState(false)

  // Block states
  const [isBlocked, setIsBlocked] = useState(false)
  const [isCheckingBlock, setIsCheckingBlock] = useState(false)
  const [showBlockConfirm, setShowBlockConfirm] = useState(false)
  const [isBlocking, setIsBlocking] = useState(false)

  // Follow states
  const [isFollowing, setIsFollowing] = useState(false)
  const [followersCount, setFollowersCount] = useState(0)
  const [followingCount, setFollowingCount] = useState(0)

  const getModelName = (type: string): string => {
    if (type === 'individual') return 'customer'
    if (type === 'business') return 'business'
    if (type === 'investor') return 'investor'
    return 'customer'
  }

  const getAccountTypeLabel = (type: string) => {
    const labels = {
      individual: "Innovator",
      business: "Business", 
      investor: "Investor"
    };
    return labels[type] || type;
  };

  const accountTypeLabel = getAccountTypeLabel(userType);

  // ✅ Check if already blocked
  useEffect(() => {
    if (accessToken && userId && !isOwnProfile) {
      const checkBlockStatus = async () => {
        setIsCheckingBlock(true)
        try {
          const response = await fetchBlockedProfiles(accessToken)
          if (response.success && response.data) {
            const isUserBlocked = response.data.some(
              (blocked: any) => blocked._id === userId
            )
            setIsBlocked(isUserBlocked)
          }
        } catch (error) {
          console.error("Error checking block status:", error)
        } finally {
          setIsCheckingBlock(false)
        }
      }
      checkBlockStatus()
    }
  }, [accessToken, userId, isOwnProfile])

  // Check if already following (only for others' profiles)
  useEffect(() => {
    if (accessToken && userId && !isOwnProfile && userModel) {
      const checkFollowStatus = async () => {
        try {
          const modelName = getModelName(userType)
          const response = await checkFollowingStatus(accessToken, userId, modelName)
          if (response.success) {
            setIsFollowing(response.data?.isFollowing || false)
          }
        } catch (error) {
          console.error('Error checking follow status:', error)
        }
      }
      checkFollowStatus()
    }
  }, [accessToken, userId, isOwnProfile, userType, userModel])

  // ✅ Get followers count
  useEffect(() => {
    if (userId && userModel) {
      const fetchFollowersCount = async () => {
        try {
          const modelName = getModelName(userType)
          const response = await getFollowersCount(userId, modelName)
          if (response.success) {
            setFollowersCount(response.data?.followersCount || 0)
          }
        } catch (error) {
          console.error('Error fetching followers count:', error)
        }
      }
      fetchFollowersCount()
    }
  }, [userId, userType, userModel])

  // ✅ Get following count
  useEffect(() => {
    if (userId && userModel && accessToken) {
      const fetchFollowingCount = async () => {
        try {
          const modelName = getModelName(userType)
          const response = await getFollowingCount(
            accessToken, 
            userId, 
            modelName
          )
          if (response.success) {
            setFollowingCount(response.data?.followingCount || 0)
          }
        } catch (error) {
          console.error('Error fetching following count:', error)
        }
      }
      fetchFollowingCount()
    }
  }, [accessToken, userId, userType, userModel])

  // Handle follow/unfollow
  const handleFollowToggle = async () => {
    if (!accessToken) {
      toast.error("Please login to follow users")
      return
    }
    
    if (isOwnProfile) {
      toast.error("You cannot follow yourself")
      return
    }
    
    const previousState = isFollowing
    setIsFollowing(!isFollowing)
    
    try {
      const modelName = getModelName(userType)
      let response;
      
      if (!previousState) {
        response = await followUser(accessToken, userId, modelName)
      } else {
        response = await unfollowUser(accessToken, userId, modelName)
      }
      
      if (response.success) {
        if (response.data?.followersCount !== undefined) {
          setFollowersCount(response.data.followersCount)
        }
        toast.success(!previousState ? "Followed" : "Unfollowed")
      } else {
        setIsFollowing(previousState)
        toast.error(response.message || "Something went wrong")
      }
    } catch (error: any) {
      setIsFollowing(previousState)
      console.error('Follow error:', error)
      toast.error(error.response?.data?.message || "Something went wrong")
    }
  }

  // ✅ Handle block user
  const handleBlockClick = () => {
    if (isOwnProfile) {
      toast.error("You cannot block yourself")
      return
    }
    if (isBlocked) {
      toast.error("User is already blocked")
      return
    }
    setShowBlockConfirm(true)
  }

  const confirmBlock = async () => {
    if (!accessToken) {
      toast.error("Please login to block users")
      return
    }
    if (!userId) {
      toast.error("Unable to block this user")
      return
    }

    setIsBlocking(true)
    try {
      const response = await blockAccountCustomer(accessToken, userId, "block")
      
      if (response.success) {
        setIsBlocked(true)
        toast.success("User blocked successfully")
        setShowBlockConfirm(false)
        // Optionally redirect to home or refresh
        setTimeout(() => {
          router.push("/home")
        }, 1500)
      } else {
        toast.error(response.message || "Failed to block user")
      }
    } catch (error) {
      console.error("Error blocking user:", error)
      toast.error("Something went wrong. Please try again.")
    } finally {
      setIsBlocking(false)
    }
  }

  const cancelBlock = () => {
    setShowBlockConfirm(false)
  }

  // Check if already reported
  useEffect(() => {
    if (accessToken && userId && !isOwnProfile && userModel) {
      const checkReport = async () => {
        setIsCheckingReport(true)
        try {
          const response = await checkReportStatus(accessToken, userId)
          if (response.success && response.hasReported) {
            setHasReported(true)
          }
        } catch (error) {
          console.error("Error checking report status:", error)
        } finally {
          setIsCheckingReport(false)
        }
      }
      checkReport()
    }
  }, [accessToken, userId, isOwnProfile, userModel])

  const handleReportClick = () => {
    if (isOwnProfile) {
      toast.error("You cannot report your own profile")
      return
    }
    if (hasReported) {
      toast.error("You have already reported this profile")
      return
    }
    setShowReportConfirm(true)
  }

  const confirmReport = async () => {
    if (!accessToken) {
      toast.error("Please login to report a profile")
      return
    }
    if (!userId || !userModel) {
      toast.error("Unable to report this profile")
      return
    }

    setIsReporting(true)
    try {
      const response = await reportProfile(accessToken, userId, userModel)
      
      if (response.success) {
        setHasReported(true)
        toast.success(response.message || "Profile reported successfully")
        setShowReportConfirm(false)
      } else {
        toast.error(response.message || "Failed to report profile")
      }
    } catch (error) {
      console.error("Error reporting profile:", error)
      toast.error("Something went wrong. Please try again.")
    } finally {
      setIsReporting(false)
    }
  }

  const cancelReport = () => {
    setShowReportConfirm(false)
  }

  const handleShareProfile = () => {
    const url = window.location.href
    navigator.clipboard.writeText(url)
    toast.success("Profile link copied to clipboard!")
  }

  const displayName = name || "User"
  const displayUsername = username || "@user"
  const displayBio = bio || ""
  const displayAvatar = avatar || null

  const getInitial = () => {
    if (!displayName) return "?"
    return displayName.charAt(0).toUpperCase()
  }

  // Helper function to format number (e.g., 1000 -> 1K)
  const formatNumber = (num: number) => {
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
    return num.toString()
  }

  return (
    <>
      <div className="px-4 md:px-6 pt-6 pb-4 border-b border-border/50">
        {/* Top Row: Avatar + Name + Actions */}
        <div className="flex items-start gap-4 md:gap-6">
          {/* Avatar */}
          <div className="shrink-0">
            <div className={cn("relative rounded-2xl", config.bgGlow)}>
              <div className={cn("rounded-xl border-2 overflow-hidden", config.borderColor)}>
                <div className="w-20 h-20 md:w-28 md:h-28 bg-secondary flex items-center justify-center text-2xl md:text-3xl font-bold text-muted-foreground">
                  {displayAvatar ? (
                    <img src={displayAvatar} alt={displayName} className="w-full h-full object-cover" />
                  ) : (
                    getInitial()
                  )}
                </div>
              </div>
              {isPremium && (
                <div className="absolute -top-1 -right-1 w-6 h-6 rounded-full bg-gradient-to-br from-amber-400 to-amber-600 flex items-center justify-center">
                  <Sparkles className="h-3 w-3 text-white" />
                </div>
              )}
            </div>
          </div>

          {/* Name, Username, Type Badge */}
         {/* Name, Username, Type Badge - Updated Layout */}
<div className="flex-1 min-w-0">
  {/* Row 1: Name + Verified Badge + Type Badge */}
  <div className="flex items-center gap-2 flex-wrap">
    <h1 className="text-xl md:text-2xl font-bold text-foreground truncate">{displayName}</h1>
    {isVerified && (
      <BadgeCheck className={cn("h-5 w-5 shrink-0", config.textColor)} />
    )}
    <span className={cn(
      "px-2.5 py-0.5 rounded-full text-xs font-semibold shrink-0",
      config.color,
      "text-white"
    )}>
      {accountTypeLabel}
    </span>
  </div>
  
  {/* Row 2: Username */}
  <p className="text-muted-foreground text-sm mt-0.5">{displayUsername}</p>
  
  {/* Row 3: Designation - You'll need to add this to your props */}
  {/* If you have a designation field, add it here */}
  {designation && (
    <p className="text-foreground/80 text-sm mt-1 font-medium">{designation}</p>
  )}
  
  {/* Row 4: Address */}
  {address && (
    <p className="text-muted-foreground text-xs mt-1 flex items-center gap-1">
      <MapPinned className="h-3 w-3" />
      {address}
    </p>
  )}
  
  {/* Row 5: Location, Website, Joined date */}
  <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-muted-foreground">
    {location && (
      <span className="flex items-center gap-1">
        <MapPin className="h-3 w-3" />
        {location}
      </span>
    )}
    {website && (
      <a 
        href={website} 
        target="_blank" 
        rel="noopener noreferrer"
        className={cn("flex items-center gap-1 hover:underline", config.textColor)}
      >
        <LinkIcon className="h-3 w-3" />
        {website.replace(/^https?:\/\//, '')}
      </a>
    )}
    <span className="flex items-center gap-1">
      <Calendar className="h-3 w-3" />
      Joined {joinedDate}
    </span>
  </div>
</div>

          {/* Actions */}
          <div className="flex items-center gap-2 shrink-0">
            {/* Follow Button - Only for others' profiles */}
            {!isOwnProfile && (
              <Button 
                size="sm" 
                className={`gap-1.5 cursor-pointer ${isFollowing ? 'bg-secondary text-foreground hover:bg-secondary/80' : ''}`}
                onClick={handleFollowToggle}
              >
                {isFollowing ? (
                  <>
                    <UserCheck className="h-4 w-4" />
                    <span className="hidden sm:inline">Following</span>
                  </>
                ) : (
                  <>
                    <UserPlus className="h-4 w-4" />
                    <span className="hidden sm:inline">Follow</span>
                  </>
                )}
              </Button>
            )}
            
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm" className="px-2 cursor-pointer">
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {isOwnProfile && (
                  <DropdownMenuItem onClick={() => router.push("/settings/profile")}>
                    <User className="h-4 w-4 mr-2" />
                    Edit Profile
                  </DropdownMenuItem>
                )}

                <DropdownMenuItem onClick={handleShareProfile}>
                  <Share2 className="h-4 w-4 mr-2" />
                  Share Profile
                </DropdownMenuItem>
                
                {/* ✅ BLOCK USER - For others' profiles only */}
                {!isOwnProfile && !isBlocked && (
                  <DropdownMenuItem 
                    onClick={handleBlockClick}
                    className="text-primary"
                    disabled={isBlocked || isCheckingBlock}
                  >
                    {isCheckingBlock ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : isBlocked ? (
                      <CheckCircle className="h-4 w-4 mr-2" />
                    ) : (
                      <Ban className="h-4 w-4 mr-2" />
                    )}
                    {isBlocked ? "Blocked" : "Block User"}
                  </DropdownMenuItem>
                )}
                
                {/* Report option - only for others */}
                {!isOwnProfile && (
                  <DropdownMenuItem 
                    onClick={handleReportClick}
                    className="text-destructive"
                    disabled={hasReported || isCheckingReport}
                  >
                    {isCheckingReport ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : hasReported ? (
                      <CheckCircle className="h-4 w-4 mr-2" />
                    ) : (
                      <Flag className="h-4 w-4 mr-2" />
                    )}
                    {hasReported ? "Reported" : "Report"}
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Bio */}
        <p className="mt-4 text-foreground/90 text-sm leading-relaxed max-w-3xl">{displayBio}</p>

        {/* Badges */}
        {badges && badges.length > 0 && (
          <div className="flex flex-wrap gap-2 mt-3">
            {badges.map((badge) => (
              <span 
                key={badge}
                className={cn(
                  "px-2.5 py-1 rounded-full text-xs font-medium border",
                  config.borderColor,
                  config.bgGlow,
                  config.textColor
                )}
              >
                {badge}
              </span>
            ))}
          </div>
        )}

        {/* Stats Row */}
        <div className="flex flex-wrap items-center gap-4 md:gap-6 mt-4 pt-4 border-t border-border/30">
          {(stats?.ideas ?? 0) > 0 && (
            <div className="flex items-center gap-1.5">
              <Lightbulb className="w-4 h-4 text-muted-foreground" />
              <span className="font-bold text-foreground">{formatNumber(stats?.ideas ?? 0)}</span>
            </div>
          )}
          
          {(stats?.likes ?? 0) > 0 && (
            <div className="flex items-center gap-1.5">
              <Image
                src="/icons/like_filled.svg"
                alt="likes"
                width={18}
                height={18}
                className="w-[18px] h-[18px]"
              />
              <span className="font-bold text-foreground">{formatNumber(stats?.likes ?? 0)}</span>
            </div>
          )}
          
          {(stats?.dislikes ?? 0) > 0 && (
            <div className="flex items-center gap-1.5">
              <Image
                src="/icons/dislike_filled.svg"
                alt="dislikes"
                width={18}
                height={18}
                className="w-[18px] h-[18px]"
              />
              <span className="font-bold text-foreground">{formatNumber(stats?.dislikes ?? 0)}</span>
            </div>
          )}
          
          {/* FOLLOWERS */}
          <div 
            className="flex items-center gap-1.5 cursor-pointer hover:opacity-80 transition-opacity"
            onClick={() => {
              router.push(`/${username}/followers`)
            }}
          >
            <span className="font-bold text-foreground">{formatNumber(followersCount)}</span>
            <span className="text-muted-foreground text-sm">
              {followersCount === 1 ? 'Follower' : 'Followers'}
            </span>
          </div>

          {/* FOLLOWING */}
          <div 
            className="flex items-center gap-1.5 cursor-pointer hover:opacity-80 transition-opacity"
            onClick={() => {
              router.push(`/${username}/following`)
            }}
          >
            <span className="font-bold text-foreground">{formatNumber(followingCount)}</span>
            <span className="text-muted-foreground text-sm">Following</span>
          </div>
          
          {stats?.deals !== undefined && (
            <div className="flex items-center gap-1.5">
              <span className="font-bold text-foreground">{formatNumber(stats.deals)}</span>
              <span className="text-muted-foreground text-sm">Deals</span>
            </div>
          )}
        </div>
      </div>

      {/* Block Confirmation Modal */}
      {showBlockConfirm && (
        <div className="fixed inset-0 bg-black/80 z-[9999] flex items-center justify-center p-4">
          <div className="bg-background border border-border rounded-2xl max-w-md w-full p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-red-500/10 flex items-center justify-center">
                <Ban className="h-5 w-5 text-primary" />
              </div>
              <h2 className="text-xl font-bold text-foreground">Block User</h2>
            </div>
            
            <p className="text-muted-foreground mb-6">
              Are you sure you want to block <span className="font-semibold text-foreground">{displayName}</span>?
              Blocked users will not be able to see your posts or interact with you.
            </p>
            
            <div className="flex justify-end gap-3">
              <Button className="cursor-pointer" variant="outline" onClick={cancelBlock} disabled={isBlocking}>
                Cancel
              </Button>
              <Button 
                
                onClick={confirmBlock}
                disabled={isBlocking}
                className="gap-2 cursor-pointer bg-primary "
              >
                {isBlocking ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Blocking...
                  </>
                ) : (
                  <>
                    <Ban className="h-4 w-4" />
                    Block User
                  </>
                )}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Report Confirmation Modal */}
      {showReportConfirm && (
        <div className="fixed inset-0 bg-black/80 z-[9999] flex items-center justify-center p-4">
          <div className="bg-background border border-border rounded-2xl max-w-md w-full p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-full bg-destructive/10 flex items-center justify-center">
                <Flag className="h-5 w-5 text-destructive" />
              </div>
              <h2 className="text-xl font-bold text-foreground">Report Profile</h2>
            </div>
            
            <p className="text-muted-foreground mb-6">
              Are you sure you want to report <span className="font-semibold text-foreground">{displayName}</span>'s profile?
              Our team will review this report and take appropriate action.
            </p>
            
            <div className="flex justify-end gap-3">
              <Button className="cursor-pointer" variant="outline" onClick={cancelReport} disabled={isReporting}>
                Cancel
              </Button>
              <Button 
                variant="destructive" 
                onClick={confirmReport}
                disabled={isReporting}
                className="gap-2 cursor-pointer"
              >
                {isReporting ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Reporting...
                  </>
                ) : (
                  <>
                    <Flag className="h-4 w-4" />
                    Report
                  </>
                )}
              </Button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}