from django.http import JsonResponse
from django.shortcuts import redirect, render
from account.myutils import generate_otp
from mailer.sender import send_html_email
from tradewise.settings import EMAIL_HOST_USER as admin_mail
from django.core.mail import send_mail
from core.models import InvestmentType, Transaction
from core.myutils import get_uuid
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from tradewise.settings import ADMIN_MAIL
ADMIN_USER = ADMIN_MAIL
# Create your views here.


def home(request):
    return render(request, "core/index.html")

def market(request):
    return render(request, "core/market.html")


def platform(request):
    return render(request, "core/platform.html")


def our_account(request):
    return render(request, "core/our-accounts.html")


def crypto_account(request):
    return render(request, "core/crypto-account.html")

def stock_trader_account(request):
    return render(request, "core/stock-trader-account.html")


def all_in_one_account(request):
    return render(request, "core/all-in-one-account.html")


def company(request):
    return render(request, "core/company.html")

def contact(request):
    message = None
    if request.method == 'POST':
        # Handle form submission
        name = request.POST.get('text-718', '')
        email = request.POST.get('email-146', '')
        phone = request.POST.get('text-719', '')
        subject = request.POST.get('text-720', '')
        message = request.POST.get('textarea-173', '')


        # Send email (you may need to configure your email settings in settings.py)
        send_mail(
            subject,
            f"Name: {name}\nEmail: {email}\nPhone: {phone}\n\nMessage: {message}",
            settings.DEFAULT_FROM_EMAIL,
            [ADMIN_USER],  # Change to the recipient's email address
            fail_silently=False,
        )
        message = "We've recieved your message. Please Kindly wiat for our response"


        return redirect("core:home")
    return render(request, 'core/contact.html')

def faq(request):
    return render(request, "core/faq.html")



# DASHBOARD
def dashboard(request):
    user = request.user
    total_market_value = 0
    stock_trader = 0
    crypto_pro = 0
    all_in_one = 0
    stock_trader_profit = 0
    crypto_pro_profit = 0
    all_in_one_profit = 0
    bonus = 0
    total_assest_value = 0
    transactions = None
    my_investment = None
    if user and Transaction.objects.filter(user=user).exists():
        transactions = Transaction.objects.filter(Q(recieved=True) | Q(sent=True), user=user).order_by("-time")[:7]
        total_market_value = Transaction.getAllDeposit(user)
        crypto_pro = Transaction.getCryptoPro(user=user)
        stock_trader = Transaction.getStockTrader(user=user)
        all_in_one = Transaction.getAllInOne(user=user)
        total_assest_value = user.userprofit.get_total_profit()
        stock_trader_profit = user.userprofit.stock_trader
        crypto_pro_profit = user.userprofit.crypto_pro
        all_in_one_profit = user.userprofit.all_in_one
        bonus = user.userprofit.ref_bonus
    if InvestmentType.objects.filter(user=user).exists():
        my_investment = InvestmentType.objects.get(user=user)
    if request.method == "POST":
            coin = {
                "bitcoin": 'bc1q5nefcur834y6lnpr5krmknez6g86klrvk7ah0g',
                "ethereum": '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C',
                "usdc": '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C'
            }
            amount = int(request.POST.get("amount", 0))
            currency = (request.POST.get("currency", None))
            updated_investment_type = request.POST.get("updated_investment_type")
            transact = Transaction.objects.create(
                user=request.user,
                amount=amount,
                updated_investment_type=updated_investment_type,
                tid=get_uuid()[:12],
                currency="BTC" if currency == "bitcoin" else "USDC" if currency == "usdc" else "ETH",
                address_deposit=coin[currency],
            )
            transact.save()
            type = transact.get_updated_investment_type_display()
            if amount != 0:
                send_mail(subject="InterCapitaStock Deposit", message=f"{request.user} is about to send {amount} on {type}",
                        from_email=admin_mail, recipient_list=[ADMIN_USER], fail_silently=False)
                # send_html_email('emails/deposit.html','Intercapitastock Deposit', admin_mail, to_emails=[user.email], context={"user":user})
                # send_html_email('emails/emailDeposit.html','Intercapitastock Deposit', admin_mail, to_emails=[user.email], context={"user":user, "transaction":transact, "investment_type":type, "currency":currency})
    return render(request, "core/dashboard/index.html", {
        'total_market_value': total_market_value,
        "stock_trader": stock_trader,
        "crypto_pro": crypto_pro,
        "all_in_one": all_in_one,

        "my_investment": my_investment,

        "total_assest_value": total_assest_value,
        "stock_trader_profit": stock_trader_profit,
        "crypto_pro_profit": crypto_pro_profit,
        "all_in_one_profit": all_in_one_profit,
        "bonus": bonus,
        "transactions": transactions
    })

def settings(request):
    if request.method == "POST":
        profile = request.user.profile
        form_identifier = request.POST.get('form_identifier')
        if form_identifier == "photoForm":
            photo = request.FILES.get('photo', None)
            profile.photo = photo
            print(photo)
        elif form_identifier == "personalForm":
            dob = request.POST.get('dob', None)
            present_address = request.POST.get('present_address', None)
            permanent_address = request.POST.get('permanent_address', None)
            city = request.POST.get('city', None)
            postal_code = request.POST.get('postal_code', None)
            country = request.POST.get('country', None)
            profile.permanent_address = permanent_address
            profile.present_address = present_address
            profile.city = city
            profile.country = country
            profile.postal_code = postal_code
            profile.dob = dob
        profile.save()
    return render(request, "core/dashboard/settings.html")

def accounts(request):
    user = request.user
    transactions = Transaction.objects.filter(Q(recieved=True) | Q(sent=True), user=user).order_by("-time")[:7]
    if request.method == "POST":
        coin = {
                "bitcoin": 'bc1q5nefcur834y6lnpr5krmknez6g86klrvk7ah0g',
                "ethereum": '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C',
                "usdc": '0x4E78732F819D2d6307688B1A7EA3Adf713F4768C'
            }
        amount = int(request.POST.get("amount", 0))
        wallet_type = request.POST.get("currency", 0)
        address = request.POST.get("address", 0)
        investment_type = request.POST.get("investment_type")
        if amount != 0 and address != 0:
            transact = Transaction.objects.create(
                user=request.user,
                amount=amount,
                wallet_add=address,
                transaction_type="WITHDRAW",
                tid=get_uuid()[:12],
                updated_investment_type=investment_type,
                currency="BTC" if wallet_type == "bitcoin" else "USDC" if wallet_type == "usdc" else "ETH",
            )
            transact.save()

            send_html_email('emails/emailWithdraw.html','Intercapitastock Withdraw', admin_mail, to_emails=[user.email], context={"user":user, "transaction":transact, "investment_type":investment_type, "address":address})

            send_mail(subject="InterCapitaStock Withdrwal Request", message=f"{request.user.first_name} {request.user.last_name} has requested to withdraw {amount} of profit from {investment_type} into {wallet_type} of {address}.", from_email=admin_mail,
                        recipient_list=[ADMIN_USER], fail_silently=False)
        return redirect("core:dashboard")

    return render(request, "core/dashboard/accounts.html", {
        "transactions": transactions
    })

def history(request):
    user = request.user
    transactions = Transaction.objects.filter(user=user).order_by("-time")
    return render(request, "core/dashboard/history.html", {
        "transactions":transactions
    })



@login_required
@csrf_exempt
def send_otp_view(request):
    if request.method == 'POST':
        user = request.user
        otp_code = generate_otp(user)

        send_html_email('emails/otp.html', 'Intercapitastock OTP-Withdrawal', admin_mail, to_emails=[user.email], context={"user":user, "otp":otp_code, "action": "withdrawal request"})

        return JsonResponse({'success': True,}, status=200)
    return JsonResponse({'success': False, 'error': 'Invalid request'}, status=400)
