import { useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { FiX, FiLink, FiShare2, FiCheck } from "react-icons/fi";

interface Props {
  postId: number;
  onClose: () => void;
}

export default function SharePopup({ postId, onClose }: Props) {
  const { t } = useTranslation("social");
  const url = `${window.location.origin}/social/post/${postId}`;
  const [copied, setCopied] = useState(false);

  async function copyLink() {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // fallback for browsers without clipboard API
      const ta = document.createElement("textarea");
      ta.value = url;
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }

  async function nativeShare() {
    await navigator.share({ url, title: t("post.share.nativeTitle") });
  }

  return createPortal(
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />

      <div
        className="relative w-full max-w-sm rounded-2xl border border-brand-lines/20 bg-brand-bg shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-brand-lines/10 px-5 py-4">
          <h3 className="font-semibold text-brand-text">{t("post.share.title")}</h3>
          <button
            type="button"
            onClick={onClose}
            className="flex h-8 w-8 items-center justify-center rounded-full text-brand-text/60 hover:bg-brand-lines/10 hover:text-brand-text transition-colors"
            aria-label={t("post.share.close")}
          >
            <FiX size={16} />
          </button>
        </div>

        {/* URL preview */}
        <div className="px-5 pt-4 pb-2">
          <div className="flex items-center gap-2 rounded-xl border border-brand-lines/20 bg-brand-bgLight/30 px-3 py-2.5">
            <FiLink size={14} className="shrink-0 text-brand-text/40" />
            <span className="truncate text-xs text-brand-text/60">{url}</span>
          </div>
        </div>

        {/* Actions */}
        <div className="flex flex-col gap-2 px-5 pb-5 pt-3">
          <button
            type="button"
            onClick={copyLink}
            className={[
              "flex items-center gap-3 rounded-xl border px-4 py-3 text-sm font-medium transition-colors",
              copied
                ? "border-green-500/40 bg-green-500/10 text-green-400"
                : "border-brand-lines/20 bg-brand-boxes/20 text-brand-text hover:bg-brand-boxes/40",
            ].join(" ")}
          >
            {copied ? <FiCheck size={16} /> : <FiLink size={16} />}
            {copied ? t("post.share.copied") : t("post.share.copyLink")}
          </button>

          {typeof navigator.share === "function" && (
            <button
              type="button"
              onClick={nativeShare}
              className="flex items-center gap-3 rounded-xl border border-brand-lines/20 bg-brand-boxes/20 px-4 py-3 text-sm font-medium text-brand-text hover:bg-brand-boxes/40 transition-colors"
            >
              <FiShare2 size={16} />
              {t("post.share.shareVia")}
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}
