from django import forms
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import timedelta
from .models import Customer, Service, CustomerTag, MarketingWeeklyReport, MarketingLeadInteraction
from decimal import Decimal
from django.core.exceptions import ValidationError

User = get_user_model()

class CustomerForm(forms.ModelForm):
    parent_customer_id = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter parent customer ID (for sub-accounts)'}),
        help_text="Leave empty for main accounts. Enter parent customer ID for sub-accounts."
    )

    class Meta:
        model = Customer
        fields = [
            'customer_type', 'full_name', 'id_passport', 'company_name',
            'contact_person_first_name', 'contact_person_last_name',
            'business_registration_number', 'vat_number', 'company_address',
            'billing_contact_name', 'billing_contact_email', 'billing_contact_phone',
            'kra_pin', 'phone', 'email', 'gps_latitude', 'gps_longitude',
            'physical_address', 'service', 'notes', 'tags'
        ]
        widgets = {
            'customer_type': forms.Select(attrs={'class': 'form-control'}),
            'full_name': forms.TextInput(attrs={'class': 'form-control'}),
            'id_passport': forms.TextInput(attrs={'class': 'form-control'}),
            'company_name': forms.TextInput(attrs={'class': 'form-control'}),
            'contact_person_first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'contact_person_last_name': forms.TextInput(attrs={'class': 'form-control'}),
            'business_registration_number': forms.TextInput(attrs={'class': 'form-control'}),
            'vat_number': forms.TextInput(attrs={'class': 'form-control'}),
            'company_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'billing_contact_name': forms.TextInput(attrs={'class': 'form-control'}),
            'billing_contact_email': forms.EmailInput(attrs={'class': 'form-control'}),
            'billing_contact_phone': forms.TextInput(attrs={'class': 'form-control'}),
            'kra_pin': forms.TextInput(attrs={'class': 'form-control'}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'gps_latitude': forms.NumberInput(attrs={'class': 'form-control', 'step': 'any'}),
            'gps_longitude': forms.NumberInput(attrs={'class': 'form-control', 'step': 'any'}),
            'physical_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'service': forms.Select(attrs={'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'tags': forms.SelectMultiple(attrs={'class': 'form-control'})
        }

    def clean_parent_customer_id(self):
        parent_id = self.cleaned_data.get('parent_customer_id')
        if parent_id:
            try:
                parent = Customer.objects.get(customer_id=parent_id, is_sub_account=False)
                return parent
            except Customer.DoesNotExist:
                raise ValidationError("Parent customer not found or is a sub-account itself")
        return None

    def save(self, commit=True):
        customer = super().save(commit=False)
        parent_customer = self.cleaned_data.get('parent_customer_id')

        if parent_customer:
            customer.parent_customer = parent_customer
            customer.is_sub_account = True

        if commit:
            customer.save()
            self.save_m2m()

        return customer

    def clean(self):
        cleaned_data = super().clean()
        customer_type = cleaned_data.get('customer_type')

        if customer_type == 'individual':
            if not cleaned_data.get('full_name'):
                self.add_error('full_name', 'Full name is required for individual customers.')
        elif customer_type == 'institution':
            if not cleaned_data.get('company_name'):
                self.add_error('company_name', 'Company name is required for institutional customers.')
            if not cleaned_data.get('contact_person_first_name'):
                self.add_error('contact_person_first_name', 'Contact person first name is required for institutional customers.')
            if not cleaned_data.get('contact_person_last_name'):
                self.add_error('contact_person_last_name', 'Contact person last name is required for institutional customers.')
        
        # Phone number cleaning
        phone = cleaned_data.get('phone')
        if phone:
            import re
            phone = re.sub(r'[^\d+]', '', phone)

            if phone.startswith('+254'):
                cleaned_data['phone'] = phone[1:]  # Remove + to store as 254...
            elif phone.startswith('254'):
                cleaned_data['phone'] = phone
            elif phone.startswith('0'):
                cleaned_data['phone'] = '254' + phone[1:]
            elif len(phone) == 9:
                cleaned_data['phone'] = '254' + phone
            else:
                if len(phone) >= 9:
                    cleaned_data['phone'] = phone
                else:
                    cleaned_data['phone'] = '254' + phone

        return cleaned_data


class ServiceForm(forms.ModelForm):
    class Meta:
        model = Service
        fields = ['name', 'speed_mbps', 'fup_gb', 'price', 'billing_cycle', 'installation_fee', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'speed_mbps': forms.NumberInput(attrs={'class': 'form-control'}),
            'fup_gb': forms.NumberInput(attrs={'class': 'form-control'}),
            'price': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
            'billing_cycle': forms.Select(attrs={'class': 'form-select'}),
            'installation_fee': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

# Keep PackageForm as an alias for backward compatibility
PackageForm = ServiceForm

class CustomerTagForm(forms.ModelForm):
    class Meta:
        model = CustomerTag
        fields = ['name', 'description', 'color']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'color': forms.TextInput(attrs={'class': 'form-control', 'type': 'color'}),
        }

class CustomerBalanceForm(forms.Form):
    TRANSACTION_TYPE_CHOICES = [
        ('credit', 'Credit (Payment/Top-up)'),
        ('debit', 'Debit (Bill Payment)'),
        ('refund', 'Refund'),
        ('adjustment', 'Manual Adjustment'),
    ]

    transaction_type = forms.ChoiceField(
        choices=TRANSACTION_TYPE_CHOICES,
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )
    amount = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=0.01,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'step': '0.01',
            'placeholder': 'Enter amount'
        })
    )
    description = forms.CharField(
        max_length=200,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Description for this transaction'
        })
    )
    reference_id = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Reference ID (optional)'
        })
    )

class CustomerAccountSetupForm(forms.Form):
    password = forms.CharField(
        min_length=8,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Create a password (minimum 8 characters)'
        }),
        help_text="Password must be at least 8 characters long."
    )
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Confirm your password'
        })
    )

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password and confirm_password:
            if password != confirm_password:
                raise forms.ValidationError("Passwords don't match.")

        return cleaned_data


class MarketingWeeklyReportForm(forms.ModelForm):
    class Meta:
        model = MarketingWeeklyReport
        exclude = ['marketing_staff', 'reviewed_by', 'reviewed_at', 'review_comments', 'status']
        widgets = {
            'week_starting': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'week_ending': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'customer_feedback_summary': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'competitor_activities': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'market_trends_observed': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'service_improvement_recommendations': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'pricing_recommendations': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'marketing_strategy_recommendations': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'challenges_faced': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}),
            'solutions_implemented': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}),
            'next_week_targets': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}),
            'support_needed': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Auto-set current week dates if creating new report
        if not self.instance.pk:
            today = timezone.now().date()
            # Find Monday of current week
            monday = today - timedelta(days=today.weekday())
            sunday = monday + timedelta(days=6)

            self.fields['week_starting'].initial = monday
            self.fields['week_ending'].initial = sunday

    def clean(self):
        cleaned_data = super().clean()
        week_starting = cleaned_data.get('week_starting')
        week_ending = cleaned_data.get('week_ending')

        if week_starting and week_ending:
            if week_ending <= week_starting:
                raise forms.ValidationError("Week ending date must be after week starting date")

            if (week_ending - week_starting).days != 6:
                raise forms.ValidationError("Report period must be exactly 7 days (Monday to Sunday)")

        return cleaned_data


class MarketingLeadInteractionForm(forms.ModelForm):
    class Meta:
        model = MarketingLeadInteraction
        exclude = ['weekly_report']
        widgets = {
            'interaction_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'follow_up_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'rows': 3, 'class': 'form-control'}),
            'follow_up_notes': forms.Textarea(attrs={'rows': 2, 'class': 'form-control'}),
            'estimated_value': forms.NumberInput(attrs={'step': '0.01', 'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.instance.pk:
            self.fields['interaction_date'].initial = timezone.now().date()


class MarketingReportReviewForm(forms.ModelForm):
    class Meta:
        model = MarketingWeeklyReport
        fields = ['review_comments', 'status']
        widgets = {
            'review_comments': forms.Textarea(attrs={'rows': 4, 'class': 'form-control'}),
            'status': forms.Select(attrs={'class': 'form-control'}),
        }


# Form for filtering marketing reports
class MarketingReportFilterForm(forms.Form):
    staff_member = forms.ModelChoiceField(
        queryset=User.objects.filter(role='marketing').order_by('first_name'),
        required=False,
        empty_label="All Staff",
        widget=forms.Select(attrs={'class': 'form-control'})
    )

    date_from = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})
    )

    date_to = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})
    )

    status = forms.ChoiceField(
        choices=[('', 'All Statuses')] + MarketingWeeklyReport.REPORT_STATUS_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'})
    )

class CustomerServiceManagementForm(forms.Form):
    ACTION_CHOICES = [
        ('suspend', 'Suspend Service'),
        ('reconnect', 'Reconnect Service'),
        ('disconnect', 'Permanently Disconnect'),
        ('start_trial', 'Start Trial Period'),
        ('activate_service', 'Activate Paid Service'),
    ]

    action = forms.ChoiceField(
        choices=ACTION_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    reason = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Reason for action'})
    )
    override_date = forms.DateTimeField(
        required=False,
        widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
        help_text="Optional: Override suspension/disconnection date"
    )
    send_notification = forms.BooleanField(
        initial=True,
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )


class SubAccountForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = [
            'full_name', 'company_name', 'phone', 'email', 
            'physical_address', 'service', 'notes'
        ]
        widgets = {
            'full_name': forms.TextInput(attrs={'class': 'form-control'}),
            'company_name': forms.TextInput(attrs={'class': 'form-control'}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'physical_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'service': forms.Select(attrs={'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3})
        }

    def __init__(self, *args, parent_customer=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent_customer = parent_customer
        if parent_customer:
            # Pre-fill some fields from parent
            self.fields['physical_address'].initial = parent_customer.physical_address

    def save(self, commit=True):
        sub_account = super().save(commit=False)
        if self.parent_customer:
            sub_account.parent_customer = self.parent_customer
            sub_account.is_sub_account = True
            sub_account.customer_type = self.parent_customer.customer_type

        if commit:
            sub_account.save()
            self.save_m2m()

        return sub_account