import React, { useEffect, useState, FormEvent } from 'react';
import { api, Volunteer } from '../api';
import { useAuth } from '../auth';

export default function Profile() {
  const { volunteerID } = useAuth();
  const [volunteer, setVolunteer] = useState<Volunteer | null>(null);
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!volunteerID) return;
    api.getVolunteer(volunteerID).then(v => {
      const vol = v as Volunteer;
      setVolunteer(vol);
      setName(vol.name);
      setPhone(vol.phone ?? '');
    }).catch(() => setError('Could not load profile.'));
  }, [volunteerID]);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError('');
    setSuccess('');
    if (!volunteerID) return;
    setSaving(true);
    try {
      const updated = await api.updateVolunteer(volunteerID, { name, phone: phone || undefined });
      setVolunteer(updated);
      setSuccess('Profile updated.');
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  }

  if (!volunteer) return <div className="page"><p>Loading…</p></div>;

  return (
    <div className="page">
      <h2>My Profile</h2>
      {error && <p className="error">{error}</p>}
      {success && <p className="success">{success}</p>}
      <form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
        <label>
          Full name
          <input value={name} onChange={e => setName(e.target.value)} required />
        </label>
        <label>
          Email
          <input value={volunteer.email} disabled />
        </label>
        <label>
          Phone
          <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="Optional" />
        </label>
        <label>
          Operational roles
          <input value={volunteer.operational_roles || '—'} disabled />
        </label>
        <label>
          Notification preference
          <input value={volunteer.notification_preference} disabled />
        </label>
        <p style={{ color: '#666', fontSize: '0.85em' }}>
          Completed shifts: {volunteer.completed_shifts}
          {volunteer.is_trainee && ' · Trainee'}
        </p>
        <button type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save Changes'}</button>
      </form>
    </div>
  );
}
