# staff/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html
from .models import Staff, TeacherSubject, StaffAttendance, StaffLeave, StaffDocument

User = get_user_model()

class StaffInline(admin.StackedInline):
    model = Staff
    can_delete = False
    verbose_name_plural = 'Staff Profile'
    fk_name = 'user'
    fieldsets = (
        ('Basic Information', {
            'fields': ('employee_id', 'role', 'department', 'school')
        }),
        ('Personal', {
            'fields': ('title', 'date_of_birth', 'gender', 'nationality', 'marital_status')
        }),
        ('Contact', {
            'fields': (
                'phone_country_code', 'phone_number',
                'alt_phone_country_code', 'alternate_phone',
                'email', 'address', 'quarter', 'city',
            )
        }),
        ('Employment', {
            'fields': ('employment_status', 'hire_date', 'contract_end_date')
        }),
        ('Financial', {
            'fields': ('salary', 'bank_name', 'bank_account', 'tax_id', 'social_security'),
            'classes': ('collapse',)
        }),
    )

class CustomUserAdmin(UserAdmin):
    inlines = [StaffInline]
    list_display = ['username', 'email', 'first_name', 'last_name', 'is_staff', 'get_role']
    list_filter = ['is_staff', 'is_superuser', 'staff_profile__role']
    
    def get_role(self, obj):
        if hasattr(obj, 'staff_profile'):
            return obj.staff_profile.get_role_display()
        return '-'
    get_role.short_description = 'Role'
    get_role.admin_order_field = 'staff_profile__role'

# Unregister default User admin and register custom
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

@admin.register(Staff)
class StaffAdmin(admin.ModelAdmin):
    list_display = ['employee_id', 'photo_thumbnail', 'get_full_name', 'role', 'department', 'phone_number', 'is_active']
    list_filter = ['role', 'department', 'employment_status', 'is_active', 'school']
    search_fields = ['employee_id', 'user__first_name', 'user__last_name', 'phone_number', 'email']
    list_editable = ['is_active']
    list_per_page = 25
    
    fieldsets = (
        ('User Account', {
            'fields': ('user', 'employee_id', 'school')
        }),
        ('Personal Information', {
            'fields': ('title', 'date_of_birth', 'gender', 'nationality', 'marital_status', 'photo')
        }),
        ('Contact Details', {
            'fields': (
                'phone_country_code', 'phone_number',
                'alt_phone_country_code', 'alternate_phone',
                'email', 'address', 'quarter', 'city',
            )
        }),
        ('Emergency Contact', {
            'fields': (
                'emergency_contact_name',
                'emergency_phone_country_code', 'emergency_contact_phone',
                'emergency_contact_relationship',
            ),
            'classes': ('collapse',)
        }),
        ('Employment Details', {
            'fields': ('role', 'department', 'employment_status', 'hire_date', 'contract_end_date')
        }),
        ('Qualifications', {
            'fields': ('qualifications', 'specialization', 'years_of_experience'),
            'classes': ('collapse',)
        }),
        ('Financial Information', {
            'fields': ('salary', 'bank_name', 'bank_account', 'bank_branch', 'tax_id', 'social_security'),
            'classes': ('collapse',)
        }),
        ('Documents', {
            'fields': ('cv_file', 'contract_file', 'id_document', 'diplomas'),
            'classes': ('collapse',)
        }),
        ('System', {
            'fields': ('is_active', 'notes', 'imported_from', 'original_data'),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ['employee_id', 'created_at', 'updated_at']
    
    def photo_thumbnail(self, obj):
        if obj.photo:
            return format_html('<img src="{}" width="50" height="50" style="border-radius: 50%;" />', obj.photo.url)
        return format_html('<div style="width:50px;height:50px;background:#4CAF50;border-radius:50%;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;">{}</div>', 
                         obj.user.first_name[0] if obj.user.first_name else '?')
    photo_thumbnail.short_description = 'Photo'
    
    def get_full_name(self, obj):
        return obj.get_display_name() or obj.user.get_full_name()
    get_full_name.short_description = 'Full Name'
    get_full_name.admin_order_field = 'user__first_name'
    
    actions = ['export_as_csv', 'deactivate_staff', 'send_welcome_email']
    
    def export_as_csv(self, request, queryset):
        import csv
        from django.http import HttpResponse
        
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="staff_export.csv"'
        
        writer = csv.writer(response)
        writer.writerow(['Employee ID', 'Title', 'Full Name', 'Role', 'Department', 'Phone', 'Email', 'Status'])
        
        for staff in queryset:
            writer.writerow([
                staff.employee_id,
                staff.title,
                staff.user.get_full_name(),
                staff.get_role_display(),
                staff.get_department_display(),
                f"{staff.phone_country_code} {staff.phone_number}".strip() if staff.phone_number else '',
                staff.email,
                'Active' if staff.is_active else 'Inactive'
            ])
        
        return response
    export_as_csv.short_description = "Export selected staff as CSV"
    
    def deactivate_staff(self, request, queryset):
        queryset.update(is_active=False)
        self.message_user(request, f"{queryset.count()} staff members deactivated.")
    deactivate_staff.short_description = "Deactivate selected staff"
    
    def send_welcome_email(self, request, queryset):
        for staff in queryset:
            # Add email sending logic here
            pass
        self.message_user(request, f"Welcome emails sent to {queryset.count()} staff members.")
    send_welcome_email.short_description = "Send welcome email"

@admin.register(StaffAttendance)
class StaffAttendanceAdmin(admin.ModelAdmin):
    list_display = ['staff', 'date', 'check_in_time', 'check_out_time', 'status']
    list_filter = ['status', 'date']
    search_fields = ['staff__user__first_name', 'staff__user__last_name', 'staff__employee_id']
    date_hierarchy = 'date'

@admin.register(StaffLeave)
class StaffLeaveAdmin(admin.ModelAdmin):
    list_display = ['staff', 'leave_type', 'start_date', 'end_date', 'days_requested', 'status']
    list_filter = ['leave_type', 'status']
    search_fields = ['staff__user__first_name', 'staff__user__last_name']
    date_hierarchy = 'start_date'
    
    actions = ['approve_leaves', 'reject_leaves']
    
    def approve_leaves(self, request, queryset):
        from django.utils import timezone
        queryset.update(status='approved', approved_by=request.user.staff_profile, approved_date=timezone.now().date())
        self.message_user(request, f"{queryset.count()} leave requests approved.")
    approve_leaves.short_description = "Approve selected leave requests"
    
    def reject_leaves(self, request, queryset):
        queryset.update(status='rejected')
        self.message_user(request, f"{queryset.count()} leave requests rejected.")
    reject_leaves.short_description = "Reject selected leave requests"