"""
Forms for dashboard / site settings.
"""
import re
from django import forms
from apps.dashboard.models import SiteSettings, EmailTemplate, EMAIL_TRIGGER_CHOICES
from utils.choices import THEME_PRESET_CHOICES, THEME_PRESETS, ROLE_CHOICES


CURRENCY_CHOICES = [
    ('PKR', 'PKR — Pakistani Rupee'),
    ('USD', 'USD — US Dollar'),
    ('EUR', 'EUR — Euro'),
    ('GBP', 'GBP — British Pound'),
    ('AED', 'AED — UAE Dirham'),
    ('SAR', 'SAR — Saudi Riyal'),
    ('INR', 'INR — Indian Rupee'),
]

CURRENCY_SYMBOLS = {
    'PKR': 'PKR',
    'USD': '$',
    'EUR': '€',
    'GBP': '£',
    'AED': 'AED',
    'SAR': 'SAR',
    'INR': '₹',
}

HEX_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')


class SiteSettingsForm(forms.ModelForm):
    class Meta:
        model = SiteSettings
        fields = [
            'institute_name',
            'tagline',
            'logo',
            'logo_dark',
            'favicon',
            'certificate_verify_url',
            'certificate_signer_name',
            'certificate_signer_title',
            'certificate_signature',
            'certificate_seal',
            'theme_preset',
            'theme_primary',
            'theme_secondary',
            'theme_accent',
            'theme_success',
            'currency_code',
            'currency_symbol',
            'enable_manual_payment',
            'enable_stripe_payment',
            'manual_payment_instructions',
            'stripe_publishable_key',
            'stripe_secret_key',
            'stripe_webhook_secret',
            'smtp_enabled',
            'smtp_host',
            'smtp_port',
            'smtp_use_tls',
            'smtp_use_ssl',
            'smtp_username',
            'smtp_password',
            'smtp_from_email',
        ]
        widgets = {
            'institute_name': forms.TextInput(attrs={
                'class': 'form-control form-control-lg',
                'placeholder': 'e.g. TSN Digital Academy',
            }),
            'tagline': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Short tagline shown on the home page',
            }),
            'logo': forms.ClearableFileInput(attrs={'class': 'form-control'}),
            'logo_dark': forms.ClearableFileInput(attrs={'class': 'form-control'}),
            'favicon': forms.ClearableFileInput(attrs={'class': 'form-control'}),
            'certificate_verify_url': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'https://yoursite.com/certifications/verify/',
            }),
            'certificate_signer_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Director full name (optional)',
            }),
            'certificate_signer_title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Director',
            }),
            'certificate_signature': forms.ClearableFileInput(attrs={'class': 'form-control'}),
            'certificate_seal': forms.ClearableFileInput(attrs={'class': 'form-control'}),
            'theme_preset': forms.Select(
                choices=THEME_PRESET_CHOICES,
                attrs={'class': 'form-select', 'id': 'id_theme_preset'},
            ),
            'theme_primary': forms.TextInput(attrs={
                'class': 'form-control form-control-color w-100',
                'type': 'color',
                'id': 'id_theme_primary',
            }),
            'theme_secondary': forms.TextInput(attrs={
                'class': 'form-control form-control-color w-100',
                'type': 'color',
                'id': 'id_theme_secondary',
            }),
            'theme_accent': forms.TextInput(attrs={
                'class': 'form-control form-control-color w-100',
                'type': 'color',
                'id': 'id_theme_accent',
            }),
            'theme_success': forms.TextInput(attrs={
                'class': 'form-control form-control-color w-100',
                'type': 'color',
                'id': 'id_theme_success',
            }),
            'currency_code': forms.Select(
                choices=CURRENCY_CHOICES,
                attrs={'class': 'form-select', 'id': 'id_currency_code'},
            ),
            'currency_symbol': forms.TextInput(attrs={
                'class': 'form-control',
                'id': 'id_currency_symbol',
                'placeholder': 'PKR',
            }),
            'enable_manual_payment': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
            }),
            'enable_stripe_payment': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
            }),
            'manual_payment_instructions': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 5,
                'placeholder': 'Bank / Easypaisa / JazzCash instructions for students…',
            }),
            'stripe_publishable_key': forms.TextInput(attrs={
                'class': 'form-control font-monospace',
                'placeholder': 'pk_test_…',
                'autocomplete': 'off',
            }),
            'stripe_secret_key': forms.PasswordInput(
                render_value=True,
                attrs={
                    'class': 'form-control font-monospace',
                    'placeholder': 'sk_test_…',
                    'autocomplete': 'new-password',
                },
            ),
            'stripe_webhook_secret': forms.PasswordInput(
                render_value=True,
                attrs={
                    'class': 'form-control font-monospace',
                    'placeholder': 'whsec_…',
                    'autocomplete': 'new-password',
                },
            ),
            'smtp_enabled': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
                'id': 'id_smtp_enabled',
            }),
            'smtp_host': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'mail.yourdomain.com',
            }),
            'smtp_port': forms.NumberInput(attrs={
                'class': 'form-control',
                'min': 1,
                'max': 65535,
            }),
            'smtp_use_tls': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
            }),
            'smtp_use_ssl': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
            }),
            'smtp_username': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'noreply@yourdomain.com',
                'autocomplete': 'off',
            }),
            'smtp_password': forms.PasswordInput(
                render_value=True,
                attrs={
                    'class': 'form-control',
                    'placeholder': 'SMTP / mailbox password',
                    'autocomplete': 'new-password',
                },
            ),
            'smtp_from_email': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'TSN Digital Academy <noreply@yourdomain.com>',
            }),
        }

    def clean_theme_primary(self):
        return self._clean_hex('theme_primary')

    def clean_theme_secondary(self):
        return self._clean_hex('theme_secondary')

    def clean_theme_accent(self):
        return self._clean_hex('theme_accent')

    def clean_theme_success(self):
        return self._clean_hex('theme_success')

    def _clean_hex(self, field):
        value = (self.cleaned_data.get(field) or '').strip()
        if not HEX_RE.match(value):
            raise forms.ValidationError('Use a valid hex color like #1e40af.')
        return value.lower()

    def clean(self):
        cleaned = super().clean()
        code = cleaned.get('currency_code') or 'PKR'
        if not cleaned.get('currency_symbol'):
            cleaned['currency_symbol'] = CURRENCY_SYMBOLS.get(code, code)

        manual = cleaned.get('enable_manual_payment')
        stripe = cleaned.get('enable_stripe_payment')
        if not manual and not stripe:
            raise forms.ValidationError(
                'Enable at least one payment method (Manual or Stripe) so students can pay for courses.'
            )

        if stripe:
            if not cleaned.get('stripe_publishable_key') or not cleaned.get('stripe_secret_key'):
                self.add_error(
                    'stripe_secret_key',
                    'Publishable and Secret keys are required when Stripe is enabled.',
                )

        if cleaned.get('smtp_enabled'):
            if not (cleaned.get('smtp_host') or '').strip():
                self.add_error('smtp_host', 'SMTP host is required when SMTP is enabled.')
            if cleaned.get('smtp_use_tls') and cleaned.get('smtp_use_ssl'):
                self.add_error('smtp_use_ssl', 'Use either TLS or SSL, not both.')
            from_addr = (cleaned.get('smtp_from_email') or '').strip()
            user = (cleaned.get('smtp_username') or '').strip()
            if not from_addr and not user:
                self.add_error(
                    'smtp_from_email',
                    'Set a From address (or SMTP username) when SMTP is enabled.',
                )

        preset = cleaned.get('theme_preset')
        if preset and preset != 'custom' and preset in THEME_PRESETS:
            colors = THEME_PRESETS[preset]
            cleaned['theme_primary'] = colors['primary']
            cleaned['theme_secondary'] = colors['secondary']
            cleaned['theme_accent'] = colors['accent']
            cleaned['theme_success'] = colors['success']
        return cleaned


class EmailTemplateForm(forms.ModelForm):
    class Meta:
        model = EmailTemplate
        fields = [
            'name', 'slug', 'trigger', 'subject',
            'body_html', 'body_text', 'is_active',
        ]
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'e.g. Welcome email',
            }),
            'slug': forms.TextInput(attrs={
                'class': 'form-control font-monospace',
                'placeholder': 'signup_welcome',
            }),
            'trigger': forms.Select(
                choices=EMAIL_TRIGGER_CHOICES,
                attrs={'class': 'form-select'},
            ),
            'subject': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Welcome to {{ institute_name }}!',
            }),
            'body_html': forms.Textarea(attrs={
                'class': 'form-control font-monospace',
                'rows': 14,
                'placeholder': '<p>Hi {{ user_name }},</p>…',
            }),
            'body_text': forms.Textarea(attrs={
                'class': 'form-control font-monospace',
                'rows': 6,
                'placeholder': 'Plain-text version (optional)',
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
                'role': 'switch',
            }),
        }


class ComposeEmailForm(forms.Form):
    """Admin compose / bulk email form."""
    RECIPIENT_MODE_CHOICES = [
        ('role', 'All users with a role'),
        ('users', 'Selected users'),
        ('emails', 'Custom email addresses'),
    ]

    recipient_mode = forms.ChoiceField(
        choices=RECIPIENT_MODE_CHOICES,
        widget=forms.RadioSelect(attrs={'class': 'form-check-input'}),
        initial='role',
    )
    role = forms.ChoiceField(
        choices=[('', '— Select role —')] + list(ROLE_CHOICES),
        required=False,
        widget=forms.Select(attrs={'class': 'form-select'}),
    )
    user_ids = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        widget=forms.SelectMultiple(attrs={
            'class': 'form-select',
            'size': 10,
        }),
        help_text='Hold Ctrl/Cmd to select multiple users.',
    )
    emails = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={
            'class': 'form-control font-monospace',
            'rows': 4,
            'placeholder': 'one@example.com\ntwo@example.com',
        }),
        help_text='One email per line (or comma-separated).',
    )
    template = forms.ModelChoiceField(
        queryset=EmailTemplate.objects.none(),
        required=False,
        empty_label='— Compose manually —',
        widget=forms.Select(attrs={'class': 'form-select', 'id': 'id_compose_template'}),
    )
    subject = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Subject (supports {{ user_name }}, {{ institute_name }}, …)',
        }),
    )
    body_html = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control font-monospace',
            'rows': 12,
            'placeholder': '<p>Hi {{ user_name }},</p>\n<p>Your message…</p>',
        }),
    )
    body_text = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={
            'class': 'form-control font-monospace',
            'rows': 4,
            'placeholder': 'Plain-text fallback (optional)',
        }),
    )

    def __init__(self, *args, **kwargs):
        from apps.accounts.models import CustomUser
        super().__init__(*args, **kwargs)
        self.fields['user_ids'].queryset = CustomUser.objects.exclude(
            email='',
        ).order_by('role', 'username')
        self.fields['template'].queryset = EmailTemplate.objects.filter(
            is_active=True,
        ).order_by('name')

    def clean(self):
        cleaned = super().clean()
        mode = cleaned.get('recipient_mode')
        if mode == 'role' and not cleaned.get('role'):
            self.add_error('role', 'Select a role to email.')
        elif mode == 'users' and not cleaned.get('user_ids'):
            self.add_error('user_ids', 'Select at least one user.')
        elif mode == 'emails':
            raw = cleaned.get('emails') or ''
            parsed = []
            for part in re.split(r'[\s,;]+', raw):
                part = part.strip()
                if part:
                    parsed.append(part)
            if not parsed:
                self.add_error('emails', 'Enter at least one email address.')
            else:
                cleaned['parsed_emails'] = parsed
        if not (cleaned.get('subject') or '').strip():
            self.add_error('subject', 'Subject is required.')
        if not (cleaned.get('body_html') or '').strip():
            self.add_error('body_html', 'Email body is required.')
        return cleaned


class SmtpTestForm(forms.Form):
    test_email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'you@example.com',
        }),
    )
