import os
from nicegui import ui, app
from supabase import create_client
from rt_commission_dashboard.ui.theme import Theme
from rt_commission_dashboard.core.config import config


def signup_page():
    Theme.apply_global_styles()

    with ui.column().classes('absolute-center w-full max-w-sm'):
        ui.label('RT Commission Dashboard').classes('text-3xl font-bold text-center w-full mb-8')

        with Theme.card():
            ui.label('Create Account').classes('text-xl font-bold mb-6 text-center w-full')

            email = ui.input('Email').props('outlined dense type=email').classes('w-full mb-4 rt-input')
            password = ui.input('Password').props('outlined dense type=password').classes('w-full mb-4 rt-input')
            confirm = ui.input('Confirm Password').props('outlined dense type=password').classes('w-full mb-6 rt-input')

            def handle_signup():
                if password.value != confirm.value:
                    ui.notify('Passwords do not match', type='negative')
                    return

                supabase_url = config.get_supabase_url()
                supabase_anon = config.get_supabase_anon_key()
                if not supabase_url or not supabase_anon:
                    ui.notify('Supabase not configured.', type='negative')
                    return

                client = create_client(supabase_url, supabase_anon)
                try:
                    resp = client.auth.sign_up({'email': email.value, 'password': password.value})
                    if resp.user:
                        ui.notify('Account created. Check your email to confirm.', type='positive')
                        ui.navigate.to('/login')
                    else:
                        ui.notify('Signup initiated. Check your email to confirm.', type='positive')
                        ui.navigate.to('/login')
                except Exception as exc:  # noqa: BLE001
                    ui.notify(f'Signup failed: {exc}', type='negative')

            ui.button('Sign Up', on_click=handle_signup).props('unelevated color=indigo-600').classes('w-full h-10')
            ui.link('Back to Login', '/login').classes('block text-center mt-3 text-sm text-indigo-500')

