"use client";

import { Avatar } from "./Avatar";
import { formatCount } from "@/lib/utils";
import type { PollOption, User } from "@/lib/types";
import clsx from "clsx";

const POLL_ICONS = ["⚡", "🎵", "🎬", "👥", "🌙", "🤖"];
const HUES = [200, 280, 150, 30, 340, 90];

export function PostPoll({
  poll,
  myVote,
  totalVotes,
  voters,
  layout,
  overPhoto,
  voting,
  onVote,
  onOpenVoters,
}: {
  poll: PollOption[];
  myVote?: string;
  totalVotes: number;
  voters: Record<string, User[]>;
  layout?: "vertical" | "horizontal";
  overPhoto: boolean;
  voting: boolean;
  onVote: (optionId: string, el: HTMLElement, hue: number) => void;
  onOpenVoters?: () => void;
}) {
  const top = Math.max(...poll.map((o) => o.voteCount));
  const allVoters = Object.values(voters).flat();
  // Rows read better on top of an image, so overlays default to horizontal
  // unless the author explicitly picked vertical.
  const horizontal = layout ? layout === "horizontal" : overPhoto;

  return (
    <div className={overPhoto ? "poll-over" : "mt-3 px-1"}>
      {allVoters.length > 0 && (
        <button
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onOpenVoters?.();
          }}
          className={clsx(
            "flex items-center gap-2 mb-2 text-xs transition-colors",
            overPhoto
              ? "text-white/90 hover:text-white drop-shadow self-center absolute top-3 left-1/2 -translate-x-1/2"
              : "text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-200"
          )}
        >
          <span className="flex -space-x-2">
            {allVoters.slice(0, 2).map((v, i) => (
              <span
                key={v.id}
                style={{ zIndex: 2 - i }}
                className="rounded-full ring-2 ring-white dark:ring-black"
              >
                <Avatar user={v} size={20} effect={false} />
              </span>
            ))}
          </span>
          <span>
            {allVoters.length > 2 ? `+${allVoters.length - 2} · ` : ""}
            {totalVotes} {totalVotes === 1 ? "vote" : "votes"}
          </span>
        </button>
      )}

      <div className={clsx("pwrap", myVote ? "voted" : "idle")}>
        {horizontal ? (
          <div className="flex flex-col gap-2">
            {poll.map((option, i) => {
              const pct = totalVotes > 0 ? Math.round((option.voteCount / totalVotes) * 100) : 0;
              const isMine = myVote === option.id;
              const isTop = option.voteCount === top && top > 0;
              const hue = HUES[i % HUES.length];
              return (
                <button
                  key={option.id}
                  onClick={(e) => onVote(option.id, e.currentTarget, hue)}
                  disabled={voting}
                  className={clsx("prow", myVote && isMine && "win")}
                >
                  <span className="ptrack-h">
                    {!myVote && (
                      <span className="pghost-h" style={{ background: `hsl(${hue} 85% 60%)` }} />
                    )}
                    {myVote && (
                      <span
                        className="pfill-h"
                        style={{
                          width: `${pct}%`,
                          background: isMine
                            ? `linear-gradient(90deg, hsl(${hue} 90% 62%), hsl(${hue} 85% 45%))`
                            : `linear-gradient(90deg, hsl(${hue} 45% 62%), hsl(${hue} 40% 45%))`,
                        }}
                      />
                    )}
                    <span className="prow-label">
                      <span className="plabel">{option.icon || POLL_ICONS[i % POLL_ICONS.length]}</span>
                      <span className="truncate">{option.text}</span>
                      {myVote && isTop && <span className="text-emerald-400"> ✓</span>}
                      {(voters[option.id]?.length ?? 0) > 0 && (
                        <span className="pvoters ml-1">
                          {voters[option.id].slice(0, 3).map((v, vi) => (
                            <span key={v.id} style={{ marginLeft: vi === 0 ? 0 : -6 }}>
                              <Avatar user={v} size={15} effect={false} />
                            </span>
                          ))}
                        </span>
                      )}
                    </span>
                    {myVote && <span className="prow-pct">{pct}%</span>}
                  </span>
                </button>
              );
            })}
          </div>
        ) : (
          <div className="pchart rail" style={{ gap: poll.length > 5 ? 8 : 12 }}>
            {poll.map((option, i) => {
              const pct = totalVotes > 0 ? Math.round((option.voteCount / totalVotes) * 100) : 0;
              const isMine = myVote === option.id;
              const isTop = option.voteCount === top && top > 0;
              const hue = HUES[i % HUES.length];
              return (
                <button
                  key={option.id}
                  onClick={(e) => onVote(option.id, e.currentTarget, hue)}
                  disabled={voting}
                  className={clsx("pcol", myVote && isMine && "win", myVote && isTop && !isMine && "lead")}
                  style={poll.length <= 2 ? { flex: "0 0 58px" } : undefined}
                  title={option.text}
                >
                  {(voters[option.id]?.length ?? 0) > 0 && (
                    <span className="pvoters">
                      {voters[option.id].slice(0, 3).map((v, vi) => (
                        <span key={v.id} style={{ marginLeft: vi === 0 ? 0 : -6, zIndex: 3 - vi }}>
                          <Avatar user={v} size={16} effect={false} />
                        </span>
                      ))}
                    </span>
                  )}
                  <span className="ptrack">
                    {!myVote && (
                      <span className="pghost" style={{ background: `hsl(${hue} 85% 60%)` }} />
                    )}
                    {!myVote && totalVotes > 0 && <span className="ppct-pre">{pct}%</span>}
                    {myVote && (
                      <>
                        <span
                          className="pfill"
                          style={{
                            height: `${pct}%`,
                            background: isMine
                              ? `linear-gradient(180deg, hsl(${hue} 90% 62%), hsl(${hue} 85% 45%))`
                              : `linear-gradient(180deg, hsl(${hue} 45% 62%), hsl(${hue} 40% 45%))`,
                          }}
                        />
                        <span
                          className="ppct"
                          style={{ bottom: pct > 82 ? "6px" : `calc(${pct}% + 4px)` }}
                        >
                          {pct}%
                        </span>
                      </>
                    )}
                  </span>
                  <span className="plabel">{option.icon || POLL_ICONS[i % POLL_ICONS.length]}</span>
                  <span className="pname2">{option.text}</span>
                </button>
              );
            })}
          </div>
        )}

        {!myVote && (
          <div className="chartHint">
            <span className="hand">👆</span> Tap to vote
          </div>
        )}
      </div>

      {!myVote && !overPhoto && (
        <p className="phint">No votes yet · results appear live</p>
      )}
    </div>
  );
}
