from django import forms

from .models import Branch, Company, CompanyPolicy, Department, Designation, Holiday, Shift


class CompanyPolicyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if getattr(self.instance, "pk", None):
            self.fields["company"].disabled = True
            self.fields["company"].help_text = "Policy company cannot be changed after creation."

    class Meta:
        model = CompanyPolicy
        fields = [
            "company", "effective_from", "effective_to", "salary_day_divisor",
            "monthly_working_hours", "salary_proration_method", "missing_workday_is_absent",
            "missing_punch_action", "half_day_deduction_fraction", "ot_minimum_minutes", "ot_rounding_minutes",
            "ot_default_rate_multiplier", "ot_weekly_off_multiplier", "ot_holiday_multiplier",
            "leave_manager_approval_required", "payroll_segregation_required", "loan_recovery_start_rule",
            "request_reference_prefix", "payroll_reference_prefix", "loan_reference_prefix",
            "notes", "is_active",
        ]
        widgets = {
            "effective_from": forms.DateInput(attrs={"type": "date"}),
            "effective_to": forms.DateInput(attrs={"type": "date"}),
            "notes": forms.Textarea(attrs={"rows": 3}),
        }


class CompanyForm(forms.ModelForm):
    class Meta:
        model = Company
        fields = ["code", "name", "legal_name", "address", "currency_code", "timezone", "is_active"]
        widgets = {"address": forms.Textarea(attrs={"rows": 3})}


class _CompanyChildForm(forms.ModelForm):
    def __init__(self, *args, company_queryset=None, **kwargs):
        super().__init__(*args, **kwargs)
        if company_queryset is not None and "company" in self.fields:
            self.fields["company"].queryset = company_queryset
        if getattr(self.instance, "pk", None) and "company" in self.fields:
            self.fields["company"].disabled = True
            self.fields["company"].help_text = "Company ownership cannot be changed after creation."


class BranchForm(_CompanyChildForm):
    class Meta:
        model = Branch
        fields = ["company", "code", "name", "address", "is_active"]
        widgets = {"address": forms.Textarea(attrs={"rows": 2})}


class DepartmentForm(_CompanyChildForm):
    class Meta:
        model = Department
        fields = ["company", "code", "name", "is_active"]


class DesignationForm(_CompanyChildForm):
    class Meta:
        model = Designation
        fields = ["company", "code", "name", "is_active"]


class ShiftForm(_CompanyChildForm):
    class Meta:
        model = Shift
        fields = ["company", "code", "name", "start_time", "end_time", "grace_minutes", "break_minutes", "is_active"]
        widgets = {"start_time": forms.TimeInput(attrs={"type": "time"}), "end_time": forms.TimeInput(attrs={"type": "time"})}


class HolidayForm(_CompanyChildForm):
    class Meta:
        model = Holiday
        fields = ["company", "holiday_date", "name", "branch", "is_active"]
        widgets = {"holiday_date": forms.DateInput(attrs={"type": "date"})}

    def __init__(self, *args, company_queryset=None, **kwargs):
        super().__init__(*args, company_queryset=company_queryset, **kwargs)
        company_id = (
            self.instance.company_id
            if getattr(self.instance, "pk", None)
            else (self.data.get("company") if self.is_bound else getattr(self.instance, "company_id", None))
        )
        self.fields["branch"].queryset = Branch.objects.filter(company_id=company_id, is_active=True).order_by("name") if company_id else Branch.objects.none()

    def clean(self):
        cleaned = super().clean()
        company = cleaned.get("company")
        branch = cleaned.get("branch")
        if company and branch and branch.company_id != company.id:
            self.add_error("branch", "Selected branch does not belong to the selected company.")
        return cleaned


class MasterLifecycleForm(forms.Form):
    reason = forms.CharField(widget=forms.Textarea(attrs={"rows": 3}), min_length=5, help_text="Required for activate/deactivate audit trail.")
