import json
import random
from functools import lru_cache

from django.contrib.humanize.templatetags.humanize import intcomma
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.views.generic import RedirectView, TemplateView
from unfold.views import UnfoldModelAdminViewMixin
from order.models import OrderModel
from ticket.models import Ticket, ContactUsModel
from account.models import SecurityBreachAttemptModel
import json




def dashboard_callback(request, context):

    pending_count = OrderModel.objects.filter(status='ADMIN_PENDING').count()
    open_tickets_count = Ticket.objects.filter(status__in=['open', 'in_progress']).count()
    open_contact_us_count = ContactUsModel.objects.filter(is_reviewed=False).count()
    context.update(random_data())
    context.update({'pending_count': pending_count})
    context.update({'open_tickets_count': open_tickets_count})
    context.update({'open_contact_us_count': open_contact_us_count})
    return context


@lru_cache
def random_data():
    WEEKDAYS = [
        "Mon",
        "Tue",
        "Wed",
        "Thu",
        "Fri",
        "Sat",
        "Sun",
    ]

    positive = [[1, random.randrange(8, 28)] for i in range(1, 28)]
    negative = [[-1, -positive[i -1][1]] for i in range(1, 28)]
    average = [r[1] - random.randint(3, 5) for r in positive]
    performance_positive = [[1, random.randrange(8, 28)] for i in range(1, 28)]
    performance_negative = [[-1, -performance_positive[i - 1][1]] for i in range(1, 28)]

    response =  {
        "navigation": [
            {"title": _("Dashboard"), "link": "/", "active": True},
            {"title": _("Products"), "link": "/admin/product/productmodel/"},
            {"title": _("Orders"), "link": "/admin/order/ordermodel/"},
        ],
        "kpi": [
            {
                "title": "گوشی Iphone 16 pro",
                "metric": f"${intcomma(f'{random.uniform(1000, 9999):.02f}')}",
                "footer": mark_safe(
                    f'<strong class="text-green-700 font-semibold dark:text-green-400">+{intcomma(f"{random.uniform(1, 9):.02f}")}%</strong>&nbsp;درصد فروش کل'
                ),
                "chart": json.dumps(
                    {
                        "labels": [WEEKDAYS[day % 7] for day in range(1, 28)],
                        "datasets": [{"data": average, "borderColor": "#9333ea"}],
                    }
                ),
            },
            {
                "title": "لپ تاپ Macbook Pro M3",
                "metric": f"${intcomma(f'{random.uniform(1000, 9999):.02f}')}",
                "footer": mark_safe(
                    f'<strong class="text-green-700 font-semibold dark:text-green-400">+{intcomma(f"{random.uniform(1, 9):.02f}")}%</strong>&nbsp;درصد فروش کل'
                ),
            },
            {
                "title": "ساعت هوشمند Apple Watch 8",
                "metric": f"${intcomma(f'{random.uniform(1000, 9999):.02f}')}",
                "footer": mark_safe(
                    f'<strong class="text-green-700 font-semibold dark:text-green-400">+{intcomma(f"{random.uniform(1, 9):.02f}")}%</strong>&nbsp;درصد فروش کل'
                ),
            },
        ],
        "progress": [
{
        "title": "📱 موبایل و گوشی",
        "description": "$2,499.99",
        "value": 20,
    },
    {
        "title": "⌚ Watch and Smart Watch",
        "description": "$1,799.49",
        "value": 60,
    },
    {
        "title": "💻 Laptop and Mac Book",
        "description": "$3,499.99",
        "value": 85,
    },
    {
        "title": "📹 Camera and Video Recorder",
        "description": "$2,299.99",
        "value": 50,
    },
    {
        "title": "📷 Camera and Picture Capture",
        "description": "$1,799.00",
        "value": 10,
    },
    {
        "title": "📚 Course Sales and Learning",
        "description": "$1,299.49",
        "value": 20,
    },
    {
        "title": "📈 Ads Revenue and Marketing",
        "description": "$3,199.99",
        "value": 90,
    },
    {
        "title": "📊 Customer Retention and Engagement",
        "description": "$1,649.00",
        "value": 80,
    },
    {
        "title": "📣 Marketing ROI and Campaigns",
        "description": "$2,199.75",
        "value": 45,
    },
    {
        "title": "🤝 Affiliate Partnerships and Collaborations",
        "description": "$2,899.95",
        "value": 78,
    },
        ],
        "chart": json.dumps(
            {
                "labels": [WEEKDAYS[day % 7] for day in range(1, 28)],
                "datasets": [
                    {
                        "label": "Example 1",
                        "type": "line",
                        "data": average,
                        "borderColor": "var(--color-primary-500)",
                    },
                    {
                        "label": "Example 2",
                        "data": positive,
                        "backgroundColor": "var(--color-primary-700)",
                    },
                    {
                        "label": "Example 3",
                        "data": negative,
                        "backgroundColor": "var(--color-primary-300)",
                    },
                ],
            }
        ),
        "performance": [
            {
                "title": 'فروش ماه اخیر',
                "metric": "$1,234.56",
                "footer": mark_safe(
                    '<strong class="text-green-600 font-medium">+3.14%</strong>&nbsp;درصد فروش کل'
                ),
                "chart": json.dumps(
                    {
                        "labels": [WEEKDAYS[day % 7] for day in range(1, 28)],
                        "datasets": [
                            {
                                "data": performance_positive,
                                "borderColor": "var(--color-primary-700)",
                            }
                        ],
                    }
                ),
            },
            {
                "title": 'مخارج ماه اخیر',
                "metric": "$1,234.56",
                "footer": mark_safe(
                    '<strong class="text-green-600 font-medium">+3.14%</strong>&nbsp;درصد فروش کل'
                ),
                "chart": json.dumps(
                    {
                        "labels": [WEEKDAYS[day % 7] for day in range(1, 28)],
                        "datasets": [
                            {
                                "data": performance_negative,
                                "borderColor": "var(--color-primary-300)",
                            },
                        ],
                    }
                ),
            },
        ],
    }
    return response













# views.py
from django.contrib.auth.views import LoginView
from django.contrib.admin.sites import site as admin_site
from django.contrib import messages
from django.shortcuts import redirect
from django.views.generic import RedirectView, TemplateView
from unfold.views import UnfoldModelAdminViewMixin
from django.views import View
from django.shortcuts import render, redirect, get_object_or_404

# class FakeAdminLoginView(View):
#     template_name = "admin/fake_login.html"
#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)

#         context.update({
#             **admin_site.each_context(self.request),
#             "title": "Log in",  
#             "site_header": admin_site.site_header,
#             "form": self.get_form(),
#         })
#         return context

#     def post(self):
#         # Log the honeypot attempt
#         username = form.cleaned_data.get("username")
#         ip = self.request.META.get("REMOTE_ADDR")
#         print(f"Honeypot triggered! IP: {ip}, Username: {username}")
        
#         # Add error message and redirect back to fake login
#         messages.error(self.request, "Please enter a correct شماره تماس and password. Note that both fields may be case-sensitive.")
#         return redirect('/admin')



from django.views import View
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.admin.sites import site as admin_site

class FakeAdminLoginView(View):
    def get_unfold_context(self, request):
        """Replicates Unfold's template context"""
        return {
            "site_title": admin_site.site_title,
            "site_header": admin_site.site_header,
            "unfold": {
                "title": admin_site.site_title,
                "navigation": [],
                "theme": "light",  # Match your Unfold config
                "color_scheme": "light",  # Match your Unfold config
            }
        }

    def get_context(self, request):
        """Combine Unfold context with default admin context"""
        context = admin_site.each_context(request)
        context.update(self.get_unfold_context(request))
        return context

    def get(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip =  x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get("REMOTE_ADDR")
        print(ip)
        print(len(ip))
        print(type(ip))
        hacker, created = SecurityBreachAttemptModel.objects.get_or_create(ip_address=ip)
        return render(request, 'admin/fake_login.html', self.get_context(request))

    def post(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip =  x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get("REMOTE_ADDR")
        print(ip)
        hacker, created = SecurityBreachAttemptModel.objects.get_or_create(ip_address=ip)
        hacker.trys += 1
        hacker.save()
        messages.error(request, "لطفا شماره تماس و گذرواژه را برای یک حساب کارمند وارد کنید. توجه داشته باشید که ممکن است هر دو به کوچکی و بزرگی حروف حساس باشند.")
        return render(request, 'admin/fake_login.html', self.get_context(request))