from django.contrib import admin
from .models import Employee, Supplier, Customer
from django.forms import ModelForm
from phonenumbers import parse, is_valid_number, format_number, PhoneNumberFormat, NumberParseException
from django import forms
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from unfold.admin import ModelAdmin
from unfold.contrib.import_export.forms import ExportForm, ImportForm, SelectableFieldsExportForm
from django.utils.translation import gettext_lazy as _

# Register your models here.

class EmployeeForm(ModelForm):
    class Meta:
        model = Employee
        fields = "__all__"
        widgets = {
            'phone_number': forms.TextInput(attrs={'placeholder': 'e.g., +62813xxxxxxx'}),
        }

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        if not phone_number:
            raise forms.ValidationError("Phone number is required and cannot be empty.")
        try:
            if not phone_number.startswith('+'):
                phone_number = '+62' + phone_number.lstrip('0')
            parsed_phone = parse(phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            # Return standardized phone number
            return format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError(f"Invalid phone number format: {phone_number}")
        
class SupplierForm(ModelForm):
    class Meta:
        model = Supplier
        fields = "__all__"
        widgets = {
            'phone_number': forms.TextInput(attrs={'placeholder': 'e.g., +62813xxxxxxx'}),
        }

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        if not phone_number:
            raise forms.ValidationError("Phone number is required and cannot be empty.")
        try:
            if not phone_number.startswith('+'):
                phone_number = '+62' + phone_number.lstrip('0')
            parsed_phone = parse(phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            # Return standardized phone number
            return format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError(f"Invalid phone number format: {phone_number}")
        
class CustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = "__all__"
        widgets = {
            'phone_number': forms.TextInput(attrs={'placeholder': 'e.g., +62813xxxxxxx'}),
        }

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        if not phone_number:
            raise forms.ValidationError("Phone number is required and cannot be empty.")
        try:
            if not phone_number.startswith('+'):
                phone_number = '+62' + phone_number.lstrip('0')
            parsed_phone = parse(phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            # Return standardized phone number
            return format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError(f"Invalid phone number format: {phone_number}")

# Buat resource untuk model Employee
class EmployeeResource(resources.ModelResource):
    def before_import_row(self, row, **kwargs):
        phone_number = row.get("phone_number")
        if phone_number:
            try:
                # Konversi ke string untuk memastikan bisa diproses
                phone_number = str(phone_number).strip()
                
                # Handle kasus awalan "0", ganti dengan "62"
                if phone_number.startswith("0"):
                    phone_number = "62" + phone_number[1:]

                # Parse nomor telepon
                parsed_phone = parse(phone_number, "ID")
                if not is_valid_number(parsed_phone):
                    raise ValueError(f"Invalid phone number: {phone_number}")

                # Format ke E.164 (format internasional)
                row["phone_number"] = format_number(parsed_phone, PhoneNumberFormat.E164)
            except NumberParseException:
                raise ValueError(f"Invalid phone number format: {phone_number}")
            
    class Meta:
        model = Employee
        fields = (
            'id', 
            'name', 
            'phone_number',
            'email', 
            'position', 
            'address', 
        )
        import_id_fields = ['name', 'phone_number']  # Field unik untuk menghindari duplikasi data

class SupplierResource(resources.ModelResource):
    def before_import_row(self, row, **kwargs):
        phone_number = row.get("phone_number")
        if phone_number:
            try:
                phone_number = str(phone_number).strip()
                
                if phone_number.startswith("0"):
                    phone_number = "62" + phone_number[1:]

                parsed_phone = parse(phone_number, "ID")
                if not is_valid_number(parsed_phone):
                    raise ValueError(f"Invalid phone number: {phone_number}")

                row["phone_number"] = format_number(parsed_phone, PhoneNumberFormat.E164)
            except NumberParseException:
                raise ValueError(f"Invalid phone number format: {phone_number}")
        
    class Meta:
        model = Supplier
        fields = (
            'id', 
            'name',
            'contact_person', 
            'phone_number',
            'email', 
            'address', 
        )
        import_id_fields = ['name', 'phone_number']

class CustomerResource(resources.ModelResource):
    def before_import_row(self, row, **kwargs):
        phone_number = row.get("phone_number")
        if phone_number:
            try:                
                phone_number = str(phone_number).strip()
                
                if phone_number.startswith("0"):
                    phone_number = "62" + phone_number[1:]

                parsed_phone = parse(phone_number, "ID")
                if not is_valid_number(parsed_phone):
                    raise ValueError(f"Invalid phone number: {phone_number}")

                row["phone_number"] = format_number(parsed_phone, PhoneNumberFormat.E164)
            except NumberParseException:
                raise ValueError(f"Invalid phone number format: {phone_number}")
        
    class Meta:
        model = Customer
        fields = (
            'id', 
            'name', 
            'phone_number',
            'email', 
            'address', 
        )
        import_id_fields = ['name', 'phone_number']

#@admin.register(Employee)
class EmployeeAdmin(ModelAdmin, ImportExportModelAdmin):
    list_display = ('position', 'name', 'phone_number', 'email', 'address', 'updated_at')
    search_fields = ('name', 'phone_number', 'email', 'position', 'address')
    #list_filter = ('position',)
    list_per_page = 10
    #form = EmployeeForm
    resource_class = EmployeeResource
    import_form_class= ImportForm
    export_form_class= SelectableFieldsExportForm  

    def has_import_permission(self, request):
        # Hanya mengizinkan impor jika user memiliki permission selain "view"
        return request.user.has_perm('app.add_employee') or request.user.has_perm('app.change_employee') or request.user.has_perm('app.delete_employee')

    def has_export_permission(self, request):
        return request.user.has_perm('app.add_employee') or request.user.has_perm('app.change_employee') or request.user.has_perm('app.delete_employee') 


admin.site.register(Employee, EmployeeAdmin)
    

@admin.register(Supplier)
class SupplierAdmin(ModelAdmin, ImportExportModelAdmin):
    list_display = ('name', 'contact_person', 'phone_number', 'email', 'address', 'updated_at')
    search_fields = ('name', 'contact_person', 'phone_number', 'email', 'address')
    #list_filter = ('contact_person',)
    list_per_page = 10
    #form = SupplierForm
    resource_class = SupplierResource
    import_form_class= ImportForm
    export_form_class= SelectableFieldsExportForm  

    def has_import_permission(self, request):
        return request.user.has_perm('app.add_supplier') or request.user.has_perm('app.change_supplier') or request.user.has_perm('app.delete_supplier')

    def has_export_permission(self, request):
        return request.user.has_perm('app.add_supplier') or request.user.has_perm('app.change_supplier') or request.user.has_perm('app.delete_supplier')  

@admin.register(Customer)
class CustomerAdmin(ModelAdmin, ImportExportModelAdmin):
    list_display = ('name', 'phone_number', 'email', 'address', 'updated_at',)
    search_fields = ('name', 'phone_number', 'email', 'address')
    #list_filter = ('name',)
    list_per_page = 10
    #form = CustomerForm
    resource_class = CustomerResource
    import_form_class= ImportForm
    export_form_class= SelectableFieldsExportForm

    def has_import_permission(self, request):
        return request.user.has_perm('app.add_customer') or request.user.has_perm('app.change_customer') or request.user.has_perm('app.delete_customer')

    def has_export_permission(self, request):
        return request.user.has_perm('app.add_customer') or request.user.has_perm('app.change_customer') or request.user.has_perm('app.delete_customer') 
    