from django.contrib import admin
from . import models
from datetime import datetime, time, date
from django.utils import timezone
from django.utils.html import format_html, urlencode
from django.urls import reverse


@admin.register(models.Department)
class DepartmentAdmin(admin.ModelAdmin):
    list_display = ['name', 'description']
    search_fields = ['name']


@admin.register(models.Position)
class PositionAdmin(admin.ModelAdmin):
    list_display = ['name', 'get_department_name', 'description']

    def department_name(self, position):
        return position.Department.name


@admin.register(models.SalaryScale)
class SalaryScaleAdmin(admin.ModelAdmin):
    list_display = ['name', 'basic_pay', 'travel_allowance', 'food_allowance',
                    'individual_allowance', 'currency', 'total_salary']

    def total_salary(self, obj):
        return obj.basic_pay + obj.travel_allowance + obj.food_allowance + obj.individual_allowance
    total_salary.short_description = 'مجموع معاش'


@admin.register(models.LeaveType)
class LeaveTypeAdmin(admin.ModelAdmin):
    list_display = ['name', 'description']


@admin.register(models.WorkingShift)
class WorkingShiftAdmin(admin.ModelAdmin):
    list_display = ['name', 'start_time', 'end_time', 'working_hours']


@admin.register(models.Employee)
class EmployeeAdmin(admin.ModelAdmin):
    list_display = ['name', 'father_name', 'primary_phone']

    def view_details(self, obj):
        url = reverse('humanresource:employee_details', kwargs={'pk': obj.id})
        return format_html('<a href="{}">View details</a>', url)

        view_details.short_description = 'Details'


@admin.register(models.Education)
class EducaionAdmin(admin.ModelAdmin):
    list_display = ['employee', 'degree_type',
                    'institution', 'grade_point_average']


@admin.register(models.Attachment)
class AttachmentAdmin(admin.ModelAdmin):
    list_display = ['name', 'employee', 'file', 'uploaded_by', 'uploaded_at']
    fields = ['name', 'employee', 'file']

    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.uploaded_by = request.user
        else:
            obj.updated_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(models.Employment)
class EmploymentAdmin(admin.ModelAdmin):
    list_display = ['employee', 'department',
                    'position', 'join_date']
    search_fields = ['employee']

    def view_details(self, obj):
        url = reverse('humanresource:employement_details',
                      kwargs={'pk': obj.id})
        return format_html('<a href="{}">View details</a>', url)

        view_details.short_description = 'Details'
