from django import forms

from market.translations import LANGUAGES

from .models import AccountType, Role, SourceType
from .phone_utils import canonical_phone
from .supabase_client import get_client


class SignupForm(forms.Form):
    role = forms.ChoiceField(choices=Role.SIGNUP_CHOICES, widget=forms.RadioSelect, initial=Role.CUSTOMER)
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100, required=False)
    last_name = forms.CharField(max_length=100, required=False)
    phone_number = forms.CharField(max_length=20, required=False)
    # Web-app site language defaults to English — separate from SMS, which
    # always defaults to Swahili regardless of this (see sms_language below).
    preferred_language = forms.ChoiceField(choices=LANGUAGES, required=False, initial='en')
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
    agree_to_policies = forms.BooleanField(
        required=True,
        error_messages={'required': 'You must read and agree to the Terms & Conditions, Privacy Policy, and Cookie Policy to continue.'},
    )

    # Customer-only fields
    account_type = forms.ChoiceField(choices=AccountType.CHOICES, required=False)
    business_name = forms.CharField(max_length=255, required=False)
    tin_number = forms.CharField(max_length=50, required=False)
    business_license_number = forms.CharField(max_length=50, required=False)
    wants_fleet_registration = forms.BooleanField(required=False)
    address = forms.CharField(
        max_length=255, required=False,
        widget=forms.TextInput(attrs={'placeholder': 'House number, building, street'}),
    )
    city = forms.CharField(max_length=100, required=False)
    area = forms.CharField(max_length=100, required=False)

    # Picker-only fields
    truck_type_id = forms.IntegerField(required=False)
    license_plate = forms.CharField(max_length=20, required=False)
    source_type = forms.ChoiceField(
        choices=SourceType.CHOICES, required=False, initial=SourceType.MARKET,
        help_text='Where do you actually pick produce from?',
    )
    market_location = forms.CharField(max_length=255, required=False)
    market_id = forms.IntegerField(required=False)
    location_lat = forms.FloatField(required=False, widget=forms.HiddenInput)
    location_lng = forms.FloatField(required=False, widget=forms.HiddenInput)
    license_number = forms.CharField(max_length=50, required=False)

    def clean_email(self):
        email = self.cleaned_data['email'].strip().lower()
        existing = get_client().table('pickker_users').select('id').eq('email', email).execute()
        if existing.data:
            raise forms.ValidationError('An account with this email already exists.')
        return email

    def clean_phone_number(self):
        # Normalized to one consistent stored form so phone-based login can
        # reliably match it later, regardless of how it was typed here.
        return canonical_phone(self.cleaned_data.get('phone_number', ''))

    def clean(self):
        cleaned = super().clean()
        if cleaned.get('password1') != cleaned.get('password2'):
            self.add_error('password2', "Passwords don't match")

        if cleaned.get('role') == Role.PICKER:
            if not cleaned.get('truck_type_id'):
                self.add_error(
                    'truck_type_id',
                    'Pickers must select a vehicle to deliver orders.',
                )
            if cleaned.get('location_lat') is None or cleaned.get('location_lng') is None:
                self.add_error(
                    'market_location',
                    'Please set your market location on the map.',
                )
        elif cleaned.get('role') == Role.CUSTOMER:
            if cleaned.get('account_type') == AccountType.B2B and not cleaned.get('business_name', '').strip():
                self.add_error('business_name', 'Business accounts must provide a business name.')
            # A plain B2B account (buying, not operating trucks) stays at
            # today's normal level — TIN/license optional. Only checking
            # "register a fleet" raises the bar, since a fleet company is
            # the one case that actually needs verifiable business identity.
            if cleaned.get('wants_fleet_registration'):
                if not cleaned.get('tin_number', '').strip():
                    self.add_error('tin_number', 'TIN number is required to register a delivery fleet.')
                if not cleaned.get('business_license_number', '').strip():
                    self.add_error('business_license_number', 'Business license number is required to register a delivery fleet.')
        return cleaned


class ProductForm(forms.Form):
    name = forms.CharField(max_length=150, label='Name (English)')
    name_sw = forms.CharField(
        max_length=150, required=False, label='Name (Kiswahili)',
        help_text='Leave blank to fall back to the English name for customers browsing in Kiswahili.',
    )
    category = forms.ChoiceField(choices=[], required=False)
    market_id = forms.ChoiceField(
        choices=[], required=False, label='Sourced from (market)',
        help_text="Leave as \"Any market\" for a generic product available everywhere (the normal case). "
                   "Pick a specific market only if this item is genuinely unique to it (e.g. a rice type only "
                   "sold there) — the site will then only assign pickers registered at that market to fulfill it, "
                   "and won't let it be ordered alongside another item unique to a different market. Leave this "
                   "as \"Any market\" if instead using Warehouse/Industry below.",
    )
    warehouse_id = forms.ChoiceField(
        choices=[], required=False, label='OR sourced from (warehouse)',
        help_text="Pick a warehouse instead of a market for stock this platform sources from its own/partner "
                   "storage. Delivered by truck/fleet, same as B2B — can't be ordered alongside market or "
                   "generic items in one cart. Leave blank unless this item is genuinely warehouse-only.",
    )
    industry_id = forms.ChoiceField(
        choices=[], required=False, label='OR sourced from (industry)',
        help_text="Pick an industry/manufacturer instead, for bulk/wholesale-sourced items. Same truck/fleet "
                   "delivery and no-mixing rule as warehouse above. Leave blank unless genuinely industry-only.",
    )
    quality_grade = forms.CharField(
        max_length=60, required=False, label='Grade / variant label',
        help_text='Optional free text shown to customers next to the market badge (e.g. "Grade A", "Organic", '
                   '"Premium") — use this when the same product name exists at different markets with different '
                   'quality/price, so customers can tell the variants apart.',
    )
    unit = forms.ChoiceField(choices=[])
    farm_price = forms.DecimalField(max_digits=8, decimal_places=2)
    market_price = forms.DecimalField(max_digits=8, decimal_places=2)
    b2b_price = forms.DecimalField(
        max_digits=8, decimal_places=2, required=False,
        help_text='Wholesale price for B2B buyers (leave blank to use the market price)',
    )
    min_purchase_qty = forms.IntegerField(
        min_value=1, initial=1,
        help_text='Minimum quantity any buyer must order of this item (1 = no restriction)',
    )
    b2b_min_qty = forms.IntegerField(
        min_value=1, initial=10,
        help_text='Minimum quantity a B2B buyer must order of this item (on top of the general minimum above)',
    )
    image = forms.ImageField(required=False)
    stock_qty = forms.IntegerField(min_value=0, initial=0)
    is_trending = forms.BooleanField(
        required=False,
        help_text='Featured on the homepage ticker. The up/down % shown there is always computed automatically '
                   'from recorded regional prices (Admin Portal → Regional Price Trends) — it is never hand-typed.',
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        from market.categories import get_all_categories
        from market.markets import get_active_markets
        from market.measure_units import get_active_measure_units
        categories = get_all_categories()
        self.fields['category'].choices = [('', '—')] + [(c['name'], c['name']) for c in categories]
        markets = get_active_markets()
        self.fields['market_id'].choices = [('', 'Any market (available everywhere)')] + [(m['id'], m['name']) for m in markets]
        from market.vendors import get_active_vendors
        self.fields['warehouse_id'].choices = [('', '—')] + [(w['id'], w['name']) for w in get_active_vendors('warehouse')]
        self.fields['industry_id'].choices = [('', '—')] + [(i['id'], i['name']) for i in get_active_vendors('industry')]
        units = get_active_measure_units()
        self.fields['unit'].choices = [
            (u['key'], u['label_en'] + (f" ({u['label_sw']})" if u.get('label_sw') else ''))
            for u in units
        ]


class LoginForm(forms.Form):
    identifier = forms.CharField(label='Email or phone number')
    password = forms.CharField(widget=forms.PasswordInput)


class RegionalPriceForm(forms.Form):
    """Admin records a new farm/market price point for a product in a region.
    The % change and up/down/tied direction are always computed automatically
    from the previous entry — never entered here."""
    product_id = forms.ChoiceField(choices=[])
    region = forms.ChoiceField(choices=[])
    farm_price = forms.DecimalField(max_digits=8, decimal_places=2)
    market_price = forms.DecimalField(max_digits=8, decimal_places=2)

    def __init__(self, *args, products=None, **kwargs):
        super().__init__(*args, **kwargs)
        from market.price_trends import TANZANIA_REGIONS
        self.fields['product_id'].choices = [(p['id'], p['name']) for p in (products or [])]
        self.fields['region'].choices = [(r, r) for r in TANZANIA_REGIONS]
