import { useCallback, useEffect, useState } from 'react';
import { fetchSharedAccount, type SharedAccountDto } from '../api/client';
import { TotpCard } from '../components/TotpCard';

export function SharePage({ token }: { token: string }) {
  const [account, setAccount] = useState<SharedAccountDto | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const a = await fetchSharedAccount(token);
      setAccount(a);
      setError(null);
    } catch (e) {
      setAccount(null);
      setError(e instanceof Error ? e.message : '无法加载');
    }
  }, [token]);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    const t = setInterval(() => void load(), 1000);
    return () => clearInterval(t);
  }, [load]);

  if (error && !account) {
    return (
      <main className="share-page">
        <div className="card">
          <p className="error">{error}</p>
          <p className="sub" style={{ marginBottom: 0 }}>
            分享链接无效或已被撤销，请联系分享者获取新链接。
          </p>
        </div>
      </main>
    );
  }

  if (!account) {
    return (
      <main className="share-page">
        <p className="sub">加载中…</p>
      </main>
    );
  }

  return (
    <main className="share-page">
      <div className="top-nav">
        <div className="top-nav-title">
          <img className="top-nav-logo" src="/logo.png" alt="" width={36} height={36} />
          <h1 style={{ margin: 0, fontSize: '1.25rem' }}>验证码</h1>
        </div>
      </div>

      <TotpCard
        label={account.label}
        issuer={account.issuer}
        code={account.code}
        expiresInSeconds={account.expiresInSeconds}
        period={account.period}
      />
    </main>
  );
}
