"use client"

import { useState } from "react"
import Link from "next/link"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
  ThumbsUp,
  ThumbsDown,
  Bookmark,
  Share2,
  MoreHorizontal,
  Flag,
  Sparkles,
  TrendingUp,
  Image as ImageIcon,
  FileText,
  Video,
  Play,
  ChevronRight,
} from "lucide-react"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

interface Attachment {
  type: "image" | "pdf" | "doc" | "video"
  url: string
  name: string
  thumbnail?: string
}

interface IdeaCardProps {
  idea: {
    id: string
    author: {
      name: string
      username: string
      avatar?: string
      country?: string
    }
    content: string
    category?: string
    likes: number
    dislikes: number
    timestamp: string
    isTrending?: boolean
    aiScore?: number
    attachments?: Attachment[]
  }
}

export function IdeaCard({ idea }: IdeaCardProps) {
  const [liked, setLiked] = useState(false)
  const [disliked, setDisliked] = useState(false)
  const [saved, setSaved] = useState(false)
  const [likes, setLikes] = useState(idea.likes)
  const [dislikes, setDislikes] = useState(idea.dislikes)

  const handleLike = () => {
    if (liked) {
      setLiked(false)
      setLikes(likes - 1)
    } else {
      setLiked(true)
      setLikes(likes + 1)
      if (disliked) {
        setDisliked(false)
        setDislikes(dislikes - 1)
      }
    }
  }

  const handleDislike = () => {
    if (disliked) {
      setDisliked(false)
      setDislikes(dislikes - 1)
    } else {
      setDisliked(true)
      setDislikes(dislikes + 1)
      if (liked) {
        setLiked(false)
        setLikes(likes - 1)
      }
    }
  }

  const truncatedContent = idea.content.length > 200 
    ? idea.content.slice(0, 200) + "..." 
    : idea.content

  const imageAttachments = idea.attachments?.filter(a => a.type === "image") || []
  const docAttachments = idea.attachments?.filter(a => a.type === "pdf" || a.type === "doc") || []
  const videoAttachments = idea.attachments?.filter(a => a.type === "video") || []

  return (
    <article className="group relative rounded-2xl glass glass-border p-5 transition-all duration-300 hover:border-primary/30">
      {/* Trending Badge */}
      {idea.isTrending && (
        <div className="absolute -top-2 -right-2 flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-xs font-bold text-accent-foreground shadow-lg">
          <TrendingUp className="h-3 w-3" />
          Trending
        </div>
      )}

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="relative">
            <Avatar className="h-11 w-11 ring-2 ring-border">
              <AvatarImage src={idea.author.avatar} alt={idea.author.name} />
              <AvatarFallback className="bg-secondary text-foreground font-semibold">
                {idea.author.name.split(" ").map((n) => n[0]).join("")}
              </AvatarFallback>
            </Avatar>
            {idea.author.country && (
              <span className="absolute -bottom-1 -right-1 text-base">{idea.author.country}</span>
            )}
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h4 className="font-semibold text-foreground">{idea.author.name}</h4>
              {idea.aiScore && idea.aiScore >= 80 && (
                <div className="flex items-center gap-1 rounded-full bg-primary/20 px-2 py-0.5">
                  <Sparkles className="h-3 w-3 text-primary" />
                  <span className="text-[10px] font-bold text-primary">{idea.aiScore}%</span>
                </div>
              )}
            </div>
            <p className="text-sm text-muted-foreground">@{idea.author.username}</p>
          </div>
        </div>

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary transition-colors">
              <MoreHorizontal className="h-5 w-5" />
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="glass glass-border">
            <DropdownMenuItem className="gap-2 cursor-pointer">
              <Share2 className="h-4 w-4" />
              Share
            </DropdownMenuItem>
            <DropdownMenuItem className="gap-2 cursor-pointer text-destructive">
              <Flag className="h-4 w-4" />
              Report
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Content */}
      <div className="mt-4">
        {idea.category && (
          <span className="mb-2 inline-block rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
            {idea.category}
          </span>
        )}
        <p className="text-foreground leading-relaxed">{truncatedContent}</p>
        
        {idea.content.length > 200 && (
          <Link 
            href={`/idea/${idea.id}`}
            className="inline-flex items-center gap-1 mt-2 text-sm font-medium text-primary hover:underline"
          >
            Read more
            <ChevronRight className="h-4 w-4" />
          </Link>
        )}
      </div>

      {/* Image Attachments */}
      {imageAttachments.length > 0 && (
        <div className="mt-4">
          <div className={`grid gap-2 ${imageAttachments.length === 1 ? '' : imageAttachments.length === 2 ? 'grid-cols-2' : 'grid-cols-2'}`}>
            {imageAttachments.slice(0, 4).map((img, idx) => (
              <div 
                key={idx}
                className={`relative rounded-xl overflow-hidden bg-secondary ${
                  imageAttachments.length === 1 ? 'aspect-video' : 
                  imageAttachments.length === 3 && idx === 0 ? 'row-span-2 aspect-square' : 'aspect-square'
                }`}
              >
                <img 
                  src={img.thumbnail || img.url || "/placeholder.svg"} 
                  alt={img.name}
                  className="w-full h-full object-cover"
                />
                {imageAttachments.length > 4 && idx === 3 && (
                  <div className="absolute inset-0 bg-background/80 flex items-center justify-center">
                    <span className="text-lg font-bold text-foreground">+{imageAttachments.length - 4}</span>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Video Attachment */}
      {videoAttachments.length > 0 && (
        <div className="mt-4">
          <div className="relative rounded-xl overflow-hidden bg-secondary aspect-video">
            <img 
              src={videoAttachments[0].thumbnail || "/placeholder.svg"} 
              alt={videoAttachments[0].name}
              className="w-full h-full object-cover"
            />
            <div className="absolute inset-0 flex items-center justify-center bg-background/40">
              <div className="flex h-14 w-14 items-center justify-center rounded-full bg-primary/90 text-primary-foreground">
                <Play className="h-6 w-6 ml-1" />
              </div>
            </div>
            {videoAttachments.length > 1 && (
              <div className="absolute bottom-2 right-2 rounded-full bg-background/80 px-2 py-1 text-xs font-medium">
                +{videoAttachments.length - 1} videos
              </div>
            )}
          </div>
        </div>
      )}

      {/* Document Attachments */}
      {docAttachments.length > 0 && (
        <div className="mt-4 flex flex-wrap gap-2">
          {docAttachments.map((doc, idx) => (
            <div 
              key={idx}
              className="flex items-center gap-2 rounded-lg bg-secondary/50 px-3 py-2 text-sm"
            >
              {doc.type === "pdf" ? (
                <FileText className="h-4 w-4 text-red-400" />
              ) : (
                <FileText className="h-4 w-4 text-blue-400" />
              )}
              <span className="text-muted-foreground truncate max-w-32">{doc.name}</span>
            </div>
          ))}
        </div>
      )}

      {/* Actions */}
      <div className="mt-5 flex items-center justify-between border-t border-border/30 pt-4">
        <div className="flex items-center gap-1">
          {/* Like */}
          <button
            onClick={handleLike}
            className={`flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all ${
              liked
                ? "bg-primary/20 text-primary"
                : "text-muted-foreground hover:bg-secondary hover:text-foreground"
            }`}
          >
            <ThumbsUp className={`h-4 w-4 ${liked ? "fill-primary" : ""}`} />
            <span>{likes}</span>
          </button>

          {/* Dislike */}
          <button
            onClick={handleDislike}
            className={`flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all ${
              disliked
                ? "bg-destructive/20 text-destructive"
                : "text-muted-foreground hover:bg-secondary hover:text-foreground"
            }`}
          >
            <ThumbsDown className={`h-4 w-4 ${disliked ? "fill-destructive" : ""}`} />
            <span>{dislikes}</span>
          </button>
        </div>

        <div className="flex items-center gap-2">
          <span className="text-xs text-muted-foreground">{idea.timestamp}</span>
          <button
            onClick={() => setSaved(!saved)}
            className={`flex h-9 w-9 items-center justify-center rounded-lg transition-all ${
              saved
                ? "bg-accent/20 text-accent"
                : "text-muted-foreground hover:bg-secondary hover:text-foreground"
            }`}
          >
            <Bookmark className={`h-5 w-5 ${saved ? "fill-accent" : ""}`} />
          </button>
          <Link
            href={`/idea/${idea.id}`}
            className="flex h-9 items-center gap-1 rounded-lg px-3 text-sm font-medium text-primary hover:bg-primary/10 transition-all"
          >
            View
            <ChevronRight className="h-4 w-4" />
          </Link>
        </div>
      </div>
    </article>
  )
}
