from django.shortcuts import render, get_object_or_404, redirect
from .models import Client, Portfolio, Activity, Document
from .forms import DocumentForm, ClientForm, PortfolioForm, ActivityForm

def index(request):
    """Render the main dashboard screen."""
    # Placeholder data for the KPI cards
    kpi_data = {
        "total_clients": Client.objects.count(),
        "total_portfolios": Portfolio.objects.count(),
        "total_activities": Activity.objects.count(),
        "total_documents": Document.objects.count(),
        "pending_tasks": Activity.objects.filter(status='todo').count(),
    }

    # Fetch recent items for the dashboard widgets
    recent_clients = Client.objects.order_by('-created_at')[:5]
    recent_activities = Activity.objects.order_by('-created_at')[:5]

    context = {
        "project_name": "Finance Hub",
        "kpi_data": kpi_data,
        "recent_clients": recent_clients,
        "recent_activities": recent_activities,
    }
    return render(request, "core/index.html", context)

def client_list(request):
    """Render a page with a list of all clients."""
    clients = Client.objects.all()
    context = {
        "clients": clients,
    }
    return render(request, "core/client_list.html", context)

def client_detail(request, pk):
    """Render a page with the details of a single client."""
    client = get_object_or_404(Client, pk=pk)
    activities = client.activities.all()
    context = {
        "client": client,
        "activities": activities,
    }
    return render(request, "core/client_detail.html", context)

def portfolio_list(request):
    """Render a page with a list of all portfolios."""
    portfolios = Portfolio.objects.all()
    context = {
        "portfolios": portfolios,
    }
    return render(request, "core/portfolio_list.html", context)

def portfolio_detail(request, pk):
    """Render a page with the details of a single portfolio."""
    portfolio = get_object_or_404(Portfolio, pk=pk)
    context = {
        "portfolio": portfolio,
    }
    return render(request, "core/portfolio_detail.html", context)

def activity_list(request):
    """Render a page with a list of all activities."""
    activities = Activity.objects.all()
    context = {
        "activities": activities,
    }
    return render(request, "core/activity_list.html", context)

def activity_detail(request, pk):
    """Render a page with the details of a single activity."""
    activity = get_object_or_404(Activity, pk=pk)
    context = {
        "activity": activity,
    }
    return render(request, "core/activity_detail.html", context)

def document_list(request):
    """Render a page with a list of all documents."""
    documents = Document.objects.all()
    context = {
        "documents": documents,
    }
    return render(request, "core/document_list.html", context)

def document_detail(request, pk):
    """Render a page with the details of a single document."""
    document = get_object_or_404(Document, pk=pk)
    context = {
        "document": document,
    }
    return render(request, "core/document_detail.html", context)

def document_upload(request):
    """Handle document upload."""
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('document_list')
    else:
        form = DocumentForm()
    context = {
        'form': form,
    }
    return render(request, 'core/document_upload.html', context)


def client_create(request):
    if request.method == 'POST':
        form = ClientForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('client_list')
    else:
        form = ClientForm()
    return render(request, 'core/client_form.html', {'form': form, 'title': 'Add Client'})


def client_update(request, pk):
    client = get_object_or_404(Client, pk=pk)
    if request.method == 'POST':
        form = ClientForm(request.POST, instance=client)
        if form.is_valid():
            form.save()
            return redirect('client_detail', pk=client.pk)
    else:
        form = ClientForm(instance=client)
    return render(request, 'core/client_form.html', {'form': form, 'title': 'Edit Client'})


def client_delete(request, pk):
    client = get_object_or_404(Client, pk=pk)
    if request.method == 'POST':
        client.delete()
        return redirect('client_list')
    return render(request, 'core/client_confirm_delete.html', {'object': client})


def portfolio_create(request):
    if request.method == 'POST':
        form = PortfolioForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('portfolio_list')
    else:
        form = PortfolioForm()
    return render(request, 'core/portfolio_form.html', {'form': form, 'title': 'Add Portfolio'})


def portfolio_update(request, pk):
    portfolio = get_object_or_404(Portfolio, pk=pk)
    if request.method == 'POST':
        form = PortfolioForm(request.POST, instance=portfolio)
        if form.is_valid():
            form.save()
            return redirect('portfolio_detail', pk=portfolio.pk)
    else:
        form = PortfolioForm(instance=portfolio)
    return render(request, 'core/portfolio_form.html', {'form': form, 'title': 'Edit Portfolio'})


def portfolio_delete(request, pk):
    portfolio = get_object_or_404(Portfolio, pk=pk)
    if request.method == 'POST':
        portfolio.delete()
        return redirect('portfolio_list')
    return render(request, 'core/portfolio_confirm_delete.html', {'object': portfolio})


def activity_create(request):
    if request.method == 'POST':
        form = ActivityForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('activity_list')
    else:
        form = ActivityForm()
    return render(request, 'core/activity_form.html', {'form': form, 'title': 'Add Activity'})


def activity_update(request, pk):
    activity = get_object_or_404(Activity, pk=pk)
    if request.method == 'POST':
        form = ActivityForm(request.POST, instance=activity)
        if form.is_valid():
            form.save()
            return redirect('activity_detail', pk=activity.pk)
    else:
        form = ActivityForm(instance=activity)
    return render(request, 'core/activity_form.html', {'form': form, 'title': 'Edit Activity'})


def activity_delete(request, pk):
    activity = get_object_or_404(Activity, pk=pk)
    if request.method == 'POST':
        activity.delete()
        return redirect('activity_list')
    return render(request, 'core/activity_confirm_delete.html', {'object': activity})

def document_delete(request, pk):
    document = get_object_or_404(Document, pk=pk)
    if request.method == 'POST':
        document.delete()
        return redirect('document_list')
    return render(request, 'core/document_confirm_delete.html', {'object': document})
