import { useEffect, useState } from 'react';
import { getWechatBindingStatus } from '../api/client';
import { buildWechatAuthorizeUrl } from '../utils/wechat';

export function WechatBindPrompt({
  returnTo,
  onDismiss,
}: {
  returnTo?: string;
  onDismiss?: () => void;
}) {
  const [visible, setVisible] = useState(false);
  const [bound, setBound] = useState(false);

  useEffect(() => {
    void getWechatBindingStatus().then((status) => {
      const suggested = sessionStorage.getItem('tkmind_suggest_wechat_bind') === '1';
      if (suggested) sessionStorage.removeItem('tkmind_suggest_wechat_bind');
      if (status.enabled && !status.bound && suggested) {
        setVisible(true);
      }
      setBound(status.bound);
    });
  }, []);

  if (!visible || bound) return null;

  const handleBind = () => {
    window.location.href = buildWechatAuthorizeUrl({
      intent: 'bind',
      returnTo: returnTo ?? window.location.pathname,
    });
  };

  const handleDismiss = () => {
    setVisible(false);
    onDismiss?.();
  };

  return (
    <div className="banner banner-info wechat-bind-banner">
      <span>绑定微信，下次在微信里可一键登录</span>
      <button type="button" className="banner-action" onClick={handleBind}>
        立即绑定
      </button>
      <button type="button" className="banner-dismiss" onClick={handleDismiss}>
        稍后再说
      </button>
    </div>
  );
}
