"use client"

import { MoreHorizontal, Rocket, Edit, Trash2 } from "lucide-react"
import PlatformIcon from "@/Components/UI/PlatformIcon"
import PostReaction from "@/Components/UI/PostReaction"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import FailedReasonTooltip from "@/Components/UI/FailedReasonTooltip"

const PostCardGrid = ({ post, onMenuAction, openMenus, onToggleMenu }) => {
  const getStatusStyle = (status) => {
    const styles = {
      published: "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800",
      scheduled: "bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800",
      pending: "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-400 dark:border-amber-800",
      draft: "bg-gray-50 text-gray-700 border-gray-200 dark:bg-gray-900/20 dark:text-gray-400 dark:border-gray-700",
      failed: "bg-red-50 text-red-700 border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800",
    }
    return styles[status?.toLowerCase()] || styles.draft
  }

  return (
    <div className="group bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 shadow-sm hover:shadow-lg hover:border-gray-300 dark:hover:border-zinc-600 transition-all duration-200 overflow-hidden">
      {/* Header with Status and Menu */}
      <div className="p-4 pb-3 border-b border-gray-100 dark:border-zinc-700">
        <div className="flex items-center justify-between">
          <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium border ${getStatusStyle(post.status)}`}>
            {post.status || "Published"}
            {post.status?.toLowerCase() === 'failed' && (
              <FailedReasonTooltip
                reason={post.failedReason}
                fallbackMessage={post.failedReasonFallback}
              />
            )}
          </span>

          <div className="relative">
            <button
              onClick={(e) => onToggleMenu(post.id, e)}
              className="p-1.5 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
            >
              <MoreHorizontal className="w-4 h-4 text-gray-500 dark:text-gray-400" />
            </button>

            {openMenus[post.id] && (
              <div
                onClick={(e) => e.stopPropagation()}
                className="absolute right-0 top-full mt-1 bg-white dark:bg-zinc-800 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-xl py-1 z-50 min-w-[140px] ring-1 ring-black/5 dark:ring-white/10"
              >
                <button
                  onClick={() => onMenuAction(post.id, "edit")}
                  className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-zinc-700 flex items-center gap-2 transition-colors"
                >
                  <Edit className="w-3.5 h-3.5" />
                  Edit Post
                </button>
                <button
                  onClick={() => onMenuAction(post.id, "publish")}
                  className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-zinc-700 flex items-center gap-2 transition-colors"
                >
                  <Rocket className="w-3.5 h-3.5" />
                  Publish Now
                </button>
                <div className="border-t border-gray-100 dark:border-zinc-600 my-1"></div>
                <button
                  onClick={() => onMenuAction(post.id, "delete")}
                  className="w-full px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center gap-2 transition-colors"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                  Delete
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Author Info */}
      <div className="p-4 pb-3">
        <div className="flex items-center gap-3">
          <div className="relative flex-shrink-0">
            <Avatar className="h-9 w-9 ring-2 ring-gray-100 dark:ring-zinc-700">
              <AvatarImage src={post?.account?.avatar} alt="User Avatar" />
              <AvatarFallback className="text-xs font-medium">{post.author?.charAt(0) || "A"}</AvatarFallback>
            </Avatar>
            <div className="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full bg-white dark:bg-zinc-900 flex items-center justify-center ring-2 ring-white dark:ring-zinc-900">
              <PlatformIcon slug={post.platform?.slug} size={12} round={true} />
            </div>
          </div>
          <div className="min-w-0 flex-1">
            <p className="font-medium text-gray-900 dark:text-white text-sm truncate">{post.author || "James Clerk"}</p>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {new Date(post.date).toLocaleDateString(undefined, {
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </p>
          </div>
        </div>
      </div>

      {/* Media Section */}
      {post.media && post.media.length > 0 && (
        <div className="px-4 pb-3">
          <div className="rounded-lg overflow-hidden bg-gray-50 dark:bg-zinc-800">
            {post.media.length === 1 ? (
              post.media[0].isVideo ? (
                <video
                  src={post.media[0].thumbnail || "/placeholder.mp4"}
                  className="w-full aspect-[16/10] object-cover"
                  muted
                  playsInline
                />
              ) : (
                <img
                  src={post.media[0].url || "/placeholder.svg"}
                  alt={post.media[0].alt || "Post content"}
                  className="w-full aspect-[16/10] object-cover"
                />
              )
            ) : (
              <div className="grid grid-cols-2 gap-0.5">
                {post.media.slice(0, 3).map((item, index) =>
                  item.isVideo ? (
                    <video
                      key={item.id}
                      src={item.thumbnail || "/placeholder.mp4"}
                      className={`aspect-square object-cover ${index === 2 && post.media.length > 3 ? 'relative' : ''}`}
                      muted
                      playsInline
                    />
                  ) : (
                    <div key={item.id} className="relative">
                      <img
                        src={item.url || "/placeholder.svg"}
                        alt={item.alt || "Post content"}
                        className="w-full aspect-square object-cover"
                      />
                      {index === 2 && post.media.length > 3 && (
                        <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                          <span className="text-white font-semibold text-sm">+{post.media.length - 3}</span>
                        </div>
                      )}
                    </div>
                  )
                )}
                {post.media.length === 2 && (
                  <div className="aspect-square"></div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Content */}
      <div className="p-4 pt-0">
        <p className="text-gray-900 dark:text-white text-sm leading-relaxed line-clamp-3">
          {post.content || "Hey there! I'm excited to share with you..."}
        </p>
      </div>

      {/* Engagement Footer */}
      {post.engagement && (
        <div className="px-4 pb-4 pt-0 border-t border-gray-100 dark:border-zinc-700 mt-2">
          <div className="flex items-center justify-between pt-3">
            <div className="flex items-center gap-2">
              <div className="flex -space-x-0.5">
                <PostReaction reactKey="like" />
                <PostReaction reactKey="love" />
                <PostReaction reactKey="care" />
              </div>
              <span className="text-sm font-medium text-gray-600 dark:text-gray-400">
                {post.engagement?.reactions ? Object.values(post.engagement.reactions).reduce((a, b) => a + b, 0) : (post.metrics?.reactions ?? post.metrics?.likes ?? 0)}
              </span>
            </div>

            <div className="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
              <div className="flex items-center gap-1">
                <PostReaction reactKey="fbcomment" />
                <span>{post.engagement?.comments ?? post.metrics?.comments ?? 0}</span>
              </div>
              <div className="flex items-center gap-1">
                <PostReaction reactKey="fbshare" />
                <span>{post.engagement?.shares ?? post.metrics?.shares ?? 0}</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default PostCardGrid
