"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { Loader2, RefreshCw, Share2 } from "lucide-react";
import { buttonVariants } from "@/components/ui/button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { createShare } from "@/lib/api/share";
import { CopyLinkItem } from "./channels/CopyLinkItem";
import { WeChatShareItem } from "./channels/WeChatShareItem";

/**
 * 分享按钮 (受控 Popover): 分享的是【已发布的持久 URL】而非易失的沙箱预览。
 * 未发布时父组件在 onOpenChange 里拦截去走发布确认流程 (分享即发布); 发布成功后
 * 父组件置 open, 本组件懒建分享链并展示复制链接 / 微信二维码。
 */
export const ShareButton = ({
  open,
  onOpenChange,
  deployUrl,
  sessionId,
  title,
}: {
  open: boolean;
  onOpenChange: (next: boolean) => void;
  /** 已发布的持久 URL; null = 尚未发布 (点击后由父组件驱动发布)。 */
  deployUrl: string | null;
  sessionId: string;
  title: string;
}) => {
  const [landingUrl, setLandingUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState(false);

  const activeRef = useRef(true);
  useEffect(() => {
    activeRef.current = true;
    return () => {
      activeRef.current = false;
    };
  }, []);

  // 建分享链。creatingRef 去重 (StrictMode 双调用 / effect 与重试重复触发只建一次);
  // setState 均在 async 微任务内, 不在 effect 同步体, 规避 react-hooks/set-state-in-effect。
  const creatingRef = useRef(false);
  const startShare = useCallback(() => {
    if (!deployUrl || creatingRef.current) return;
    creatingRef.current = true;
    void (async () => {
      setErr(false);
      setLoading(true);
      try {
        const r = await createShare({
          targetType: "session_artifact",
          sessionId,
          previewUrl: deployUrl,
          title,
        });
        if (activeRef.current) setLandingUrl(r.landingUrl);
      } catch {
        if (activeRef.current) setErr(true);
      } finally {
        creatingRef.current = false;
        if (activeRef.current) setLoading(false);
      }
    })();
  }, [deployUrl, sessionId, title]);

  // 面板打开且已有发布 URL、尚未建链 → 懒建 (含父组件发布成功后自动开面板的情形)。
  useEffect(() => {
    if (open && deployUrl && !landingUrl) startShare();
  }, [open, deployUrl, landingUrl, startShare]);

  return (
    <Popover open={open} onOpenChange={onOpenChange}>
      <PopoverTrigger
        aria-label="分享"
        title="分享"
        className={cn(
          buttonVariants({ variant: "ghost", size: "icon" }),
          "text-muted-foreground",
        )}
      >
        <Share2 size={16} strokeWidth={1.8} />
      </PopoverTrigger>
      <PopoverContent align="end" sideOffset={8} className="w-56 p-1.5">
        {loading && (
          <div className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground">
            <Loader2 className="size-4 animate-spin" /> 生成分享链接…
          </div>
        )}
        {err && (
          <button
            type="button"
            onClick={startShare}
            className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm text-red-600 hover:bg-surface-2"
          >
            <RefreshCw className="size-4" />
            生成失败，点击重试
          </button>
        )}
        {landingUrl && (
          <div className="flex flex-col">
            <WeChatShareItem url={landingUrl} />
            <CopyLinkItem url={landingUrl} />
          </div>
        )}
      </PopoverContent>
    </Popover>
  );
};
