import pytest
from django.urls import reverse

from apps.core.authentication.forms import ProfileForm
from apps.core.authentication.models import UserProfile


@pytest.mark.django_db
def test_profile_form_normalizes_lowercase_country(django_user_model):
    user = django_user_model.objects.create_user(email="profile@example.com", password="pw")
    profile = user.profile

    form = ProfileForm(
        data={
            "bio": "",
            "country": "ug",
            "degree_level": "",
            "timezone": "Africa/Kampala",
            "preferred_language": "en",
            "first_name": "Ada",
            "last_name": "Lovelace",
            "phone": "+256700000000",
        },
        instance=profile,
        user=user,
    )

    assert form.is_valid(), form.errors
    saved = form.save()
    assert saved.country == "Uganda"


@pytest.mark.django_db
def test_profile_form_rejects_invalid_country_code(django_user_model):
    user = django_user_model.objects.create_user(email="invalid@example.com", password="pw")
    profile = user.profile

    form = ProfileForm(
        data={
            "bio": "",
            "country": "QQ",
            "degree_level": "",
            "timezone": "UTC",
            "preferred_language": "en",
            "first_name": "",
            "last_name": "",
            "phone": "",
        },
        instance=profile,
        user=user,
    )

    assert not form.is_valid()
    assert "country" in form.errors


@pytest.mark.django_db
def test_profile_form_accepts_non_ruforum_iso_country(django_user_model):
    user = django_user_model.objects.create_user(email="us@example.com", password="pw")
    profile = user.profile

    form = ProfileForm(
        data={
            "bio": "",
            "country": "US",
            "degree_level": "",
            "timezone": "UTC",
            "preferred_language": "en",
            "first_name": "",
            "last_name": "",
            "phone": "",
        },
        instance=profile,
        user=user,
    )

    assert form.is_valid(), form.errors
    assert form.save().country == "United States"


@pytest.mark.django_db
def test_profile_view_updates_country_with_normalized_code(client, django_user_model):
    user = django_user_model.objects.create_user(email="viewer@example.com", password="pw")
    client.force_login(user)

    response = client.post(
        reverse("accounts:profile"),
        {
            "bio": "",
            "country": "rw",
            "degree_level": "",
            "timezone": "Africa/Kigali",
            "preferred_language": "en",
            "first_name": "Test",
            "last_name": "User",
            "phone": "",
        },
    )

    assert response.status_code == 302
    assert response.url == reverse("accounts:profile")
    user.refresh_from_db()
    assert user.profile.country == "Rwanda"


# WS1.5 UI follow-up — the profile form must round-trip the new
# demographic fields. If these regress, the AR010 women & youth participation
# indicator silently stops collecting data.


@pytest.mark.django_db
def test_profile_form_accepts_gender_and_date_of_birth(django_user_model):
    user = django_user_model.objects.create_user(email="demo@example.com", password="pw")

    form = ProfileForm(
        data={
            "bio": "",
            "country": "UG",
            "degree_level": "",
            "gender": UserProfile.Gender.FEMALE,
            "date_of_birth": "1995-04-12",
            "timezone": "Africa/Kampala",
            "preferred_language": "en",
            "first_name": "",
            "last_name": "",
            "phone": "",
        },
        instance=user.profile,
        user=user,
    )

    assert form.is_valid(), form.errors
    saved = form.save()
    assert saved.gender == UserProfile.Gender.FEMALE
    assert str(saved.date_of_birth) == "1995-04-12"


@pytest.mark.django_db
def test_profile_form_accepts_blank_demographic_fields(django_user_model):
    """Demographic fields are explicitly optional — submitting them blank must not error."""
    user = django_user_model.objects.create_user(email="demo-blank@example.com", password="pw")

    form = ProfileForm(
        data={
            "bio": "",
            "country": "",
            "degree_level": "",
            "gender": "",
            "date_of_birth": "",
            "timezone": "UTC",
            "preferred_language": "en",
            "first_name": "",
            "last_name": "",
            "phone": "",
        },
        instance=user.profile,
        user=user,
    )

    assert form.is_valid(), form.errors
    saved = form.save()
    assert saved.gender == ""
    assert saved.date_of_birth is None


@pytest.mark.django_db
def test_profile_view_persists_gender_and_dob(client, django_user_model):
    user = django_user_model.objects.create_user(email="demo-view@example.com", password="pw")
    client.force_login(user)

    response = client.post(
        reverse("accounts:profile"),
        {
            "bio": "",
            "country": "KE",
            "degree_level": "",
            "gender": UserProfile.Gender.MALE,
            "date_of_birth": "1988-08-08",
            "timezone": "Africa/Nairobi",
            "preferred_language": "en",
            "first_name": "",
            "last_name": "",
            "phone": "",
        },
    )
    assert response.status_code == 302
    user.refresh_from_db()
    assert user.profile.gender == UserProfile.Gender.MALE
    assert str(user.profile.date_of_birth) == "1988-08-08"
