"use client";

import { useAuth } from "@/lib/auth-context";
import clsx from "clsx";

import { useEffect, useState } from "react";
import Link from "next/link";
import { X, Heart } from "lucide-react";
import { Avatar } from "./Avatar";
import { useConnectionWords } from "@/lib/site-context";
import { useEscapeKey } from "@/lib/use-escape-key";
import type { User } from "@/lib/types";

const REACTION_EMOJI: Record<string, string> = {
  heart: "❤️", thumb: "👍", laugh: "😂", party: "🎉",
  wow: "😮", sad: "😢", angry: "😡", fire: "🔥",
};

export function PostLikers({
  postId,
  likeCount,
  refreshKey = 0,
}: {
  postId: string;
  likeCount: number;
  refreshKey?: number;
}) {
  const [likers, setLikers] = useState<(User & { reaction?: string })[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  // Only the first few avatars are needed for the inline row, but the list
  // is small enough that one fetch covers both the row and the popup.
  useEffect(() => {
    if (likeCount === 0) return;
    fetch(`/api/posts/${postId}/likers`)
      .then((r) => (r.ok ? r.json() : { likers: [] }))
      .then((d) => setLikers(d.likers || []))
      .catch(() => {});
  }, [postId, likeCount, refreshKey]);

  if (likeCount === 0 || likers.length === 0) return null;

  const shown = likers.slice(0, 2);
  const remaining = likeCount - shown.length;

  return (
    <>
      <button
        onClick={() => {
          setOpen(true);
          setLoading(likers.length === 0);
        }}
        title={`Liked by ${likers[0].name}${likeCount > 1 ? ` and ${likeCount - 1} others` : ""}`}
        className="pa-wholiked group flex items-center ml-1.5 mr-1"
      >
        {shown.map((u, i) => (
          <span
            key={u.id}
            className="pa-wav relative rounded-full ring-2 ring-white dark:ring-black"
            style={{ marginLeft: i === 0 ? 0 : -7, animationDelay: `${i * 0.08}s`, zIndex: shown.length - i + 1 }}
          >
            <Avatar user={u} size={20} />
            <span className="absolute -bottom-1 -right-1 text-[9px] leading-none">
              {REACTION_EMOJI[u.reaction ?? "heart"] ?? "❤️"}
            </span>
          </span>
        ))}
        {remaining > 0 && (
          <span
            className="pa-wav rounded-full ring-2 ring-white dark:ring-black bg-neutral-200 dark:bg-neutral-700 text-neutral-600 dark:text-neutral-200 text-[10px] font-bold w-5 h-5 flex items-center justify-center"
            style={{ marginLeft: -7, animationDelay: "0.16s", zIndex: 0 }}
          >
            +{remaining > 99 ? "99" : remaining}
          </span>
        )}
      </button>

      {open && (
        <LikersModal
          setLikers={setLikers}
          likers={likers}
          loading={loading}
          onClose={() => setOpen(false)}
        />
      )}
    </>
  );
}

function LikersModal({
  likers,
  setLikers,
  loading,
  onClose,
}: {
  likers: (User & { reaction?: string })[];
  /** So following someone updates the row without a reload. */
  setLikers: React.Dispatch<
    React.SetStateAction<(User & { reaction?: string })[]>
  >;
  loading: boolean;
  onClose: () => void;
}) {
  const cw = useConnectionWords();
  const { user: me } = useAuth();

  /** Follows or unfollows without leaving the list. */
  async function follow(u: User & { reaction?: string }) {
    const was = u.followedByViewer;

    setLikers((prev) =>
      prev.map((x) =>
        x.id === u.id ? { ...x, followedByViewer: !was } : x
      )
    );

    const res = await fetch(`/api/users/${u.username}/follow`, {
      method: "POST",
    }).catch(() => null);

    if (!res || !res.ok) {
      setLikers((prev) =>
        prev.map((x) => (x.id === u.id ? { ...x, followedByViewer: was } : x))
      );
      return;
    }

    window.dispatchEvent(
      new CustomEvent("xr-followed", { detail: { id: u.id, following: !was } })
    );
  }

  useEscapeKey(onClose);
  return (
    <div
      className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-neutral-950 rounded-2xl w-full max-w-sm shadow-2xl overflow-hidden max-h-[70vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 py-4 border-b border-neutral-100 dark:border-neutral-800 shrink-0">
          <span className="flex items-center gap-2 font-semibold">
            <Heart size={16} className="text-rose-500 fill-rose-500" /> Likes
          </span>
          <button onClick={onClose} className="text-neutral-400 hover:text-neutral-600 transition-colors">
            <X size={18} />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto px-3 py-2">
          {loading && <p className="text-sm text-neutral-400 text-center py-6">Loading…</p>}
          {likers.map((u) => (
            <Link
              key={u.id}
              href={`/${u.username}`}
              onClick={onClose}
              className="flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-neutral-50 dark:hover:bg-neutral-900 transition-colors"
            >
              <Avatar user={u} size={40} />
              <span className="lk-arrow" aria-hidden>
                <span className="lk-dash" />
                <span className="lk-head">▶</span>
              </span>
              <span className="lk-emoji">{REACTION_EMOJI[u.reaction ?? "heart"] ?? "❤️"}</span>
              <span className="min-w-0 flex-1">
                <span className="block text-sm font-semibold truncate flex items-center gap-1">
                  {u.name}
                  
                  {u.premium && <span className="text-amber-500 text-xs">👑</span>}
                </span>
                <span className="block text-xs text-neutral-400 truncate">
                  @{u.username}
                </span>
              </span>

              {/* Follow from here, without leaving the list. */}
              {u.id !== me?.id && (
                <button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    follow(u);
                  }}
                  className={clsx("lk-follow", u.followedByViewer && "on")}
                >
                  {u.followedByViewer ? cw.connected : cw.connect}
                </button>
              )}
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}
