"use client";

import { useState, useRef, useEffect } from "react";
import { Heart, User, Zap } from "lucide-react";
import type { PostStatus, Network, Region } from "@/lib/types";

export type PostSource = "HUMAN" | "HUBSPOT";

const SOURCE_ICONS: Record<PostSource, typeof User> = {
  HUMAN: User,
  HUBSPOT: Zap,
};

const SOURCE_COLORS: Record<PostSource, string> = {
  HUMAN: "text-gray-500",
  HUBSPOT: "text-orange-500",
};

const STATUS_COLORS: Record<PostStatus, string> = {
  DRAFT: "bg-gray-100 text-gray-700",
  SCHEDULED: "bg-blue-100 text-blue-700",
  PUBLISHED: "bg-green-100 text-green-700",
  FAILED: "bg-red-100 text-red-700",
  PENDING_APPROVAL: "bg-yellow-100 text-yellow-700",
  REJECTED: "bg-orange-100 text-orange-700",
};

const NETWORK_DOTS: Record<Network, string> = {
  LINKEDIN: "bg-[#0A66C2]",
  TWITTER: "bg-[#1DA1F2]",
  FACEBOOK: "bg-[#1877F2]",
  INSTAGRAM: "bg-[#E4405F]",
};

export interface PostAnalyticsData {
  impressions: number;
  clicks: number;
  shares: number;
  comments: number;
  reactions: number;
}

const REGION_LEFT_BORDER: Record<Region, string> = {
  APAC: "border-l-2 border-l-blue-500",
  NA: "border-l-2 border-l-green-500",
  LATAM: "border-l-2 border-l-purple-500",
  EMEA: "border-l-2 border-l-amber-500",
  GLOBAL: "border-l-2 border-l-gray-400",
};

interface PostPillProps {
  title: string;
  status: PostStatus;
  networks: Network[];
  scheduledAt?: string;
  originalScheduledAt?: string | null;
  analytics?: PostAnalyticsData[];
  source?: PostSource;
  campaignName?: string | null;
  region?: Region | null;
  hasMedia?: boolean;
  onClick?: () => void;
}

function EngagementBadge({ analytics }: { analytics: PostAnalyticsData[] }) {
  const [showTooltip, setShowTooltip] = useState(false);
  const badgeRef = useRef<HTMLSpanElement>(null);

  const totals = analytics.reduce(
    (acc, a) => ({
      impressions: acc.impressions + a.impressions,
      likes: acc.likes + a.reactions,
      retweets: acc.retweets + a.shares,
      replies: acc.replies + a.comments,
    }),
    { impressions: 0, likes: 0, retweets: 0, replies: 0 }
  );

  const engagement = totals.likes + totals.retweets;
  const colorClass =
    engagement > 10
      ? "bg-green-500/15 text-green-700"
      : engagement > 0
        ? "bg-amber-500/15 text-amber-700"
        : "bg-gray-200/60 text-gray-500";

  // Close tooltip on outside click (mobile)
  useEffect(() => {
    if (!showTooltip) return;
    const handler = (e: MouseEvent) => {
      if (badgeRef.current && !badgeRef.current.contains(e.target as Node)) {
        setShowTooltip(false);
      }
    };
    document.addEventListener("click", handler, true);
    return () => document.removeEventListener("click", handler, true);
  }, [showTooltip]);

  return (
    <span
      ref={badgeRef}
      className="relative inline-flex flex-shrink-0"
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
      onClick={(e) => {
        e.stopPropagation();
        setShowTooltip((prev) => !prev);
      }}
    >
      <span
        className={`inline-flex items-center gap-0.5 rounded-full px-1 py-px text-[9px] font-semibold leading-none ${colorClass}`}
      >
        <Heart className="h-2 w-2" />
        {engagement}
      </span>
      {showTooltip && (
        <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 z-50 whitespace-nowrap rounded-md bg-gray-900 px-2.5 py-1.5 text-[10px] text-white shadow-lg">
          <span className="block">Impressions: {totals.impressions.toLocaleString()}</span>
          <span className="block">Likes: {totals.likes.toLocaleString()}</span>
          <span className="block">Retweets: {totals.retweets.toLocaleString()}</span>
          <span className="block">Replies: {totals.replies.toLocaleString()}</span>
          <span className="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900" />
        </span>
      )}
    </span>
  );
}

export function PostPill({ title, status, networks, scheduledAt, originalScheduledAt, analytics, source, campaignName, region, hasMedia, onClick }: PostPillProps) {
  const showBadge =
    status === "PUBLISHED" && analytics && analytics.length > 0;

  const timeLabel = scheduledAt
    ? new Date(scheduledAt).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })
    : null;

  const isRescheduled = originalScheduledAt && scheduledAt && originalScheduledAt !== scheduledAt;

  return (
    <button
      onClick={onClick}
      className={`w-full overflow-hidden rounded-full px-2 py-0.5 text-left text-xs font-medium ${STATUS_COLORS[status]} ${region ? REGION_LEFT_BORDER[region] : ""} hover:opacity-80 transition-opacity`}
    >
      <span className="flex items-center gap-1 whitespace-nowrap">
        {source && (() => { const SourceIcon = SOURCE_ICONS[source]; return <SourceIcon className={`h-2.5 w-2.5 flex-shrink-0 ${SOURCE_COLORS[source]}`} />; })()}
        {networks.slice(0, 2).map((n) => (
          <span key={n} className={`inline-block h-1.5 w-1.5 rounded-full flex-shrink-0 ${NETWORK_DOTS[n]}`} />
        ))}
        {hasMedia && <span className="shrink-0 text-xs" title="Has media" data-testid="media-badge">📷</span>}
        {isRescheduled && <span className="shrink-0 text-[10px] opacity-70" title="Rescheduled" data-testid="rescheduled-badge">↻</span>}
        {timeLabel && <span className="shrink-0 opacity-70">{timeLabel}</span>}
        <span className="truncate min-w-0">{title}</span>
        {campaignName && (
          <span className="shrink-0 inline-flex items-center rounded-full bg-purple-100 text-purple-700 px-1 py-px text-[8px] font-medium leading-none max-w-[50px] truncate" title={campaignName} data-testid="campaign-badge">
            {campaignName}
          </span>
        )}
        {region && (
          <span className="shrink-0 inline-flex items-center rounded-full px-1 py-px text-[8px] font-medium leading-none max-w-[40px] truncate bg-gray-100 text-gray-600" data-testid="region-pill-badge">
            {region}
          </span>
        )}
        {showBadge && <EngagementBadge analytics={analytics} />}
      </span>
    </button>
  );
}
