"use client";

import Link from "next/link";
import { X, BarChart3 } from "lucide-react";
import { Avatar } from "./Avatar";
import { useEscapeKey } from "@/lib/use-escape-key";
import type { PollOption, User } from "@/lib/types";

/** Lists who voted, grouped by the option they chose. */
export function PollVotersModal({
  poll,
  voters,
  icons,
  onClose,
}: {
  poll: PollOption[];
  voters: Record<string, User[]>;
  icons: string[];
  onClose: () => void;
}) {
  useEscapeKey(onClose);
  const total = Object.values(voters).flat().length;

  return (
    <div
      className="fixed inset-0 z-[60] 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-[75vh] 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">
            <BarChart3 size={16} className="text-sky-500" /> Votes
            <span className="text-neutral-400 font-normal">({total})</span>
          </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">
          {poll.map((option, i) => {
            const list = voters[option.id] ?? [];
            if (list.length === 0) return null;
            return (
              <div key={option.id} className="mb-3">
                <div className="flex items-center gap-2 px-2 py-1.5 text-xs font-bold text-neutral-500">
                  <span className="text-base leading-none">
                    {option.icon || icons[i % icons.length]}
                  </span>
                  <span className="truncate">{option.text}</span>
                  <span className="ml-auto shrink-0">{list.length}</span>
                </div>
                {list.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={34} />
                    <span className="min-w-0">
                      <span className="block text-sm font-semibold truncate">{u.name}</span>
                    </span>
                  </Link>
                ))}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
