from django.contrib import admin
from django.utils.html import format_html
from .models import OvertimeRequest, Holiday, CompanyOvertimeConfig
from wtlms.admin import admin_site

# Register your models here.

@admin.register(Holiday, site=admin_site)
class HolidayAdmin(admin.ModelAdmin):
    list_display = ('name', 'date', 'recurring', 'company')
    list_filter = ('recurring', 'company')
    search_fields = ('name',)
    ordering = ('date',)
    date_hierarchy = 'date'

@admin.register(CompanyOvertimeConfig, site=admin_site)
class CompanyOvertimeConfigAdmin(admin.ModelAdmin):
    list_display = ('company', 'calculation_method', 'working_days_per_month', 'weekday_rate', 'saturday_rate', 'sunday_holiday_rate')
    list_filter = ('calculation_method',)
    search_fields = ('company__name',)
    
    fieldsets = (
        ('Company', {
            'fields': ('company',)
        }),
        ('Working Hours', {
            'fields': ('working_days_per_month', 'working_hours_per_day')
        }),
        ('Rate Configuration', {
            'fields': ('weekday_rate', 'saturday_rate', 'sunday_holiday_rate')
        }),
        ('Calculation Method', {
            'fields': ('calculation_method',)
        }),
        ('Fixed Rate Settings', {
            'fields': ('fixed_weekday_amount', 'fixed_saturday_amount', 'fixed_sunday_holiday_amount'),
            'classes': ('collapse',),
            'description': 'Only used when calculation method is FIXED_RATE'
        }),
        ('Custom Formula', {
            'fields': ('custom_formula',),
            'classes': ('collapse',),
            'description': 'Only used when calculation method is CUSTOM. Available variables: basic_pay, hours, rate'
        })
    )

@admin.register(OvertimeRequest, site=admin_site)
class OvertimeRequestAdmin(admin.ModelAdmin):
    list_display = ('employee', 'date', 'hours', 'rate', 'status', 'payment_status', 'calculate_amount')
    list_filter = ('status', 'payment_status', 'rate')
    search_fields = ('employee__user__username', 'employee__user__first_name', 'employee__user__last_name')
    ordering = ('-date',)
    readonly_fields = ('calculate_amount',)
    
    fieldsets = (
        ('Employee Information', {
            'fields': ('employee',)
        }),
        ('Overtime Details', {
            'fields': ('date', 'hours', 'rate', 'calculate_amount')
        }),
        ('Status', {
            'fields': ('status', 'payment_status')
        }),
        ('Comments', {
            'fields': ('reason', 'hr_comment', 'registrar_comment')
        }),
    )

    def calculate_amount(self, obj):
        amount = obj.calculate_amount()
        return format_html('<span style="color: #004088; font-weight: bold;">K{:,.2f}</span>', amount)
    calculate_amount.short_description = 'Amount'

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if hasattr(request.user, 'employee'):
            role = request.user.employee.role
            if role == 'HR':
                # HR sees all requests
                return qs
            elif role == 'REG':
                # Registrar sees HR approved requests
                return qs.filter(status='HR_APPROVED')
            elif role == 'FIN':
                # Finance sees approved requests
                return qs.filter(status='APPROVED')
        return qs.none()  # Other roles don't see anything in admin

    def has_change_permission(self, request, obj=None):
        if not obj or not hasattr(request.user, 'employee'):
            return False
        role = request.user.employee.role
        if role == 'HR':
            # HR can only change pending requests
            return obj.status == 'PENDING_HR'
        elif role == 'REG':
            # Registrar can only change HR approved requests
            return obj.status == 'HR_APPROVED'
        elif role == 'FIN':
            # Finance can only change payment status of approved requests
            return obj.status == 'APPROVED' and obj.payment_status == 'PENDING'
        return False

    def has_delete_permission(self, request, obj=None):
        if not obj or not hasattr(request.user, 'employee'):
            return False
        # Only HR can delete pending requests
        return request.user.employee.role == 'HR' and obj.status == 'PENDING_HR'

    def has_add_permission(self, request):
        # Overtime requests should be created through the frontend
        return False

    def get_readonly_fields(self, request, obj=None):
        readonly_fields = list(self.readonly_fields)
        if obj and hasattr(request.user, 'employee'):
            role = request.user.employee.role
            if role == 'FIN':
                # Finance can only change payment status
                readonly_fields.extend([
                    'employee', 'date', 'hours', 'rate', 'status',
                    'reason', 'hr_comment', 'registrar_comment'
                ])
        return readonly_fields

    def save_model(self, request, obj, form, change):
        if change and hasattr(request.user, 'employee'):
            role = request.user.employee.role
            if role == 'HR' and 'status' in form.changed_data:
                if obj.status == 'HR_APPROVED':
                    obj.hr_comment = f'Approved by {request.user.get_full_name()}'
                elif obj.status == 'REJECTED':
                    obj.hr_comment = f'Rejected by {request.user.get_full_name()}'
            elif role == 'REG' and 'status' in form.changed_data:
                if obj.status == 'APPROVED':
                    obj.registrar_comment = f'Approved by {request.user.get_full_name()}'
                elif obj.status == 'REJECTED':
                    obj.registrar_comment = f'Rejected by {request.user.get_full_name()}'
        super().save_model(request, obj, form, change)
