"""Admin-managed mobile money payment numbers (Lipa Namba) shown to
customers at the payment step. Payment itself happens outside the app
(customer sends money via M-Pesa/Tigo Pesa/etc. directly) — admin then
manually confirms the order once payment is received. No payment gateway
is integrated; this is a display + manual-confirmation workflow only."""

import urllib.parse

from accounts.supabase_client import get_client
from .site_settings import get_whatsapp_number

# Real brand logo images aren't used here (trademarked assets) — each
# provider instead gets a distinct colour badge so customers can still tell
# networks apart at a glance.
PROVIDER_INFO = {
    'mpesa': {'label': 'M-Pesa', 'color': '#3CB043'},
    'tigopesa': {'label': 'Tigo Pesa', 'color': '#0077C8'},
    'airtelmoney': {'label': 'Airtel Money', 'color': '#ED1C24'},
    'halopesa': {'label': 'HaloPesa', 'color': '#F7941D'},
    'other': {'label': 'Other', 'color': '#6b7280'},
}

PROVIDER_CHOICES = [(key, info['label']) for key, info in PROVIDER_INFO.items()]


def _attach_provider_info(method):
    method['provider_label'] = PROVIDER_INFO.get(method['provider'], PROVIDER_INFO['other'])['label']
    method['provider_color'] = PROVIDER_INFO.get(method['provider'], PROVIDER_INFO['other'])['color']
    return method


def get_active_payment_methods():
    resp = get_client().table('pickker_payment_methods').select('*').eq('is_active', True).order('created_at').execute()
    return [_attach_provider_info(m) for m in resp.data]


def get_all_payment_methods():
    resp = get_client().table('pickker_payment_methods').select('*').order('created_at').execute()
    return [_attach_provider_info(m) for m in resp.data]


def create_payment_method(provider, lipa_number, account_name='', instructions=''):
    get_client().table('pickker_payment_methods').insert({
        'provider': provider,
        'lipa_number': lipa_number.strip(),
        'account_name': account_name.strip(),
        'instructions': instructions.strip(),
    }).execute()


def update_payment_method(method_id, provider, lipa_number, account_name='', instructions=''):
    get_client().table('pickker_payment_methods').update({
        'provider': provider,
        'lipa_number': lipa_number.strip(),
        'account_name': account_name.strip(),
        'instructions': instructions.strip(),
    }).eq('id', method_id).execute()


def toggle_payment_method_active(method_id):
    client = get_client()
    resp = client.table('pickker_payment_methods').select('is_active').eq('id', method_id).execute()
    if resp.data:
        current = resp.data[0]['is_active']
        client.table('pickker_payment_methods').update({'is_active': not current}).eq('id', method_id).execute()
        return not current
    return None


def build_whatsapp_proof_link(order_id, total_amount, customer_name, phone, email):
    """The pre-filled WhatsApp message a customer sends after paying — same
    wording used everywhere an order's "how to pay" step is shown (the real
    order-detail page and the chat assistant's inline order-scheduled card),
    so it never drifts between the two."""
    message = (
        f"Payment proof for Order #{order_id}\n"
        f"Amount paid: TSh {total_amount}\n"
        f"Name: {customer_name}\n"
        f"Phone: {phone}\n"
        f"Email: {email}\n"
        f"(Screenshot attached)"
    )
    return f"https://wa.me/{get_whatsapp_number()}?text={urllib.parse.quote(message)}"
