import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FiMessageSquare, FiArrowUp, FiArrowDown, FiShare2, FiBookmark } from "react-icons/fi";
import IconButton from "@/components/ui/IconButton";
import { apiSocialPostsVoteCreate } from "@/api/generated/private/posts/posts";
import { privateApi } from "@/api/privateClient";
import SharePopup from "./SharePopup";

interface Props {
  postId: number;
  replyCount?: number;
  voteScore?: number;
  initialUserVote?: -1 | 0 | 1;
  initialIsSaved?: boolean;
  initialSaveCount?: number;
  onReplyClick?: () => void;
}

export default function PostActions({
  postId,
  replyCount,
  voteScore,
  initialUserVote,
  initialIsSaved,
  initialSaveCount,
  onReplyClick,
}: Props) {
  const { t } = useTranslation("social");
  const [vote, setVote] = useState<-1 | 0 | 1>(initialUserVote ?? 0);
  const [score, setScore] = useState(voteScore ?? 0);
  const [busy, setBusy] = useState(false);
  const [showShare, setShowShare] = useState(false);
  const [upHover, setUpHover] = useState(false);
  const [downHover, setDownHover] = useState(false);
  const [saved, setSaved] = useState(initialIsSaved ?? false);
  const [saveCount, setSaveCount] = useState(initialSaveCount ?? 0);

  async function castVote(value: 1 | -1) {
    if (busy) return;
    setBusy(true);
    try {
      const next: -1 | 0 | 1 = vote === value ? 0 : value;
      const delta = next - vote;
      setScore((s) => s + delta);
      setVote(next);
      await apiSocialPostsVoteCreate(postId, { vote: value } as never);
    } finally {
      setBusy(false);
    }
  }

  async function toggleSave() {
    const next = !saved;
    setSaved(next);
    setSaveCount((c) => c + (next ? 1 : -1));
    try {
      await privateApi.post(`/api/social/posts/${postId}/save/`);
    } catch {
      setSaved(!next);
      setSaveCount((c) => c + (next ? -1 : 1));
    }
  }

  const upActive = vote === 1;
  const downActive = vote === -1;

  return (
    <>
      <div className="mt-3 flex items-center gap-3 text-brand-text/70">
        {/* Reply */}
        <button
          type="button"
          onClick={onReplyClick}
          className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-2 text-sm hover:bg-brand-lines/10 hover:text-brand-accent transition-colors"
          aria-label={t("post.actions.reply")}
          title={t("post.actions.reply")}
        >
          <FiMessageSquare size={16} />
          {typeof replyCount === "number" && replyCount > 0 && (
            <span className="text-xs tabular-nums">{replyCount}</span>
          )}
        </button>

        {/* Vote pill */}
        <div className="inline-flex items-center overflow-hidden rounded-full border border-brand-lines/20">
          {/* Upvote */}
          <div
            role="button"
            tabIndex={0}
            aria-label={t("post.actions.upvote")}
            aria-disabled={busy}
            onClick={() => !busy && castVote(1)}
            onKeyDown={(e) => e.key === "Enter" && !busy && castVote(1)}
            onMouseEnter={() => setUpHover(true)}
            onMouseLeave={() => setUpHover(false)}
            className={[
              "relative flex cursor-pointer items-center justify-center px-2.5 py-2 select-none",
              busy ? "opacity-50 pointer-events-none" : "",
              "before:absolute before:inset-0 before:bg-gradient-to-br before:from-white/90 before:to-sky-200/60 before:transition-opacity before:duration-200",
              upActive ? "before:opacity-100" : upHover ? "before:opacity-40" : "before:opacity-0",
            ].join(" ")}
          >
            <FiArrowUp
              size={16}
              style={{ color: upActive ? "rgb(12 74 110)" : undefined }}
              className="relative z-10 text-brand-text/50"
            />
          </div>

          <div className="w-px self-stretch bg-brand-lines/20" />

          <span
            className={[
              "min-w-[2rem] px-1.5 text-center text-xs tabular-nums transition-colors duration-200",
              upActive || downActive ? "!text-sky-500" : "text-brand-text/50",
            ].join(" ")}
          >
            {score}
          </span>

          <div className="w-px self-stretch bg-brand-lines/20" />

          {/* Downvote */}
          <div
            role="button"
            tabIndex={0}
            aria-label={t("post.actions.downvote")}
            aria-disabled={busy}
            onClick={() => !busy && castVote(-1)}
            onKeyDown={(e) => e.key === "Enter" && !busy && castVote(-1)}
            onMouseEnter={() => setDownHover(true)}
            onMouseLeave={() => setDownHover(false)}
            className={[
              "relative flex cursor-pointer items-center justify-center px-2.5 py-2 select-none",
              busy ? "opacity-50 pointer-events-none" : "",
              "before:absolute before:inset-0 before:bg-gradient-to-br before:from-white/90 before:to-sky-200/60 before:transition-opacity before:duration-200",
              downActive ? "before:opacity-100" : downHover ? "before:opacity-40" : "before:opacity-0",
            ].join(" ")}
          >
            <FiArrowDown
              size={16}
              style={{ color: downActive ? "rgb(12 74 110)" : undefined }}
              className="relative z-10 text-brand-text/50"
            />
          </div>
        </div>

        {/* Save */}
        <button
          type="button"
          onClick={toggleSave}
          className={[
            "inline-flex items-center gap-1.5 rounded-full px-2.5 py-2 text-sm transition-colors hover:bg-brand-lines/10",
            saved ? "text-brand-accent" : "hover:text-brand-accent",
          ].join(" ")}
          aria-label={t("post.actions.save")}
          title={t("post.actions.save")}
        >
          <FiBookmark size={16} fill={saved ? "currentColor" : "none"} />
          {saveCount > 0 && <span className="text-xs tabular-nums">{saveCount}</span>}
        </button>

        {/* Share */}
        <IconButton
          icon={<FiShare2 size={16} />}
          label={t("post.actions.share")}
          onClick={() => setShowShare(true)}
        />
      </div>

      {showShare && (
        <SharePopup postId={postId} onClose={() => setShowShare(false)} />
      )}
    </>
  );
}
