from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.urls import path, include, re_path


def landing_page(request):
    return render(request, "landing.html")


def store_product_page(request):
    return render(request, "pages/store_product.html")


def ai_product_page(request):
    return render(request, "pages/ai_product.html")


def web_chat_disabled(request, *args, **kwargs):
    """Temporarily disable web chat and direct users to WhatsApp."""
    if request.path.startswith("/chat/"):
        if request.path == "/chat/" or request.path == "/chat":
            return redirect("whatsapp:home")
        return JsonResponse(
            {
                "error": "Web chat is temporarily disabled. Please use WhatsApp.",
                "redirect": "/whatsapp/",
            },
            status=403,
        )
    return HttpResponse(status=404)


@login_required
def login_redirect_view(request):
    """Route users to the correct dashboard based on their role."""
    user = request.user
    # Vendor users → vendor dashboard
    if hasattr(user, "vendor_profile"):
        return redirect("vendors:dashboard")
    # Staff / superuser → admin dashboard
    if user.is_staff or user.is_superuser:
        return redirect("stores:dashboard")
    # Fallback (regular user with no role) → landing page
    return redirect("landing")


urlpatterns = [
    path("admin/", admin.site.urls),
    path("dashboard/", include("stores.urls")),
    path("chat/", web_chat_disabled, name="chat-disabled-root"),
    re_path(r"^chat/.*$", web_chat_disabled, name="chat-disabled"),
    path("vendor/", include("vendors.urls")),
    path("cart/", include("cart.urls")),
    path("escrow/", include("escrow.urls")),
    path("accounts/login/", auth_views.LoginView.as_view(template_name="registration/login.html"), name="login"),
    path("accounts/logout/", auth_views.LogoutView.as_view(next_page="/"), name="logout"),
    path("accounts/redirect/", login_redirect_view, name="login_redirect"),
    path("products/store/", store_product_page, name="product_store"),
    path("products/ai-assistant/", ai_product_page, name="product_ai"),
    path("", landing_page, name="landing"),

    path("whatsapp/", include("whatsapp.urls")),
]

# Serve uploaded media files in development
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
