"""
Organizations admin
"""

from django.contrib import admin

from .models import (
    Department,
    Hospital,
    LegacyHierarchyMapping,
    LegacyLocation,
    LegacyMainSection,
    LegacySubSection,
    Section,
    OrgSubSection,
    SubSection,
    Organization,
    Patient,
    Staff,
)


@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
    """Organization admin"""

    list_display = ["name", "code", "city", "status", "created_at"]
    list_filter = ["status", "city"]
    search_fields = ["name", "name_ar", "code"]
    ordering = ["name"]

    fieldsets = (
        (None, {"fields": ("name", "name_ar", "code")}),
        ("Contact Information", {"fields": ("address", "city", "phone", "email")}),
        ("Details", {"fields": ("status", "preferred_language")}),
        ("Metadata", {"fields": ("created_at", "updated_at")}),
    )

    readonly_fields = ["created_at", "updated_at"]


@admin.register(Hospital)
class HospitalAdmin(admin.ModelAdmin):
    """Hospital admin"""

    list_display = ["name", "get_display_name", "code", "city", "ceo", "status", "capacity", "created_at"]
    list_filter = ["status", "city"]
    search_fields = ["name", "name_ar", "display_name", "display_name_ar", "code", "license_number"]
    ordering = ["name"]

    fieldsets = (
        (None, {"fields": ("organization", "name", "name_ar", "code")}),
        ("Display", {"fields": ("display_name", "display_name_ar")}),
        ("Contact Information", {"fields": ("address", "city", "phone", "email")}),
        ("Executive Leadership", {"fields": ("ceo", "medical_director", "coo", "cfo")}),
        ("Details", {"fields": ("license_number", "capacity", "status")}),
        ("Metadata", {"fields": ("created_at", "updated_at")}),
    )
    autocomplete_fields = ["organization", "ceo", "medical_director", "coo", "cfo"]

    readonly_fields = ["created_at", "updated_at"]


@admin.register(Department)
class DepartmentAdmin(admin.ModelAdmin):
    """Department admin"""

    list_display = ["name", "hospital", "code", "category", "manager", "status", "created_at"]
    list_filter = ["status", "hospital", "category"]
    search_fields = ["name", "name_ar", "code"]
    ordering = ["hospital", "name"]
    autocomplete_fields = ["hospital", "parent", "manager"]

    fieldsets = (
        (None, {"fields": ("hospital", "name", "name_ar", "code", "category")}),
        ("Hierarchy", {"fields": ("parent", "manager")}),
        ("Contact", {"fields": ("phone", "email", "location")}),
        ("Status", {"fields": ("status",)}),
        ("Metadata", {"fields": ("created_at", "updated_at")}),
    )

    readonly_fields = ["created_at", "updated_at"]

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related("hospital", "manager", "parent")


@admin.register(Staff)
class StaffAdmin(admin.ModelAdmin):
    """Staff admin"""

    list_display = [
        "__str__",
        "staff_type",
        "job_title",
        "employee_id",
        "hospital",
        "department",
        "email",
        "phone",
        "report_to",
        "country",
        "has_user_account",
        "status",
    ]
    list_filter = ["status", "hospital", "staff_type", "specialization", "gender", "country"]
    search_fields = [
        "name",
        "first_name",
        "last_name",
        "first_name_ar",
        "last_name_ar",
        "employee_id",
        "license_number",
        "job_title",
        "phone",
        "department_name",
        "section",
    ]
    ordering = ["last_name", "first_name"]
    autocomplete_fields = ["hospital", "department", "user", "report_to"]
    actions = ["create_user_accounts", "send_credentials_emails"]

    fieldsets = (
        (None, {"fields": ("name", "first_name", "last_name", "first_name_ar", "last_name_ar")}),
        ("Role", {"fields": ("staff_type", "job_title")}),
        ("Professional", {"fields": ("license_number", "specialization", "employee_id", "email", "phone")}),
        (
            "Organization",
            {"fields": ("hospital", "department", "department_name", "section", "subsection", "location")},
        ),
        ("Hierarchy", {"fields": ("report_to",)}),
        ("Personal Information", {"fields": ("country", "gender")}),
        ("Account", {"fields": ("user",)}),
        ("Status", {"fields": ("status",)}),
        ("Metadata", {"fields": ("created_at", "updated_at")}),
    )

    readonly_fields = ["created_at", "updated_at"]

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related("hospital", "department", "user")

    def has_user_account(self, obj):
        """Display user account status"""
        if obj.user:
            return '<span style="color: green;">✓ Yes</span>'
        return '<span style="color: red;">✗ No</span>'

    has_user_account.short_description = "User Account"
    has_user_account.allow_tags = True

    def create_user_accounts(self, request, queryset):
        """Admin action to create user accounts for selected staff"""
        from .services import StaffService

        created = 0
        failed = 0
        for staff in queryset:
            if not staff.user and staff.email:
                try:
                    user, was_created, _password = StaffService.create_user_for_staff(staff, role='staff', request=request)
                    if was_created and user:
                        StaffService.send_password_reset_email(staff, request)
                    created += 1
                except Exception as e:
                    failed += 1

        self.message_user(
            request, f"Created {created} user accounts. Failed: {failed}", level="success" if failed == 0 else "warning"
        )

    create_user_accounts.short_description = "Create user accounts for selected staff"

    def send_password_reset_emails(self, request, queryset):
        """Admin action to send password reset links to selected staff"""
        from .services import StaffService

        sent = 0
        failed = 0
        for staff in queryset:
            if staff.user and staff.email:
                try:
                    StaffService.send_password_reset_email(staff, request)
                    sent += 1
                except Exception as e:
                    failed += 1

        self.message_user(
            request, f"Sent {sent} password reset emails. Failed: {failed}", level="success" if failed == 0 else "warning"
        )

    send_password_reset_emails.short_description = "Send password reset links to selected staff"


@admin.register(Patient)
class PatientAdmin(admin.ModelAdmin):
    """Patient admin"""

    list_display = ["get_full_name", "mrn", "get_masked_national_id", "phone", "primary_hospital", "status"]
    list_filter = ["status", "gender", "primary_hospital", "city"]
    search_fields = [
        "mrn",
        "national_id_hash",
        "first_name",
        "last_name",
        "first_name_ar",
        "last_name_ar",
        "phone",
        "email",
    ]
    ordering = ["last_name", "first_name"]
    autocomplete_fields = ["primary_hospital"]

    fieldsets = (
        (None, {"fields": ("mrn", "national_id")}),
        ("Personal Information", {"fields": ("first_name", "last_name", "first_name_ar", "last_name_ar")}),
        ("Demographics", {"fields": ("date_of_birth", "gender")}),
        ("Contact", {"fields": ("phone", "email", "address", "city")}),
        ("Hospital", {"fields": ("primary_hospital",)}),
        ("Status", {"fields": ("status",)}),
        ("Metadata", {"fields": ("created_at", "updated_at")}),
    )

    readonly_fields = ["created_at", "updated_at"]

    def get_masked_national_id(self, obj):
        return obj.get_masked_national_id()

    get_masked_national_id.short_description = "National ID"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related("primary_hospital")


admin.site.register(LegacyLocation)
admin.site.register(LegacyMainSection)
admin.site.register(LegacySubSection)
admin.site.register(OrgSubSection)
admin.site.register(SubSection)
admin.site.register(LegacyHierarchyMapping)
