"use client";

/**
 * Share toggle for a saved chart. When chart has a shareToken, shows the
 * public URL with a copy button; toggling off clears the token.
 */
import { useState, useTransition } from "react";
import { Copy, Check, Eye, EyeOff, Loader2 } from "lucide-react";
import { toggleShareAction } from "@/app/la-so/_actions";

type Props = {
  chartId: string;
  shareToken: string | null;
};

export function ShareToggle({ chartId, shareToken }: Props) {
  const [pending, startTransition] = useTransition();
  const [copied, setCopied] = useState(false);
  const isShared = shareToken !== null;

  function toggle() {
    const fd = new FormData();
    fd.set("id", chartId);
    startTransition(async () => {
      await toggleShareAction(fd);
    });
  }

  async function copy() {
    if (!shareToken) return;
    const url = `${window.location.origin}/la-so/${shareToken}`;
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard blocked — fallback: select the text input
      const el = document.getElementById(`share-url-${chartId}`) as HTMLInputElement | null;
      el?.select();
    }
  }

  if (!isShared) {
    return (
      <button
        type="button"
        onClick={toggle}
        disabled={pending}
        className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 hover:text-brand-gold inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-xs disabled:opacity-50"
      >
        {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Eye className="h-3 w-3" />}
        Tạo link chia sẻ
      </button>
    );
  }

  const url =
    typeof window !== "undefined"
      ? `${window.location.origin}/la-so/${shareToken}`
      : `/la-so/${shareToken}`;

  return (
    <div className="inline-flex items-center gap-1.5 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-2 py-1">
      <input
        id={`share-url-${chartId}`}
        readOnly
        value={url}
        onClick={(e) => (e.target as HTMLInputElement).select()}
        className="text-ink-primary w-56 truncate bg-transparent font-mono text-[11px] focus:outline-none"
      />
      <button
        type="button"
        onClick={copy}
        className="text-emerald-300 hover:text-emerald-200"
        title="Sao chép URL"
      >
        {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
      </button>
      <button
        type="button"
        onClick={toggle}
        disabled={pending}
        className="text-ink-muted hover:text-brand-red text-[11px]"
        title="Tắt chia sẻ (xoá link)"
      >
        {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <EyeOff className="h-3 w-3" />}
      </button>
    </div>
  );
}
