from django import forms
from .models import Ticket, TicketComment, TicketAttachment
from customers.models import Customer
from django.contrib.auth import get_user_model

User = get_user_model()

class TicketForm(forms.ModelForm):
    scheduled_date = forms.DateTimeField(
        required=False,
        widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
        help_text="Optional: Schedule this task for a specific date and time"
    )
    estimated_duration_hours = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=23,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Hours"
    )
    estimated_duration_minutes = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=59,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Minutes"
    )
    reminder_before_hours = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=23,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Reminder before - Hours"
    )
    reminder_before_minutes = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=59,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Reminder before - Minutes"
    )

    class Meta:
        model = Ticket
        fields = ['customer', 'assigned_to', 'assigned_employee', 'category', 'title', 'description', 'priority', 'scheduled_date', 'is_scheduled']
        widgets = {
            'customer': forms.Select(attrs={'class': 'form-select'}),
            'assigned_to': forms.Select(attrs={'class': 'form-select'}),
            'assigned_employee': forms.Select(attrs={'class': 'form-select'}),
            'category': forms.Select(attrs={'class': 'form-select'}),
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'priority': forms.Select(attrs={'class': 'form-select'}),
            'is_scheduled': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Filter to show only employees for assignment
        from hr.models import Employee
        employee_user_ids = Employee.objects.filter(
            user__isnull=False,
            employment_status='active'
        ).values_list('user_id', flat=True)
        self.fields['assigned_to'].queryset = User.objects.filter(id__in=employee_user_ids)
        self.fields['assigned_to'].empty_label = "Unassigned"

        # Set up employee assignment field
        self.fields['assigned_employee'].queryset = Employee.objects.filter(employment_status='active')
        self.fields['assigned_employee'].empty_label = "Unassigned"

        # Make customer optional
        self.fields['customer'].empty_label = "Company/Infrastructure Ticket"
        self.fields['customer'].required = False

        # If editing existing ticket, populate duration fields
        if self.instance and self.instance.pk:
            if self.instance.estimated_duration:
                total_seconds = int(self.instance.estimated_duration.total_seconds())
                hours = total_seconds // 3600
                minutes = (total_seconds % 3600) // 60
                self.fields['estimated_duration_hours'].initial = hours
                self.fields['estimated_duration_minutes'].initial = minutes

            if self.instance.reminder_before:
                total_seconds = int(self.instance.reminder_before.total_seconds())
                hours = total_seconds // 3600
                minutes = (total_seconds % 3600) // 60
                self.fields['reminder_before_hours'].initial = hours
                self.fields['reminder_before_minutes'].initial = minutes

    def clean_scheduled_date(self):
        scheduled_date = self.cleaned_data.get('scheduled_date')
        if scheduled_date:
            # Check if the time is within working hours (8 AM to 5 PM)
            hour = scheduled_date.hour
            if hour < 8 or hour >= 17:
                raise forms.ValidationError('Please schedule within working hours (8:00 AM - 5:00 PM)')
        return scheduled_date

    def save(self, commit=True):
        instance = super().save(commit=False)

        # Handle estimated duration
        hours = self.cleaned_data.get('estimated_duration_hours', 0) or 0
        minutes = self.cleaned_data.get('estimated_duration_minutes', 0) or 0

        if hours > 0 or minutes > 0:
            from datetime import timedelta
            instance.estimated_duration = timedelta(hours=hours, minutes=minutes)
        else:
            instance.estimated_duration = None

        # Handle reminder before duration
        rem_hours = self.cleaned_data.get('reminder_before_hours', 0) or 0
        rem_minutes = self.cleaned_data.get('reminder_before_minutes', 0) or 0

        if rem_hours > 0 or rem_minutes > 0:
            from datetime import timedelta
            instance.reminder_before = timedelta(hours=rem_hours, minutes=rem_minutes)
        else:
            instance.reminder_before = None

        if commit:
            instance.save()
        return instance

class TicketUpdateForm(forms.ModelForm):
    scheduled_date = forms.DateTimeField(
        required=False,
        widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
        help_text="Optional: Schedule this task for a specific date and time"
    )
    estimated_duration_hours = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=23,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Hours"
    )
    estimated_duration_minutes = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=59,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Minutes"
    )
    reminder_before_hours = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=23,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Reminder before - Hours"
    )
    reminder_before_minutes = forms.IntegerField(
        required=False,
        min_value=0,
        max_value=59,
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0'}),
        help_text="Reminder before - Minutes"
    )

    class Meta:
        model = Ticket
        fields = ['assigned_to', 'assigned_employee', 'title', 'description', 'priority', 'status', 'category', 'scheduled_date', 'is_scheduled']
        widgets = {
            'category': forms.Select(attrs={'class': 'form-select'}),
            'assigned_to': forms.Select(attrs={'class': 'form-select'}),
            'assigned_employee': forms.Select(attrs={'class': 'form-select'}),
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'priority': forms.Select(attrs={'class': 'form-select'}),
            'status': forms.Select(attrs={'class': 'form-select'}),
            'is_scheduled': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Filter to show only employees for assignment
        from hr.models import Employee
        employee_user_ids = Employee.objects.filter(
            user__isnull=False,
            employment_status='active'
        ).values_list('user_id', flat=True)
        self.fields['assigned_to'].queryset = User.objects.filter(id__in=employee_user_ids)

        # Set up employee assignment field
        self.fields['assigned_employee'].queryset = Employee.objects.filter(employment_status='active')
        self.fields['assigned_employee'].empty_label = "Unassigned"

        # If editing existing ticket, populate duration fields
        if self.instance and self.instance.pk:
            if self.instance.estimated_duration:
                total_seconds = int(self.instance.estimated_duration.total_seconds())
                hours = total_seconds // 3600
                minutes = (total_seconds % 3600) // 60
                self.fields['estimated_duration_hours'].initial = hours
                self.fields['estimated_duration_minutes'].initial = minutes

            if self.instance.reminder_before:
                total_seconds = int(self.instance.reminder_before.total_seconds())
                hours = total_seconds // 3600
                minutes = (total_seconds % 3600) // 60
                self.fields['reminder_before_hours'].initial = hours
                self.fields['reminder_before_minutes'].initial = minutes

    def clean_scheduled_date(self):
        scheduled_date = self.cleaned_data.get('scheduled_date')
        if scheduled_date:
            # Check if the time is within working hours (8 AM to 5 PM)
            hour = scheduled_date.hour
            if hour < 8 or hour >= 17:
                raise forms.ValidationError('Please schedule within working hours (8:00 AM - 5:00 PM)')
        return scheduled_date

    def save(self, commit=True):
        instance = super().save(commit=False)

        # Handle estimated duration
        hours = self.cleaned_data.get('estimated_duration_hours', 0) or 0
        minutes = self.cleaned_data.get('estimated_duration_minutes', 0) or 0

        if hours > 0 or minutes > 0:
            from datetime import timedelta
            instance.estimated_duration = timedelta(hours=hours, minutes=minutes)
        else:
            instance.estimated_duration = None

        # Handle reminder before duration
        rem_hours = self.cleaned_data.get('reminder_before_hours', 0) or 0
        rem_minutes = self.cleaned_data.get('reminder_before_minutes', 0) or 0

        if rem_hours > 0 or rem_minutes > 0:
            from datetime import timedelta
            instance.reminder_before = timedelta(hours=rem_hours, minutes=rem_minutes)
        else:
            instance.reminder_before = None

        if commit:
            instance.save()
        return instance

class TicketCommentForm(forms.ModelForm):
    class Meta:
        model = TicketComment
        fields = ['comment', 'is_internal']
        widgets = {
            'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Add your comment...'}),
            'is_internal': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

class TicketAttachmentForm(forms.ModelForm):
    class Meta:
        model = TicketAttachment
        fields = ['file', 'description']
        widgets = {
            'file': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*,application/pdf,.doc,.docx,.txt'}),
            'description': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Optional description...'}),
        }

    def clean_file(self):
        file = self.cleaned_data.get('file')
        if file:
            # Check file size (limit to 10MB)
            if file.size > 10 * 1024 * 1024:
                raise forms.ValidationError('File size cannot exceed 10MB.')

            # Check file type
            allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'pdf', 'doc', 'docx', 'txt']
            file_ext = file.name.lower().split('.')[-1] if '.' in file.name else ''
            if file_ext not in allowed_extensions:
                raise forms.ValidationError('File type not allowed. Please upload images or documents only.')

        return file