from datetime import timedelta

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Count, Exists, OuterRef, Q
from django.db.models.functions import TruncDate
from django.shortcuts import render
from django.utils import timezone

from common.utils import is_supervisor
from contacts.models import ContactPerson
from farmerapp.models import Farmer
from pricing.models import UnloadingPointPrice
from .models import Interaction

WEEKDAYS = ['Понеділок', 'Вівторок', 'Середа', 'Четвер', "П'ятниця", 'Субота', 'Неділя']
MONTHS = ['січня', 'лютого', 'березня', 'квітня', 'травня', 'червня',
          'липня', 'серпня', 'вересня', 'жовтня', 'листопада', 'грудня']
UPCOMING_DAYS = 7
CHART_DAYS = 30
STATUS_ORDER = ['unprocessed', 'cold', 'warm', 'hot']


def human_date(dt):
    return f"{WEEKDAYS[dt.weekday()]}, {dt.day} {MONTHS[dt.month - 1]}"


def greeting(dt):
    if dt.hour < 12:
        return 'Доброго ранку'
    if dt.hour < 18:
        return 'Добрий день'
    return 'Добрий вечір'


def open_tasks():
    """Взаємодії із запланованим наступним контактом, після яких ще не було нової взаємодії з фермером."""
    newer = Interaction.objects.filter(farmer=OuterRef('farmer'), date__gt=OuterRef('date'))
    return Interaction.objects.filter(next_interaction_date__isnull=False).filter(~Exists(newer))


def responsible_q(user):
    # Відповідальний — той, кому призначено, інакше автор взаємодії
    return Q(assigned_to=user) | Q(assigned_to__isnull=True, user=user)


def tasks_of(user):
    return open_tasks().filter(responsible_q(user))


def farmers_of(user):
    return Farmer.objects.filter(pk__in=Interaction.objects.filter(responsible_q(user)).values('farmer'))


def transfer_work(old, new):
    """Передає все, за що відповідає old. Автор взаємодій не змінюється, тож історія і статистика лишаються чесними."""
    tasks, farmers = tasks_of(old).count(), farmers_of(old).count()
    interactions = Interaction.objects.filter(responsible_q(old))
    # Нагадування могло піти лише старому менеджеру: новий має отримати своє
    pending = list(tasks_of(old).filter(next_interaction_date__gt=timezone.now()).values_list('pk', flat=True))
    Interaction.objects.filter(pk__in=pending).update(reminder_sent_at=None)
    interactions.update(assigned_to=new)
    return tasks, farmers


def day_bounds():
    today_start = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)
    return today_start, today_start + timedelta(days=1)


def split_agenda(tasks, upcoming_days=UPCOMING_DAYS):
    today_start, tomorrow_start = day_bounds()
    tasks = tasks.select_related('farmer', 'contact_person', 'user', 'assigned_to').order_by('next_interaction_date')
    upcoming = tasks.filter(next_interaction_date__gte=tomorrow_start)
    if upcoming_days:
        upcoming = upcoming.filter(next_interaction_date__lt=tomorrow_start + timedelta(days=upcoming_days))
    return {
        'overdue': list(tasks.filter(next_interaction_date__lt=today_start)),
        'today': list(tasks.filter(next_interaction_date__gte=today_start, next_interaction_date__lt=tomorrow_start)),
        'upcoming': list(upcoming),
    }


def daily_counts(interactions):
    """Кількість взаємодій по днях за останні CHART_DAYS днів, включно з днями без взаємодій."""
    today = timezone.localdate()
    start = today - timedelta(days=CHART_DAYS - 1)
    counts = dict(
        interactions.filter(date__date__gte=start)
        .annotate(day=TruncDate('date', tzinfo=timezone.get_current_timezone()))
        .values_list('day').annotate(n=Count('id')).values_list('day', 'n')
    )
    days = [start + timedelta(days=i) for i in range(CHART_DAYS)]
    return {
        'labels': [d.strftime('%d.%m') for d in days],
        'values': [counts.get(d, 0) for d in days],
    }


def status_funnel(farmers):
    names = dict(Farmer.CLIENT_STATUS_CHOICES)
    counts = dict(farmers.values_list('client_status').annotate(n=Count('id')).values_list('client_status', 'n'))
    return [{'status': s, 'label': names[s], 'count': counts.get(s, 0)} for s in STATUS_ORDER]


def recent_prices(limit=8):
    return (UnloadingPointPrice.objects.filter(status='active')
            .select_related('culture', 'unloading_point__region')
            .order_by('-last_updated')[:limit])


def team_rows(team):
    today_start, tomorrow_start = day_bounds()
    week_ago = timezone.now() - timedelta(days=7)
    month_ago = timezone.now() - timedelta(days=30)
    rows = []
    for member in team:
        tasks = tasks_of(member)
        rows.append({
            'user': member,
            'today': tasks.filter(next_interaction_date__gte=today_start, next_interaction_date__lt=tomorrow_start).count(),
            'overdue': tasks.filter(next_interaction_date__lt=today_start).count(),
            'week': member.interactions.filter(date__gte=week_ago).count(),
            'month': member.interactions.filter(date__gte=month_ago).count(),
        })
    return sorted(rows, key=lambda r: (-r['overdue'], -r['today'], r['user'].get_full_name()))


@login_required
def dashboard(request):
    user = request.user
    supervisor = is_supervisor(user)
    week_ago = timezone.now() - timedelta(days=7)

    agenda = split_agenda(tasks_of(user))
    my_interactions = Interaction.objects.filter(user=user)
    my_farmers = Farmer.objects.filter(Q(interactions__user=user) | Q(interactions__assigned_to=user)).distinct()

    now = timezone.localtime()
    context = {
        'is_supervisor': supervisor,
        'today_label': human_date(now),
        'greeting': greeting(now),
        'agenda': agenda,
        'week_interactions': my_interactions.filter(date__gte=week_ago).count(),
        'hot_clients': my_farmers.filter(client_status='hot').count(),
        'funnel': status_funnel(my_farmers),
        'chart': daily_counts(my_interactions),
        'birthdays': ContactPerson.objects.filter(birth_date__month=timezone.localdate().month,
                                                  birth_date__day=timezone.localdate().day)[:10],
        'recent_prices': recent_prices(),
    }

    if supervisor:
        team = User.objects.filter(groups__name__in=['Managers', 'Supervisors'], is_active=True).distinct()
        all_tasks = open_tasks()
        today_start, _ = day_bounds()
        context.update({
            'team': team_rows(team),
            'team_overdue': all_tasks.filter(next_interaction_date__lt=today_start).count(),
            'team_week_interactions': Interaction.objects.filter(date__gte=week_ago).count(),
            'team_funnel': status_funnel(Farmer.objects.all()),
            'team_chart': daily_counts(Interaction.objects.all()),
        })

    return render(request, 'dashboard.html', context)
