import { useEffect, useState, type FormEvent } from 'react';
import * as memberApi from '../../api/member';
import { ApiError } from '../../api/http';

export function ProfilePage() {
  const [displayName, setDisplayName] = useState('');
  const [language, setLanguage] = useState('zh-TW');
  const [currency, setCurrency] = useState('TWD');
  const [phone, setPhone] = useState('');
  const [msg, setMsg] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    memberApi.getMe().then((m) => {
      setDisplayName(m.display_name ?? '');
      setLanguage(m.language ?? 'zh-TW');
      setCurrency(m.currency ?? 'TWD');
      setPhone(m.phone ?? '');
    });
  }, []);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setMsg('');
    setLoading(true);
    try {
      await memberApi.updateMe({
        display_name: displayName,
        language,
        currency,
        phone: phone || undefined,
      });
      setMsg('已儲存');
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '儲存失敗');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>個人資料</h1>
      <form onSubmit={submit} className="form form-narrow">
        <label>
          顯示名稱
          <input
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
          />
        </label>
        <label>
          語系
          <input value={language} onChange={(e) => setLanguage(e.target.value)} />
        </label>
        <label>
          幣別
          <input value={currency} onChange={(e) => setCurrency(e.target.value)} />
        </label>
        <label>
          聯絡電話
          <input value={phone} onChange={(e) => setPhone(e.target.value)} />
        </label>
        {error && <p className="form-error">{error}</p>}
        {msg && <p className="form-ok">{msg}</p>}
        <button type="submit" className="btn-primary" disabled={loading}>
          儲存
        </button>
      </form>
    </div>
  );
}
