"use client"

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Star, MessageCircle, Music } from 'lucide-react'
import type { Post } from "@/types/post"
import { getDisplayName, getAvatarUrl } from "@/types/post"
import { cn } from "@/lib/utils"
import Link from "next/link"
import { formatDistanceToNow } from "date-fns"
import { motion, AnimatePresence } from "framer-motion"
import { useState } from "react"

interface PostCardProps {
  post: Post
  onLike: (postId: string) => void
  onClick?: () => void
}

export function PostCard({ post, onLike, onClick }: PostCardProps) {
  const [showStarAnimation, setShowStarAnimation] = useState(false)
  
  const displayName = getDisplayName(post.author)
  const avatarUrl = getAvatarUrl(post.author)
  const timestamp = post.timestamp || (post.createdAt ? formatDistanceToNow(new Date(post.createdAt), { addSuffix: true }) : '')
  const likesCount = post.likesCount ?? post.likes ?? 0
  const repliesCount = post.repliesCount ?? post.comments ?? post.replies?.length ?? 0
  const mediaUrl = post.mediaUrl || post.imageUrl
  
  // Detect if media is video or image
  const isVideo = mediaUrl && (
    mediaUrl.includes('.mp4') || 
    mediaUrl.includes('.webm') || 
    mediaUrl.includes('.ogg') ||
    mediaUrl.includes('.mov')
  )

  const handleLikeClick = () => {
    // Trigger animation
    setShowStarAnimation(true)
    setTimeout(() => setShowStarAnimation(false), 600)
    
    // Call parent like handler
    onLike(post.id)
  }

  return (
    <div className="bg-card rounded-xl border border-border p-4 space-y-4">
      <div className="flex gap-3">
        <Link href={`/profile/${post.author.id}`}>
          <Avatar className="w-10 h-10 cursor-pointer hover:opacity-80 transition-opacity">
            <AvatarImage src={avatarUrl} />
            <AvatarFallback>{displayName[0]?.toUpperCase() || 'U'}</AvatarFallback>
          </Avatar>
        </Link>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <Link 
              href={`/profile/${post.author.id}`}
              className="font-semibold text-sm text-foreground hover:underline cursor-pointer"
            >
              {displayName}
            </Link>
            <span className="text-xs text-muted-foreground">{timestamp}</span>
          </div>
          {post.author.username && (
            // <Link 
            //   href={`/profile/${post.author.id}`}
            //   className="text-sm text-muted-foreground hover:underline cursor-pointer"
            // >
              <span className="text-sm text-muted-foreground hover:underline">{post.author.username}</span>
            // </Link>
          )}
        </div>
      </div>

      <p className="text-base text-foreground leading-relaxed whitespace-pre-wrap">{post.content}</p>

      {mediaUrl && (
        <div className="rounded-lg overflow-hidden bg-muted">
          {isVideo ? (
            <video 
              src={mediaUrl} 
              controls 
              className="w-full h-auto max-h-[500px] object-contain"
              preload="metadata"
            >
              Your browser does not support the video tag.
            </video>
          ) : (
            <img 
              src={mediaUrl} 
              alt="Post media" 
              className="w-full h-auto object-cover" 
            />
          )}
        </div>
      )}

      {post.musicUrl && (
        <div className="bg-secondary rounded-lg p-4 flex items-center gap-4">
          <div className="w-12 h-12 bg-primary/20 rounded flex items-center justify-center">
            <Music className="w-6 h-6 text-primary" />
          </div>
          <div className="flex-1">
            <p className="font-semibold text-sm">{post.musicTitle}</p>
            <p className="text-xs text-muted-foreground">{post.musicArtist}</p>
          </div>
        </div>
      )}

      <div className="flex items-center gap-6 pt-2">
        <div className="relative">
          <Button
            variant="ghost"
            size="sm"
            onClick={handleLikeClick}
            className={cn(
              "gap-2 px-2 transition-all duration-200",
              post.isLiked && "text-yellow-500 hover:text-yellow-600"
            )}
          >
            <motion.div
              animate={post.isLiked ? { scale: [1, 1.3, 1], rotate: [0, 20, -20, 0] } : {}}
              transition={{ duration: 0.4 }}
            >
              <Star 
                className={cn(
                  "w-5 h-5 transition-all", 
                  post.isLiked && "fill-yellow-500 text-yellow-500"
                )} 
              />
            </motion.div>
            <span className="text-sm font-medium">{likesCount}</span>
          </Button>

          {/* Popout star animation */}
          <AnimatePresence>
            {showStarAnimation && (
              <motion.div
                initial={{ scale: 0, opacity: 1, y: 0 }}
                animate={{ 
                  scale: [1, 1.5, 2],
                  opacity: [1, 0.8, 0],
                  y: [-20, -40, -60]
                }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.6, ease: "easeOut" }}
                className="absolute left-1/2 top-0 -translate-x-1/2 pointer-events-none"
              >
                <Star className="w-8 h-8 fill-yellow-400 text-yellow-400" />
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        <Button variant="ghost" size="sm" className="gap-2 px-2" onClick={onClick}>
          <MessageCircle className="w-5 h-5" />
          <span className="text-sm font-medium">{repliesCount}</span>
        </Button>
      </div>
    </div>
  )
}
