from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.admin import UserAdmin
from django import forms
from django.shortcuts import redirect
from django.urls import path,reverse
from django.utils.html import format_html
from .models import User,EmploymentHistory,OTPChallenge,Member,AccountInvitation
from .services import issue_account_invitation
class EmploymentUserChoiceField(forms.ModelChoiceField):
 def label_from_instance(self,user):
  member=getattr(user,'member_profile',None)
  if member:
   name=' '.join(part for part in (member.first_name,member.other_names,member.last_name) if part)
   return f'{name} Â· {member.primary_phone}'
  return f'{user.get_full_name() or "Unlinked account"} Â· {user.phone_number}'
class EmploymentHistoryAdminForm(forms.ModelForm):
 class Meta: model=EmploymentHistory; fields='__all__'
 user=EmploymentUserChoiceField(queryset=User.objects.select_related('member_profile').all())
@admin.register(User)
class CustomUserAdmin(UserAdmin):
 model=User; ordering=('phone_number',); list_display=('phone_number','first_name','last_name','member_type','campus','profile_completed','is_staff'); list_filter=('member_type','profile_completed','is_staff','is_active','country','campus'); search_fields=('phone_number','first_name','last_name','email','profession','employer'); list_select_related=('country','campus'); fieldsets=UserAdmin.fieldsets+(("Member Profile",{'fields':('phone_number','other_names','gender','date_of_birth','country','campus','member_type','graduation_year','profession','employer','job_title','bio','profile_completed')}),); add_fieldsets=((None,{'classes':('wide',),'fields':('phone_number','password1','password2','is_staff','is_superuser')}),)

@admin.register(EmploymentHistory)
class EmploymentHistoryAdmin(admin.ModelAdmin):
 form=EmploymentHistoryAdminForm; list_display=('member_name','employer','job_title','industry','start_date','end_date','current'); list_filter=('current','industry'); search_fields=('user__phone_number','user__first_name','user__last_name','user__member_profile__first_name','user__member_profile__last_name','employer','job_title'); list_select_related=('user','user__member_profile','industry')
 @admin.display(description='Member',ordering='user__member_profile__first_name')
 def member_name(self,obj):
  member=getattr(obj.user,'member_profile',None)
  return ' '.join(part for part in (member.first_name,member.other_names,member.last_name) if part) if member else f'{obj.user.get_full_name() or "Unlinked account"} ({obj.user.phone_number})'

@admin.register(OTPChallenge)
class OTPChallengeAdmin(admin.ModelAdmin):
 list_display=('phone_number','purpose','created_at','expires_at','attempts','consumed_at'); list_filter=('purpose','created_at'); search_fields=('phone_number',); readonly_fields=('code','created_at','expires_at','attempts','consumed_at'); ordering=('-created_at',)

@admin.register(Member)
class MemberAdmin(admin.ModelAdmin):
 list_display=('member_number','full_name','primary_phone','campus_display','church_branch','account_status_badge','credential_action')
 list_filter=('account_status','status','gender','country','campus','church_branch'); search_fields=('member_number','first_name','other_names','last_name','primary_phone','alternate_phone','user__email'); autocomplete_fields=('user',); readonly_fields=('member_number','source','imported_at','created_at','updated_at','credential_action'); actions=('send_account_invitations',); list_select_related=('user','country','campus')
 fieldsets=(("Identity",{'fields':('member_number','user','first_name','other_names','last_name','gender','nationality')}),("Contact & affiliation",{'fields':('primary_phone','alternate_phone','country','campus','campus_name_raw','church_branch')}),("Account lifecycle",{'fields':('status','account_status','credential_action')}),("Audit",{'classes':('collapse',),'fields':('source','imported_at','created_at','updated_at')}))
 @admin.display(description='Member',ordering='first_name')
 def full_name(self,obj): return f'{obj.first_name} {obj.other_names} {obj.last_name}'.replace('  ',' ')
 @admin.display(description='Campus',ordering='campus__name')
 def campus_display(self,obj): return obj.campus or obj.campus_name_raw or 'â€”'
 @admin.display(description='Account',ordering='account_status')
 def account_status_badge(self,obj): return format_html('<span class="status status-{}">{}</span>',obj.account_status.lower(),obj.get_account_status_display())
 @admin.display(description='Credentials')
 def credential_action(self,obj):
  if not obj.pk:return 'Save the member first'
  return format_html('<a class="button" href="{}">Send invitation</a>',reverse('admin:accounts_member_invite',args=[obj.pk]))
 def get_urls(self): return [path('<int:member_id>/send-invitation/',self.admin_site.admin_view(self.send_invitation),name='accounts_member_invite')]+super().get_urls()
 def send_invitation(self,request,member_id):
  member=self.get_object(request,member_id)
  if member:
   invitation,_=issue_account_invitation(member,request.user)
   if invitation.status==AccountInvitation.Status.SENT: messages.success(request,f'Account invitation sent to {invitation.destination}.')
   else: messages.error(request,f'Invitation failed: {invitation.error}')
  return redirect(reverse('admin:accounts_member_change',args=[member_id]))
 @admin.action(description='Send account invitations to selected members')
 def send_account_invitations(self,request,queryset):
  sent=failed=0
  for member in queryset:
   invitation,_=issue_account_invitation(member,request.user)
   if invitation.status==AccountInvitation.Status.SENT: sent+=1
   else: failed+=1
  self.message_user(request,f'{sent} invitation(s) sent; {failed} failed.',messages.SUCCESS if not failed else messages.WARNING)

@admin.register(AccountInvitation)
class AccountInvitationAdmin(admin.ModelAdmin):
 list_display=('member','channel','destination','status','sent_at','expires_at','accepted_at'); list_filter=('status','channel','created_at'); search_fields=('member__member_number','member__first_name','member__last_name','destination'); readonly_fields=('member','token_hash','channel','destination','status','sent_by','created_at','sent_at','expires_at','accepted_at','error'); ordering=('-created_at',); has_add_permission=lambda self,request:False

