import enum
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from typing import Any, ClassVar, Generic, Literal, TypeAlias, TypeVar, cast, overload, type_check_only

from django import forms
from django.contrib.admin.filters import FieldListFilter, ListFilter
from django.contrib.admin.models import LogEntry
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.views.main import ChangeList
from django.contrib.contenttypes.models import ContentType
from django.core.checks.messages import CheckMessage
from django.core.paginator import Paginator
from django.db.models.base import Model
from django.db.models.fields import Field
from django.db.models.fields.related import ForeignKey, ManyToManyField, RelatedField
from django.db.models.options import Options
from django.db.models.query import QuerySet
from django.forms.fields import Field as FormField
from django.forms.fields import TypedChoiceField
from django.forms.formsets import BaseFormSet
from django.forms.models import (
    BaseInlineFormSet,
    BaseModelFormSet,
    ModelChoiceField,
    ModelForm,
    ModelMultipleChoiceField,
)
from django.forms.widgets import Media, MediaDefiningClass
from django.http.request import HttpRequest
from django.http.response import HttpResponse, HttpResponseBase, HttpResponseRedirect
from django.template.response import _TemplateForResponseT
from django.urls.resolvers import URLPattern
from django.utils.datastructures import _ListOrTuple
from django.utils.functional import _StrOrPromise
from django.utils.safestring import SafeString
from typing_extensions import Self, TypedDict, deprecated

IS_POPUP_VAR: str
TO_FIELD_VAR: str
IS_FACETS_VAR: str
HORIZONTAL: Literal[1]
VERTICAL: Literal[2]

_Direction: TypeAlias = Literal[1, 2]

class ShowFacets(enum.Enum):
    NEVER = cast(str, ...)
    ALLOW = cast(str, ...)
    ALWAYS = cast(str, ...)

def get_content_type_for_model(obj: type[Model] | Model) -> ContentType: ...
def get_ul_class(radio_style: int) -> str: ...

class IncorrectLookupParameters(Exception): ...

FORMFIELD_FOR_DBFIELD_DEFAULTS: Any
csrf_protect_m: Any

_FieldGroups: TypeAlias = _ListOrTuple[str | _ListOrTuple[str]]

@type_check_only
class _OptionalFieldOpts(TypedDict, total=False):
    classes: Sequence[str]
    description: _StrOrPromise

@type_check_only
class _FieldOpts(_OptionalFieldOpts, total=True):
    fields: _FieldGroups

_FieldsetSpec: TypeAlias = _ListOrTuple[tuple[_StrOrPromise | None, _FieldOpts]]
_ListFilterT: TypeAlias = (
    type[ListFilter]
    | Field[Any, Any]
    | str
    | tuple[Field[Any, Any] | str, type[FieldListFilter]]
    | list[Field[Any, Any] | str | type[FieldListFilter]]
)

# Generic type specifically for models, for use in BaseModelAdmin and subclasses
# https://github.com/typeddjango/django-stubs/issues/482
_ModelT = TypeVar("_ModelT", bound=Model)
_DisplayT: TypeAlias = str | Callable[[_ModelT], str | bool]
_ListDisplayT: TypeAlias = _ListOrTuple[_DisplayT[_ModelT]]

# Options `form`, `list_display`, `list_display_links` and `actions` are not marked as `ClassVar` due to the
# limitations of the current type system: `ClassVar` cannot contain type variables.
class BaseModelAdmin(Generic[_ModelT], metaclass=MediaDefiningClass):
    autocomplete_fields: ClassVar[_ListOrTuple[str]]
    raw_id_fields: ClassVar[_ListOrTuple[str]]
    fields: ClassVar[_FieldGroups | None]
    exclude: ClassVar[_ListOrTuple[str] | None]
    fieldsets: ClassVar[_FieldsetSpec | None]
    form: type[forms.ModelForm[_ModelT]]
    filter_vertical: ClassVar[_ListOrTuple[str]]
    filter_horizontal: ClassVar[_ListOrTuple[str]]
    radio_fields: ClassVar[Mapping[str, _Direction]]
    prepopulated_fields: ClassVar[dict[str, Sequence[str]]]
    formfield_overrides: ClassVar[Mapping[type[Field], Mapping[str, Any]]]
    readonly_fields: ClassVar[_ListOrTuple[str]]
    ordering: ClassVar[_ListOrTuple[str] | None]
    sortable_by: ClassVar[_ListOrTuple[str] | None]
    show_full_result_count: ClassVar[bool]
    checks_class: ClassVar[Any]
    model: type[_ModelT]
    opts: Options[_ModelT]
    admin_site: AdminSite
    def __init__(self) -> None: ...
    def check(self, **kwargs: Any) -> list[CheckMessage]: ...
    def formfield_for_dbfield(self, db_field: Field, request: HttpRequest, **kwargs: Any) -> FormField | None: ...
    def formfield_for_choice_field(
        self, db_field: Field, request: HttpRequest, **kwargs: Any
    ) -> TypedChoiceField | None: ...
    def get_field_queryset(self, db: str | None, db_field: RelatedField, request: HttpRequest) -> QuerySet | None: ...
    def formfield_for_foreignkey(
        self, db_field: ForeignKey, request: HttpRequest, **kwargs: Any
    ) -> ModelChoiceField | None: ...
    def formfield_for_manytomany(
        self, db_field: ManyToManyField, request: HttpRequest, **kwargs: Any
    ) -> ModelMultipleChoiceField | None: ...
    def get_autocomplete_fields(self, request: HttpRequest) -> _ListOrTuple[str]: ...
    def get_view_on_site_url(self, obj: _ModelT | None = ...) -> str | None: ...
    def get_empty_value_display(self) -> SafeString: ...
    def get_exclude(self, request: HttpRequest, obj: _ModelT | None = ...) -> _ListOrTuple[str] | None: ...
    def get_fields(self, request: HttpRequest, obj: _ModelT | None = ...) -> _FieldGroups: ...
    def get_fieldsets(self, request: HttpRequest, obj: _ModelT | None = ...) -> _FieldsetSpec: ...
    def get_inlines(self, request: HttpRequest, obj: _ModelT | None) -> _ListOrTuple[type[InlineModelAdmin]]: ...
    def get_ordering(self, request: HttpRequest) -> _ListOrTuple[str]: ...
    def get_readonly_fields(self, request: HttpRequest, obj: _ModelT | None = ...) -> _ListOrTuple[str]: ...
    def get_prepopulated_fields(self, request: HttpRequest, obj: _ModelT | None = ...) -> dict[str, Sequence[str]]: ...
    def get_queryset(self, request: HttpRequest) -> QuerySet[_ModelT]: ...
    def get_sortable_by(self, request: HttpRequest) -> _ListDisplayT[_ModelT]: ...
    @overload
    @deprecated("None value for the request parameter will be removed in Django 6.0.")
    def lookup_allowed(self, lookup: str, value: str, request: None = None) -> bool: ...
    @overload
    def lookup_allowed(self, lookup: str, value: str, request: HttpRequest) -> bool: ...
    def to_field_allowed(self, request: HttpRequest, to_field: str) -> bool: ...
    def has_add_permission(self, request: HttpRequest) -> bool: ...
    def has_change_permission(self, request: HttpRequest, obj: _ModelT | None = ...) -> bool: ...
    def has_delete_permission(self, request: HttpRequest, obj: _ModelT | None = ...) -> bool: ...
    def has_view_permission(self, request: HttpRequest, obj: _ModelT | None = ...) -> bool: ...
    def has_view_or_change_permission(self, request: HttpRequest, obj: _ModelT | None = ...) -> bool: ...
    def has_module_permission(self, request: HttpRequest) -> bool: ...
    @property
    def view_on_site(self) -> Callable[[_ModelT], str | None] | bool: ...

_ModelAdmin = TypeVar("_ModelAdmin", bound=ModelAdmin[Any])
_ActionCallable: TypeAlias = Callable[[_ModelAdmin, HttpRequest, QuerySet[_ModelT]], HttpResponseBase | None]

class ModelAdmin(BaseModelAdmin[_ModelT]):
    list_display: _ListDisplayT[_ModelT]
    list_display_links: _ListDisplayT[_ModelT] | None
    list_filter: ClassVar[_ListOrTuple[_ListFilterT]]
    list_select_related: ClassVar[bool | _ListOrTuple[str]]
    list_per_page: ClassVar[int]
    list_max_show_all: ClassVar[int]
    list_editable: ClassVar[_ListOrTuple[str]]
    search_fields: ClassVar[_ListOrTuple[str]]
    search_help_text: ClassVar[_StrOrPromise | None]
    date_hierarchy: ClassVar[str | None]
    save_as: ClassVar[bool]
    save_as_continue: ClassVar[bool]
    save_on_top: ClassVar[bool]
    paginator: ClassVar[type]
    preserve_filters: ClassVar[bool]
    show_facets: ClassVar[ShowFacets]
    inlines: ClassVar[_ListOrTuple[type[InlineModelAdmin]]]
    add_form_template: ClassVar[_TemplateForResponseT | None]
    change_form_template: ClassVar[_TemplateForResponseT | None]
    change_list_template: ClassVar[_TemplateForResponseT | None]
    delete_confirmation_template: ClassVar[_TemplateForResponseT | None]
    delete_selected_confirmation_template: ClassVar[_TemplateForResponseT | None]
    object_history_template: ClassVar[_TemplateForResponseT | None]
    popup_response_template: ClassVar[_TemplateForResponseT | None]
    actions: Sequence[_ActionCallable[Self, _ModelT] | str] | None
    action_form: ClassVar[Any]
    actions_on_top: ClassVar[bool]
    actions_on_bottom: ClassVar[bool]
    actions_selection_counter: ClassVar[bool]
    model: type[_ModelT]
    opts: Options[_ModelT]
    admin_site: AdminSite
    def __init__(self, model: type[_ModelT], admin_site: AdminSite) -> None: ...
    def get_inline_instances(self, request: HttpRequest, obj: _ModelT | None = ...) -> list[InlineModelAdmin]: ...
    def get_urls(self) -> list[URLPattern]: ...
    @property
    def urls(self) -> list[URLPattern]: ...
    @property
    def media(self) -> Media: ...
    def get_model_perms(self, request: HttpRequest) -> dict[str, bool]: ...
    def get_form(
        self, request: HttpRequest, obj: _ModelT | None = ..., change: bool = ..., **kwargs: Any
    ) -> type[forms.ModelForm[_ModelT]]: ...
    def get_changelist(self, request: HttpRequest, **kwargs: Any) -> type[ChangeList]: ...
    def get_changelist_instance(self, request: HttpRequest) -> ChangeList: ...
    def get_object(self, request: HttpRequest, object_id: str, from_field: str | None = ...) -> _ModelT | None: ...
    def get_changelist_form(self, request: HttpRequest, **kwargs: Any) -> type[ModelForm[_ModelT]]: ...
    def get_changelist_formset(
        self, request: HttpRequest, **kwargs: Any
    ) -> type[BaseModelFormSet[_ModelT, ModelForm[_ModelT]]]: ...
    def get_formsets_with_inlines(self, request: HttpRequest, obj: _ModelT | None = ...) -> Iterator[Any]: ...
    def get_paginator(
        self,
        request: HttpRequest,
        queryset: QuerySet,
        per_page: int,
        orphans: int = ...,
        allow_empty_first_page: bool = ...,
    ) -> Paginator: ...
    def log_addition(self, request: HttpRequest, obj: _ModelT, message: Any) -> LogEntry: ...
    def log_change(self, request: HttpRequest, obj: _ModelT, message: Any) -> LogEntry: ...
    @deprecated("log_deletion() is deprecated and will be removed in Django 6.0. Use log_deletions() instead.")
    def log_deletion(self, request: HttpRequest, obj: _ModelT, object_repr: str) -> LogEntry: ...
    def log_deletions(self, request: HttpRequest, queryset: QuerySet[_ModelT]) -> list[LogEntry] | LogEntry: ...
    def action_checkbox(self, obj: _ModelT) -> SafeString: ...
    def get_actions(self, request: HttpRequest) -> dict[str, tuple[Callable[..., str], str, str] | None]: ...
    def get_action_choices(
        self, request: HttpRequest, default_choices: list[tuple[str, str]] = ...
    ) -> list[tuple[str, str]]: ...
    def get_action(self, action: Callable | str) -> tuple[Callable[..., str], str, str] | None: ...
    def get_list_display(self, request: HttpRequest) -> _ListDisplayT[_ModelT]: ...
    def get_list_display_links(
        self, request: HttpRequest, list_display: _ListDisplayT[_ModelT]
    ) -> _ListDisplayT[_ModelT]: ...
    def get_list_filter(self, request: HttpRequest) -> _ListOrTuple[_ListFilterT]: ...
    def get_list_select_related(self, request: HttpRequest) -> bool | _ListOrTuple[str]: ...
    def get_search_fields(self, request: HttpRequest) -> _ListOrTuple[str]: ...
    def get_search_results(
        self, request: HttpRequest, queryset: QuerySet, search_term: str
    ) -> tuple[QuerySet[_ModelT], bool]: ...
    def get_preserved_filters(self, request: HttpRequest) -> str: ...
    def _get_edited_object_pks(self, request: HttpRequest, prefix: str) -> list[str]: ...
    def _get_list_editable_queryset(self, request: HttpRequest, prefix: str) -> QuerySet[_ModelT]: ...
    def construct_change_message(
        self, request: HttpRequest, form: forms.Form, formsets: Iterable[BaseFormSet], add: bool = ...
    ) -> list[dict[str, dict[str, list[str]]]]: ...
    def message_user(
        self,
        request: HttpRequest,
        message: _StrOrPromise,
        level: int | str = ...,
        extra_tags: str = ...,
        fail_silently: bool = ...,
    ) -> None: ...
    def save_form(self, request: HttpRequest, form: Any, change: Any) -> Any: ...
    def save_model(self, request: HttpRequest, obj: _ModelT, form: Any, change: Any) -> None: ...
    def delete_model(self, request: HttpRequest, obj: _ModelT) -> None: ...
    def delete_queryset(self, request: HttpRequest, queryset: QuerySet) -> None: ...
    def save_formset(self, request: HttpRequest, form: Any, formset: Any, change: Any) -> None: ...
    def save_related(self, request: HttpRequest, form: Any, formsets: Any, change: Any) -> None: ...
    def render_change_form(
        self,
        request: HttpRequest,
        context: dict[str, Any],
        add: bool = ...,
        change: bool = ...,
        form_url: str = ...,
        obj: _ModelT | None = ...,
    ) -> HttpResponse: ...
    def response_add(self, request: HttpRequest, obj: _ModelT, post_url_continue: str | None = ...) -> HttpResponse: ...
    def response_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponse: ...
    def response_post_save_add(self, request: HttpRequest, obj: _ModelT) -> HttpResponseRedirect: ...
    def response_post_save_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponseRedirect: ...
    # Probably FileResponse cannot come from ModelAdmin views
    def response_action(self, request: HttpRequest, queryset: QuerySet) -> HttpResponse | None: ...
    def response_delete(self, request: HttpRequest, obj_display: str, obj_id: int) -> HttpResponse: ...
    def render_delete_form(self, request: HttpRequest, context: dict[str, Any]) -> HttpResponse: ...
    def get_inline_formsets(
        self, request: HttpRequest, formsets: list[Any], inline_instances: list[Any], obj: _ModelT | None = ...
    ) -> list[Any]: ...
    def get_changeform_initial_data(self, request: HttpRequest) -> dict[str, str | list[str]]: ...
    def changeform_view(
        self,
        request: HttpRequest,
        object_id: str | None = ...,
        form_url: str = ...,
        extra_context: dict[str, Any] | None = ...,
    ) -> HttpResponse: ...
    def add_view(
        self, request: HttpRequest, form_url: str = ..., extra_context: dict[str, Any] | None = ...
    ) -> HttpResponse: ...
    def change_view(
        self, request: HttpRequest, object_id: str, form_url: str = ..., extra_context: dict[str, Any] | None = ...
    ) -> HttpResponse: ...
    def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = ...) -> HttpResponse: ...
    def get_deleted_objects(
        self, objs: Sequence[_ModelT] | QuerySet[_ModelT], request: HttpRequest
    ) -> tuple[list[str], dict[str, int], set[str], list[str]]: ...
    def delete_view(
        self, request: HttpRequest, object_id: str, extra_context: dict[str, Any] | None = ...
    ) -> HttpResponse: ...
    def history_view(
        self, request: HttpRequest, object_id: str, extra_context: dict[str, Any] | None = ...
    ) -> HttpResponse: ...
    def get_formset_kwargs(
        self, request: HttpRequest, obj: _ModelT, inline: InlineModelAdmin[Any, _ModelT], prefix: str
    ) -> dict[str, Any]: ...

_ChildModelT = TypeVar("_ChildModelT", bound=Model)
_ParentModelT = TypeVar("_ParentModelT", bound=Model)

class InlineModelAdmin(BaseModelAdmin[_ChildModelT], Generic[_ChildModelT, _ParentModelT]):
    model: type[_ChildModelT]
    fk_name: str | None
    formset: type[BaseInlineFormSet[_ChildModelT, _ParentModelT, forms.ModelForm[_ChildModelT]]]
    extra: int
    min_num: int | None
    max_num: int | None
    template: str
    verbose_name: _StrOrPromise | None
    verbose_name_plural: _StrOrPromise | None
    can_delete: bool
    show_change_link: bool
    classes: Sequence[str] | None
    admin_site: AdminSite
    parent_model: type[_ParentModelT]
    opts: Options[_ChildModelT]
    has_registered_model: bool
    def __init__(self, parent_model: type[_ParentModelT], admin_site: AdminSite) -> None: ...
    @property
    def media(self) -> Media: ...
    def get_extra(self, request: HttpRequest, obj: _ParentModelT | None = ..., **kwargs: Any) -> int: ...
    def get_min_num(self, request: HttpRequest, obj: _ParentModelT | None = ..., **kwargs: Any) -> int | None: ...
    def get_max_num(self, request: HttpRequest, obj: _ParentModelT | None = ..., **kwargs: Any) -> int | None: ...
    def get_formset(
        self, request: HttpRequest, obj: _ParentModelT | None = ..., **kwargs: Any
    ) -> type[BaseInlineFormSet[_ChildModelT, _ParentModelT, forms.ModelForm[_ChildModelT]]]: ...
    def get_queryset(self, request: HttpRequest) -> QuerySet[_ChildModelT]: ...
    def has_add_permission(self, request: HttpRequest, obj: _ParentModelT | None) -> bool: ...  # type: ignore[override]
    def has_change_permission(self, request: HttpRequest, obj: _ParentModelT | None = ...) -> bool: ...  # type: ignore[override]
    def has_delete_permission(self, request: HttpRequest, obj: _ParentModelT | None = ...) -> bool: ...  # type: ignore[override]
    def has_view_permission(self, request: HttpRequest, obj: _ParentModelT | None = ...) -> bool: ...  # type: ignore[override]

class StackedInline(InlineModelAdmin[_ChildModelT, _ParentModelT]):
    template: str

class TabularInline(InlineModelAdmin[_ChildModelT, _ParentModelT]):
    template: str
