from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from datetime import datetime
import requests
import os
import sys
sys.path.append('..')
from app import db, Wallet, Transaction, Contribution

wallet_bp = Blueprint('wallet', __name__)

@wallet_bp.route('/wallet')
@login_required
def wallet_dashboard():
    wallet = Wallet.query.filter_by(user_id=current_user.id).first()
    transactions = Transaction.query.filter_by(user_id=current_user.id).order_by(Transaction.created_at.desc()).all()
    
    return render_template('wallet/dashboard.html', wallet=wallet, transactions=transactions)

@wallet_bp.route('/wallet/contribute', methods=['GET', 'POST'])
@login_required
def contribute():
    if request.method == 'POST':
        amount = float(request.form.get('amount'))
        payment_method = request.form.get('payment_method')
        
        if payment_method == 'paystack':
            # Initialize Paystack transaction
            return initialize_paystack_payment(amount, 'contribution')
        else:
            # Manual payment
            contribution = Contribution(
                user_id=current_user.id,
                amount=amount,
                payment_method='manual',
                status='pending'
            )
            
            db.session.add(contribution)
            db.session.commit()
            
            flash('Contribution submitted for approval. Please wait for admin confirmation.', 'info')
            return redirect(url_for('wallet.wallet_dashboard'))
    
    return render_template('wallet/contribute.html')

def initialize_paystack_payment(amount, purpose):
    url = 'https://api.paystack.co/transaction/initialize'
    headers = {
        'Authorization': f'Bearer {os.environ.get("PAYSTACK_SECRET_KEY")}',
        'Content-Type': 'application/json'
    }
    
    callback_url = url_for('wallet.paystack_callback', _external=True)
    
    data = {
        'email': current_user.email,
        'amount': int(amount * 100),  # Convert to kobo
        'callback_url': callback_url,
        'metadata': {
            'user_id': current_user.id,
            'purpose': purpose,
            'amount': amount
        }
    }
    
    try:
        response = requests.post(url, json=data, headers=headers)
        response_data = response.json()
        
        if response_data['status']:
            return jsonify({
                'status': 'success',
                'authorization_url': response_data['data']['authorization_url'],
                'reference': response_data['data']['reference']
            })
        else:
            return jsonify({'status': 'error', 'message': 'Payment initialization failed'})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

@wallet_bp.route('/wallet/paystack/callback')
@login_required
def paystack_callback():
    reference = request.args.get('reference')
    
    # Verify payment
    url = f'https://api.paystack.co/transaction/verify/{reference}'
    headers = {
        'Authorization': f'Bearer {os.environ.get("PAYSTACK_SECRET_KEY")}'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response_data = response.json()
        
        if response_data['status'] and response_data['data']['status'] == 'success':
            # Payment successful
            amount = response_data['data']['amount'] / 100  # Convert back to Naira
            metadata = response_data['data']['metadata']
            
            # Update wallet
            wallet = Wallet.query.filter_by(user_id=current_user.id).first()
            wallet.balance += amount
            
            # Create transaction record
            transaction = Transaction(
                user_id=current_user.id,
                type='deposit',
                amount=amount,
                status='completed',
                reference=reference,
                description='Paystack contribution'
            )
            
            # Create contribution record
            contribution = Contribution(
                user_id=current_user.id,
                amount=amount,
                payment_method='paystack',
                transaction_reference=reference,
                status='approved'
            )
            
            db.session.add(transaction)
            db.session.add(contribution)
            db.session.commit()
            
            flash('Payment successful! Your contribution has been added to your wallet.', 'success')
        else:
            flash('Payment verification failed. Please contact support.', 'danger')
    except Exception as e:
        flash('An error occurred during payment verification.', 'danger')
    
    return redirect(url_for('wallet.wallet_dashboard'))

@wallet_bp.route('/wallet/withdraw', methods=['GET', 'POST'])
@login_required
def withdraw():
    if request.method == 'POST':
        amount = float(request.form.get('amount'))
        wallet = Wallet.query.filter_by(user_id=current_user.id).first()
        
        if wallet.balance < amount:
            flash('Insufficient balance.', 'danger')
            return redirect(url_for('wallet.withdraw'))
        
        # Create withdrawal transaction
        transaction = Transaction(
            user_id=current_user.id,
            type='withdrawal',
            amount=amount,
            status='pending',
            description='Withdrawal request'
        )
        
        db.session.add(transaction)
        db.session.commit()
        
        flash('Withdrawal request submitted. Please wait for admin approval.', 'info')
        return redirect(url_for('wallet.wallet_dashboard'))
    
    return render_template('wallet/withdraw.html')
