import hashlib
from functools import wraps

import openpyxl
from dal import autocomplete
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.core.cache import cache
from django.template.loader import render_to_string
from django.views.decorators.http import require_POST

from common.utils import is_logist, is_supervisor, is_manager, text_search_q
from farmerapp.models import District, Region
from .calculator import calculate
from .distances import DistanceError, search_settlements
from .forms import (CostCalculatorForm, QuickFarmerForm, SupervisorUnloadingPointForm,
                    TransportTariffFormSet, UnloadingPointPriceFormSet)
from .models import TariffImport, TransportTariff, UnloadingPoint, UnloadingPointImport
from .point_import import apply_plan, export_rows, parse_points
from .sheets import SheetImportError, read_google_sheet, read_upload
from .tariff_import import find_gaps, parse_rows, replace_tariffs


def can_manage_prices(user):
    return user is not None and user.is_authenticated and (user.is_staff or is_supervisor(user))


def can_edit_tariffs(user):
    return can_manage_prices(user) or (user is not None and is_logist(user))


def access_required(check):
    def decorator(view):
        @wraps(view)
        @login_required
        def wrapper(request, *args, **kwargs):
            if not check(request.user):
                return HttpResponseForbidden("Ви не маєте доступу до цієї сторінки.")
            return view(request, *args, **kwargs)
        return wrapper
    return decorator


supervisor_required = access_required(can_manage_prices)
tariff_editor_required = access_required(can_edit_tariffs)


class DistrictAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        if not self.request.user.is_authenticated:
            return District.objects.none()

        qs = District.objects.order_by('name')

        region_id = self.forwarded.get('region', None)
        if region_id:
            qs = qs.filter(region_id=region_id)

        if self.q:
            qs = qs.filter(text_search_q(['name'], self.q))

        return qs


@tariff_editor_required
def tariff_list(request):
    queryset = TransportTariff.objects.order_by('km_from')

    if request.method == 'POST':
        formset = TransportTariffFormSet(request.POST, queryset=queryset)
        if formset.is_valid():
            formset.save()
            messages.success(request, 'Тарифи збережено.')
            return redirect('pricing:tariff_list')
    else:
        formset = TransportTariffFormSet(queryset=queryset)

    return render(request, 'pricing/tariff_list.html', tariff_page_context(formset))


def tariff_page_context(formset, import_errors=(), sheet_url=None):
    last_import = TariffImport.objects.select_related('user').first()
    if sheet_url is None:
        last_sheet = TariffImport.objects.exclude(sheet_url='').first()
        sheet_url = last_sheet.sheet_url if last_sheet else ''
    return {'formset': formset, 'import_errors': import_errors, 'sheet_url': sheet_url, 'last_import': last_import}


@tariff_editor_required
@require_POST
def tariff_import(request):
    """Повністю замінює таблицю тарифів на ту, що в файлі чи Google Таблиці."""
    sheet_url = request.POST.get('sheet_url', '').strip()
    try:
        rows, source, sheet_url = read_import_source(request)
        tariffs = parse_rows(rows)
    except SheetImportError as e:
        formset = TransportTariffFormSet(queryset=TransportTariff.objects.order_by('km_from'))
        return render(request, 'pricing/tariff_list.html',
                      tariff_page_context(formset, e.errors, sheet_url or None), status=400)

    old_count = replace_tariffs(tariffs)
    TariffImport.objects.create(user=request.user, source=source[:500], sheet_url=sheet_url,
                                old_count=old_count, new_count=len(tariffs))
    messages.success(request, f'Таблицю тарифів замінено: було {old_count} рядків, тепер {len(tariffs)}.')
    gaps = find_gaps(tariffs)
    if gaps:
        messages.warning(request, 'У таблиці є проміжки без тарифу: ' +
                         ', '.join(f'{a}–{b} км' for a, b in gaps) + '. Для цих відстаней калькулятор не порахує перевезення.')
    return redirect('pricing:tariff_list')


@tariff_editor_required
def tariff_export(request):
    rows = [['Кілометраж від', 'До', 'Ціна, грн за т/км']]
    rows += [[t.km_from, t.km_to, t.price_per_ton_km] for t in TransportTariff.objects.order_by('km_from')]
    return xlsx_response(rows, 'Тарифи', 'tariffs.xlsx')


def read_import_source(request):
    """Рядки таблиці з завантаженого файлу або Google Таблиці: (рядки, джерело, посилання)."""
    sheet_url = request.POST.get('sheet_url', '').strip()
    upload = request.FILES.get('file')
    if upload:
        return read_upload(upload), f'Файл {upload.name}', ''
    if sheet_url:
        return read_google_sheet(sheet_url), 'Google Таблиця', sheet_url
    raise SheetImportError('Оберіть файл або вставте посилання на Google Таблицю.')


def xlsx_response(rows, title, filename):
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = title
    for row in rows:
        sheet.append(row)
    for cells in sheet.columns:
        width = max(len(str(c.value or '')) for c in cells)
        sheet.column_dimensions[cells[0].column_letter].width = min(max(width + 2, 12), 50)
    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename="{filename}"'
    wb.save(response)
    return response


@supervisor_required
def unloading_point_list(request):
    return render(request, 'pricing/unloading_point_list.html', unloading_point_list_context(request))


def unloading_point_list_context(request, import_errors=(), sheet_url=None):
    points = UnloadingPoint.objects.select_related('region', 'district').prefetch_related('prices__culture')

    region_id = request.GET.get('region', '')
    if region_id:
        points = points.filter(region_id=region_id)

    q = request.GET.get('q', '').strip()
    if q:
        points = points.filter(
            text_search_q(['name', 'settlement', 'terminal', 'prices__culture__cultureable_name'], q)
        ).distinct()

    context = {
        'points': points,
        'regions': Region.objects.order_by('name'),
        'selected_region': region_id,
        'q': q,
        'import_errors': import_errors,
        'last_import': UnloadingPointImport.objects.select_related('user').first(),
    }
    if sheet_url is None:
        last_sheet = UnloadingPointImport.objects.exclude(sheet_url='').first()
        sheet_url = last_sheet.sheet_url if last_sheet else ''
    context['sheet_url'] = sheet_url
    return context


@supervisor_required
@require_POST
def unloading_point_import(request):
    """Приводить місця розвантаження та їхні ціни до стану таблиці; зведена таблиця місць не видаляє."""
    sheet_url = request.POST.get('sheet_url', '').strip()
    try:
        rows, source, sheet_url = read_import_source(request)
        plan = parse_points(rows)
    except SheetImportError as e:
        return render(request, 'pricing/unloading_point_list.html',
                      unloading_point_list_context(request, e.errors, sheet_url or None), status=400)

    result = apply_plan(plan)
    UnloadingPointImport.objects.create(
        user=request.user, source=source[:500], sheet_url=sheet_url, created=result.created,
        updated=result.updated, deleted=result.deleted, deleted_names='\n'.join(result.deleted_names))
    messages.success(request, f'Місця розвантаження оновлено з таблиці: {len(plan.points)} місць, '
                              f'{plan.price_count} цін. Додано {result.created}, змінено {result.updated}, '
                              f'без змін {result.unchanged}, видалено {result.deleted}.')
    if result.deleted_names:
        messages.warning(request, 'Видалено місця, яких немає в таблиці: ' + ', '.join(result.deleted_names) + '.')
    if result.missing_names:
        messages.warning(request, 'Цих місць немає в таблиці, вони залишилися без змін: '
                                  + ', '.join(result.missing_names) + '.')
    return redirect('pricing:unloading_point_list')


@supervisor_required
def unloading_point_export(request):
    return xlsx_response(export_rows(), 'Місця розвантаження', 'unloading-points.xlsx')


@supervisor_required
def unloading_point_edit(request, point_id=None):
    point = get_object_or_404(UnloadingPoint, id=point_id) if point_id else None

    if request.method == 'POST':
        form = SupervisorUnloadingPointForm(request.POST, instance=point)
        formset = UnloadingPointPriceFormSet(request.POST, instance=point or UnloadingPoint(), prefix='prices')
        if form.is_valid() and formset.is_valid():
            with transaction.atomic():
                point = form.save()
                formset.instance = point
                formset.save()
            messages.success(request, f'Місце розвантаження «{point.name}» збережено.')
            return redirect('pricing:unloading_point_list')
    else:
        form = SupervisorUnloadingPointForm(instance=point)
        formset = UnloadingPointPriceFormSet(instance=point or UnloadingPoint(), prefix='prices')

    return render(request, 'pricing/unloading_point_form.html', {'form': form, 'formset': formset, 'point': point})


@supervisor_required
@require_POST
def unloading_point_delete(request, point_id):
    point = get_object_or_404(UnloadingPoint, id=point_id)
    name = point.name
    point.delete()
    messages.success(request, f'Місце розвантаження «{name}» видалено.')
    return redirect('pricing:unloading_point_list')


def can_use_calculator(user):
    return user.is_authenticated and (user.is_staff or is_supervisor(user) or is_manager(user))


def calculator_access(view):
    @wraps(view)
    @login_required
    def wrapper(request, *args, **kwargs):
        if not can_use_calculator(request.user):
            return HttpResponseForbidden("Ви не маєте доступу до цієї сторінки.")
        return view(request, *args, **kwargs)
    return wrapper


@calculator_access
def cost_calculator(request):
    if 'culture' in request.GET:
        form = CostCalculatorForm(request.GET)
    else:
        # Перехід з картки фермера: господарство вже обране, решту вводить користувач
        form = CostCalculatorForm(initial={'farmer': request.GET.get('farmer')})
    calculation, origin_label = None, ''
    if form.is_bound and form.is_valid():
        data = form.cleaned_data
        origin, origin_label = form.origin
        # Кеш відстаней господарства потрібен лише тоді, коли везуть з його адреси
        farmer = None if data['settlement'] else data['farmer']
        calculation = calculate(origin, data['culture'], data['price'], data['tons'], farmer=farmer)

    context = {
        'form': form,
        'calculation': calculation,
        'origin_label': origin_label,
        'farmer_form': QuickFarmerForm(),
        'google_configured': bool(settings.GOOGLE_MAPS_API_KEY),
    }
    return render(request, 'pricing/cost_calculator.html', context)


@calculator_access
def settlement_autocomplete(request):
    """Варіанти для Select2: населені пункти з Google і, останнім, введений текст як є."""
    q = ' '.join(request.GET.get('q', '').split())
    if len(q) < 2:
        return JsonResponse({'results': []})

    cache_key = 'pricing:settlements:' + hashlib.md5(q.lower().encode()).hexdigest()
    places = cache.get(cache_key)
    if places is None:
        try:
            places = search_settlements(q)
            cache.set(cache_key, places, 60 * 60 * 24)
        except DistanceError:
            # Без Google лишається ручне введення: Routes API сам знайде адресу за текстом
            places = []

    results = [{'id': f'{place_id}|{name}', 'text': name} for place_id, name in places]
    results.append({'id': f'|{q}', 'text': f'{q} (як введено)'})
    return JsonResponse({'results': results, 'pagination': {'more': False}})


@calculator_access
@require_POST
def quick_farmer_create(request):
    form = QuickFarmerForm(request.POST)
    if form.is_valid():
        farmer = form.save()
        return JsonResponse({'id': farmer.id, 'text': f'{farmer.name} ({farmer.region})'})
    html = render_to_string('pricing/_quick_farmer_form.html', {'farmer_form': form}, request=request)
    return JsonResponse({'html': html}, status=400)
