import { FormEvent, useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { fetchAccounts, updateAccount, type AccountDto } from '../api/client';

export function EditAccountPage() {
  const { id } = useParams<{ id: string }>();
  const nav = useNavigate();
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [loading, setLoading] = useState(true);

  const [label, setLabel] = useState('');
  const [issuer, setIssuer] = useState('');
  const [secret, setSecret] = useState('');
  const [algorithm, setAlgorithm] = useState('SHA1');
  const [digits, setDigits] = useState(6);
  const [period, setPeriod] = useState(30);

  useEffect(() => {
    if (!id) {
      nav('/', { replace: true });
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const list = await fetchAccounts();
        const account = list.find((a) => a.id === id);
        if (cancelled) return;
        if (!account) {
          nav('/', { replace: true });
          return;
        }
        applyAccount(account);
        setLoading(false);
      } catch {
        if (!cancelled) nav('/login', { replace: true });
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [id, nav]);

  function applyAccount(a: AccountDto) {
    setLabel(a.label);
    setIssuer(a.issuer ?? '');
    setAlgorithm(a.algorithm);
    setDigits(a.digits);
    setPeriod(a.period);
    setSecret('');
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (!id) return;
    const trimmedLabel = label.trim();
    if (!trimmedLabel) {
      setError('请填写显示名称');
      return;
    }
    setBusy(true);
    setError(null);
    try {
      await updateAccount(id, {
        label: trimmedLabel,
        issuer: issuer.trim() || null,
        secret: secret.trim() || undefined,
        algorithm,
        digits,
        period,
      });
      nav('/', { replace: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败');
    } finally {
      setBusy(false);
    }
  }

  if (loading) {
    return (
      <main>
        <p className="sub">加载中…</p>
      </main>
    );
  }

  return (
    <main>
      <div className="top-nav">
        <Link className="btn secondary" to="/">
          返回
        </Link>
        <span style={{ fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <img className="top-nav-logo" src="/logo.png" alt="" width={28} height={28} />
          编辑账户
        </span>
        <span style={{ width: 72 }} />
      </div>

      <form className="card" onSubmit={onSubmit}>
        <div className="field">
          <label>显示名称</label>
          <input value={label} onChange={(e) => setLabel(e.target.value)} required />
        </div>
        <div className="field">
          <label>发行方（可选）</label>
          <input value={issuer} onChange={(e) => setIssuer(e.target.value)} />
        </div>
        <div className="field">
          <label>Secret（Base32）</label>
          <input
            value={secret}
            onChange={(e) => setSecret(e.target.value)}
            placeholder="留空表示不修改密钥"
            autoComplete="off"
          />
        </div>
        <div className="field">
          <label>算法</label>
          <select value={algorithm} onChange={(e) => setAlgorithm(e.target.value)}>
            <option value="SHA1">SHA1</option>
            <option value="SHA256">SHA256</option>
            <option value="SHA512">SHA512</option>
          </select>
        </div>
        <div className="field">
          <label>位数</label>
          <input
            type="number"
            min={6}
            max={10}
            value={digits}
            onChange={(e) => setDigits(Number(e.target.value))}
          />
        </div>
        <div className="field">
          <label>周期（秒）</label>
          <input
            type="number"
            min={10}
            max={120}
            value={period}
            onChange={(e) => setPeriod(Number(e.target.value))}
          />
        </div>
        {error ? <p className="error">{error}</p> : null}
        <button className="btn" type="submit" disabled={busy} style={{ width: '100%', marginTop: 8 }}>
          {busy ? '保存中…' : '保存修改'}
        </button>
      </form>
    </main>
  );
}
