import { useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.jsx';
import { useJoinHousehold } from '../api/queries.js';
import { useHouseholdContext } from '../household/HouseholdContext.jsx';
import { useTranslation } from '../i18n/I18nContext.jsx';
import PasswordField from '../components/PasswordField.jsx';

export default function Register() {
  const { register } = useAuth();
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const inviteCode = params.get('code') || '';
  const joinHousehold = useJoinHousehold();
  const { switchHousehold } = useHouseholdContext();
  const { t, tError } = useTranslation();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await register(email, password, name);
      if (inviteCode) {
        const result = await joinHousehold.mutateAsync(inviteCode);
        switchHousehold(result.household.id);
        navigate('/', { replace: true });
      } else {
        navigate('/onboarding', { replace: true });
      }
    } catch (err) {
      setError(tError(err));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="auth-page">
      <h1>{t('common.appName')}</h1>
      <p className="auth-subtitle">{inviteCode ? t('register.subtitleInvite') : t('register.subtitle')}</p>
      <form onSubmit={handleSubmit} className="auth-form">
        <input type="text" placeholder={t('register.namePlaceholder')} value={name} onChange={(e) => setName(e.target.value)} required />
        <input
          type="email"
          placeholder={t('register.emailPlaceholder')}
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <PasswordField
          placeholder={t('register.passwordPlaceholder')}
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        {error && <p className="form-error">{error}</p>}
        <button type="submit" className="btn-primary" disabled={loading}>
          {loading ? t('register.creating') : t('register.submit')}
        </button>
      </form>
      <p>
        {t('register.haveAccount')}{' '}
        <Link to={inviteCode ? `/login?code=${encodeURIComponent(inviteCode)}` : '/login'}>{t('register.login')}</Link>
      </p>
    </div>
  );
}
