from decimal import Decimal
from django import forms
from django.contrib.auth.models import User
from .models import Wallet, Withdrawal
from .services import minor_units

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=150)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput, min_length=8)
    def clean_username(self):
        username = self.cleaned_data["username"]
        if User.objects.filter(username__iexact=username).exists():
            raise forms.ValidationError("That username is already taken.")
        return username

class AmountForm(forms.Form):
    asset = forms.ChoiceField(choices=Wallet.ASSETS)
    amount = forms.CharField(max_length=30)
    def amount_minor(self):
        return minor_units(self.cleaned_data["asset"], self.cleaned_data["amount"])

class SendForm(AmountForm):
    recipient_username = forms.CharField(max_length=150)

class WithdrawalForm(AmountForm):
    channel = forms.ChoiceField(choices=Withdrawal.CHANNELS)
    destination = forms.CharField(
        max_length=180,
        help_text="For TRON USDT testnet, enter the recipient TRON Base58Check address (starts with T).",
    )
    network = forms.ChoiceField(
        choices=[("", "Not applicable"), ("Tron-Shasta", "TRON Shasta testnet (TRC-20 USDT)")],
        required=False,
        help_text="USDT blockchain withdrawals currently use TRON Shasta testnet.",
    )


from django.core.exceptions import ValidationError
from .models import Terminal

class TerminalForm(forms.ModelForm):
    class Meta:
        model = Terminal
        fields = [
            "terminal_id", "protocol", "ip_address", "dns_name",
            "machine_os", "port", "min_receiving_usd", "max_receiving_usd",
        ]
        widgets = {
            "terminal_id": forms.TextInput(attrs={"placeholder": "TERM-000001"}),
            "ip_address": forms.TextInput(),
            "port": forms.NumberInput(attrs={"min": 1, "max": 65535}),
            "min_receiving_usd": forms.NumberInput(attrs={"min": "0", "step": "0.01"}),
            "max_receiving_usd": forms.NumberInput(attrs={"min": "0", "step": "0.01"}),
        }

    def clean_terminal_id(self):
        value = self.cleaned_data["terminal_id"].strip()
        if not value:
            raise forms.ValidationError("Terminal ID is required.")
        qs = Terminal.objects.filter(terminal_id=value)
        if self.instance.pk:
            qs = qs.exclude(pk=self.instance.pk)
        if qs.exists():
            raise forms.ValidationError("This terminal ID is already registered.")
        return value

    def clean(self):
        cleaned = super().clean()
        minimum = cleaned.get("min_receiving_usd")
        maximum = cleaned.get("max_receiving_usd")
        port = cleaned.get("port")
        if minimum is not None and minimum < 0:
            self.add_error("min_receiving_usd", "Minimum cannot be negative.")
        if maximum is not None and maximum < 0:
            self.add_error("max_receiving_usd", "Maximum cannot be negative.")
        if minimum is not None and maximum is not None and maximum < minimum:
            self.add_error("max_receiving_usd", "Maximum must be greater than or equal to minimum.")
        if port is not None and not 1 <= port <= 65535:
            self.add_error("port", "Port must be between 1 and 65535.")
        return cleaned



class PayloadTransferForm(forms.Form):
    recipient_username = forms.CharField(max_length=150, label="Receiver username")
    asset = forms.ChoiceField(choices=Wallet.ASSETS)
    amount = forms.CharField(max_length=30)
    memo = forms.CharField(max_length=200, required=False)

    def amount_minor(self):
        return minor_units(self.cleaned_data["asset"], self.cleaned_data["amount"])
