import re
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, FloatField, IntegerField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Email, Length, Optional, ValidationError


def validate_abn(form, field):
    if not field.data:
        return  # skip validation if empty

    abn = re.sub(r'\s', '', field.data)
    if not re.fullmatch(r'\d{11}', abn):
        raise ValidationError('ABN must be 11 digits.')

    weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
    digits = [int(d) for d in abn]
    digits[0] -= 1
    total = sum(w * d for w, d in zip(weights, digits))

    if total % 89 != 0:
        raise ValidationError('Invalid ABN — please check and re-enter.')


def validate_mobile(form, field):
    mobile = re.sub(r'[\s\-()]', '', field.data or '')
    if not re.fullmatch(r'(04\d{8}|\+614\d{8})', mobile):
        raise ValidationError('Enter a valid Australian mobile (e.g. 0412 345 678).')


class ApplicationForm(FlaskForm):
    # Optional — Business (hidden in UI)
    business_name = StringField('Business / Trading Name', validators=[Optional(), Length(max=120)])
    abn = StringField('ABN (Australian Business Number)', validators=[Optional(), validate_abn])
    business_structure = SelectField('Business Structure', choices=[
        ('', '— Select —'),
        ('sole_trader', 'Sole Trader'),
        ('partnership', 'Partnership'),
        ('company', 'Company (Pty Ltd)'),
        ('trust', 'Trust'),
        ('other', 'Other'),
    ], validators=[Optional()])
    industry = SelectField('Industry', choices=[
        ('', '— Select Industry —'),
        ('agriculture', 'Agriculture, Forestry & Fishing'),
        ('mining', 'Mining'),
        ('manufacturing', 'Manufacturing'),
        ('construction', 'Construction'),
        ('retail', 'Retail Trade'),
        ('hospitality', 'Accommodation & Food Services'),
        ('transport', 'Transport, Postal & Warehousing'),
        ('ict', 'Information & Communication Technology'),
        ('finance', 'Financial & Insurance Services'),
        ('real_estate', 'Rental, Hiring & Real Estate'),
        ('professional', 'Professional, Scientific & Technical'),
        ('admin', 'Administrative & Support Services'),
        ('health', 'Health Care & Social Assistance'),
        ('education', 'Education & Training'),
        ('arts', 'Arts & Recreation'),
        ('other', 'Other'),
    ], validators=[Optional()])
    years_trading = SelectField('Years in Business', choices=[
        ('', '— Select —'),
        ('0-1', 'Less than 1 year'),
        ('1-2', '1–2 years'),
        ('2-5', '2–5 years'),
        ('5-10', '5–10 years'),
        ('10+', '10+ years'),
    ], validators=[Optional()])
    annual_revenue = SelectField('Annual Turnover (AUD)', choices=[
        ('', '— Select —'),
        ('<100k', 'Under $100,000'),
        ('100-250k', '$100,000 – $250,000'),
        ('250-500k', '$250,000 – $500,000'),
        ('500k-1m', '$500,000 – $1,000,000'),
        ('1-5m', '$1M – $5M'),
        ('5m+', 'Over $5M'),
    ], validators=[Optional()])

    # Step 1 — Loan
    loan_amount = FloatField('Loan Amount (AUD)', validators=[DataRequired()])
    loan_purpose = SelectField('Loan Purpose', choices=[
        ('', '— Select —'),
        ('working_capital', 'Working Capital'),
        ('equipment', 'Equipment / Machinery'),
        ('property', 'Commercial Property'),
        ('refinance', 'Debt Refinancing'),
        ('expansion', 'Business Expansion'),
        ('inventory', 'Stock / Inventory'),
        ('fitout', 'Fit-Out / Renovation'),
        ('other', 'Other'),
    ], validators=[DataRequired()])
    loan_term = SelectField('Preferred Loan Term', choices=[
        ('', '— Select —'),
        ('6', '6 months'),
        ('12', '12 months'),
        ('24', '24 months'),
        ('36', '36 months'),
        ('48', '48 months'),
        ('60', '60 months'),
        ('84', '84 months'),
    ], validators=[DataRequired()])
    has_security = SelectField('Do you have security / collateral?', choices=[
        ('', '— Select —'),
        ('yes', 'Yes'),
        ('no', 'No — unsecured is fine'),
    ], validators=[DataRequired()])

    # Step 2 — Personal
    first_name = StringField('First Name', validators=[DataRequired(), Length(max=60)])
    last_name = StringField('Last Name', validators=[DataRequired(), Length(max=60)])
    email = StringField('Email Address', validators=[DataRequired(), Email()])
    mobile = StringField('Mobile Number', validators=[DataRequired(), validate_mobile])
    state = SelectField('State / Territory', choices=[
        ('', '— Select —'),
        ('NSW', 'New South Wales'),
        ('VIC', 'Victoria'),
        ('QLD', 'Queensland'),
        ('SA', 'South Australia'),
        ('WA', 'Western Australia'),
        ('TAS', 'Tasmania'),
        ('ACT', 'Australian Capital Territory'),
        ('NT', 'Northern Territory'),
    ], validators=[DataRequired()])
    referral = SelectField('How did you hear about us?', choices=[
        ('', '— Select —'),
        ('google', 'Google Search'),
        ('social', 'Social Media'),
        ('referral', 'Referral / Word of Mouth'),
        ('broker', 'Finance Broker'),
        ('other', 'Other'),
    ], validators=[Optional()])
    notes = TextAreaField('Additional Notes (optional)', validators=[Optional(), Length(max=500)])

    # Step 3 — Consent
    privacy_consent = BooleanField(
        'I have read and agree to the Privacy Policy and consent to my personal information being used to assess this application.',
        validators=[DataRequired(message='You must agree to the Privacy Policy.')]
    )
    credit_consent = BooleanField(
        'I consent to Capital Bridge Finance performing a credit enquiry on my behalf as required under the National Consumer Credit Protection Act 2009.',
        validators=[DataRequired(message='Credit check consent is required.')]
    )
