<?php

namespace App\Http\Controllers;

use App\Enums\DeclarationStatus;
use App\Models\Declaration;
use App\Models\Workspace;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    /**
     * Display the dashboard with assigned declarations and notifications.
     */
    public function __invoke(Request $request): Response
    {
        $user = $request->user();
        $workspaceId = $request->session()->get('current_workspace_id');
        $workspace = $workspaceId ? Workspace::query()->find($workspaceId) : null;

        $assignedDeclarations = [];
        $notifications = [];

        if ($workspace && $user) {
            $assignedDeclarations = $workspace->declarations()
                ->where('assigned_to', $user->id)
                ->whereNotIn('status', [DeclarationStatus::Ferme])
                ->with('client:id,company_name')
                ->orderByRaw('CASE WHEN due_date IS NULL THEN 1 ELSE 0 END, due_date ASC')
                ->limit(50)
                ->get()
                ->map(fn (Declaration $f) => [
                    'id' => $f->id,
                    'title' => $f->title,
                    'type' => $f->type->value,
                    'client_name' => $f->client->company_name,
                    'status' => $f->status->value,
                    'due_date' => $f->due_date?->format('Y-m-d'),
                    'priority' => $f->priority?->value,
                    'showUrl' => route('declarations.show', $f),
                ])
                ->all();

            $overdue = $workspace->declarations()
                ->where('assigned_to', $user->id)
                ->where('due_date', '<', now()->startOfDay())
                ->whereNotIn('status', [DeclarationStatus::Ferme])
                ->with('client:id,company_name')
                ->orderBy('due_date')
                ->limit(10)
                ->get()
                ->map(fn (Declaration $f) => [
                    'id' => $f->id,
                    'title' => $f->title,
                    'client_name' => $f->client->company_name,
                    'due_date' => $f->due_date?->format('Y-m-d'),
                    'showUrl' => route('declarations.show', $f),
                ])
                ->all();

            $dueSoon = $workspace->declarations()
                ->where('assigned_to', $user->id)
                ->whereBetween('due_date', [now()->startOfDay(), now()->addDays(7)->endOfDay()])
                ->whereNotIn('status', [DeclarationStatus::Ferme])
                ->with('client:id,company_name')
                ->orderBy('due_date')
                ->limit(10)
                ->get()
                ->map(fn (Declaration $f) => [
                    'id' => $f->id,
                    'title' => $f->title,
                    'client_name' => $f->client->company_name,
                    'due_date' => $f->due_date?->format('Y-m-d'),
                    'showUrl' => route('declarations.show', $f),
                ])
                ->all();

            $documentsReceived = $workspace->declarations()
                ->where('assigned_to', $user->id)
                ->where('status', DeclarationStatus::EnCours)
                ->with('client:id,company_name')
                ->orderBy('updated_at', 'desc')
                ->limit(10)
                ->get()
                ->map(fn (Declaration $f) => [
                    'id' => $f->id,
                    'title' => $f->title,
                    'client_name' => $f->client->company_name,
                    'showUrl' => route('declarations.show', $f),
                ])
                ->all();

            $awaitingValidation = $workspace->declarations()
                ->where('assigned_to', $user->id)
                ->where('status', DeclarationStatus::EnAttenteClient)
                ->with('client:id,company_name')
                ->orderBy('confirmation_requested_at', 'desc')
                ->limit(10)
                ->get()
                ->map(fn (Declaration $f) => [
                    'id' => $f->id,
                    'title' => $f->title,
                    'client_name' => $f->client->company_name,
                    'showUrl' => route('declarations.show', $f),
                ])
                ->all();

            $notifications = [
                'overdue' => $overdue,
                'due_soon' => $dueSoon,
                'documents_received' => $documentsReceived,
                'awaiting_validation' => $awaitingValidation,
            ];
        }

        return Inertia::render('Dashboard', [
            'assignedDeclarations' => $assignedDeclarations,
            'notifications' => $notifications,
            'workspaceName' => $workspace?->name ?? null,
            'declarationsUrl' => $workspace ? route('declarations.index') : null,
            'clientsUrl' => $workspace ? route('clients.index') : null,
        ]);
    }
}
