<?php

namespace App\Filament\Widgets;

use App\Filament\Concerns\CachesWidgetData;
use App\Filament\Pages\FinalDecision;
use App\Filament\Resources\AdoptionApplications\AdoptionApplicationResource;
use App\Filament\Resources\AssistanceApplications\AssistanceApplicationResource;
use App\Filament\Resources\FosteringApplications\FosteringApplicationResource;
use App\Filament\Resources\Interviews\InterviewResource;
use App\Filament\Resources\Pets\PetResource;
use App\Filament\Resources\TicketPurchaseRequests\TicketPurchaseRequestResource;
use App\Models\AdoptionApplication;
use App\Models\AssistanceApplication;
use App\Models\FosteringApplication;
use App\Models\Interview;
use App\Models\Pet;
use App\Models\Setting;
use App\Models\TicketPurchaseRequest;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class KeyAlertsWidget extends StatsOverviewWidget
{
    use CachesWidgetData;

    protected ?string $heading = 'Key Alerts';

    protected function getStats(): array
    {
        $stats = [];

        $requiresInterviewCount = $this->cached('requires_interview', fn () => AdoptionApplication::query()
            ->where('status', 'submitted')
            ->count());

        if ($requiresInterviewCount > 0) {
            $stats[] = Stat::make('Awaiting Interview', $requiresInterviewCount)
                ->description('Applications awaiting interview scheduling')
                ->descriptionIcon('heroicon-m-calendar')
                ->color('danger')
                ->url(AdoptionApplicationResource::getUrl('index', ['tab' => 'submitted']));
        }

        $overdueInterviewsCount = $this->cached('overdue_interviews', fn () => Interview::query()
            ->whereNull('completed_at')
            ->where('scheduled_at', '<', now())
            ->count());

        if ($overdueInterviewsCount > 0) {
            $stats[] = Stat::make('Overdue Interviews', $overdueInterviewsCount)
                ->description('Interviews past their scheduled time')
                ->descriptionIcon('heroicon-m-exclamation-triangle')
                ->color('danger')
                ->url(InterviewResource::getUrl('index'));
        }

        $requiresFinalDecisionCount = $this->cached('requires_final_decision', fn () => AdoptionApplication::query()
            ->where('status', 'under_review')
            ->count());

        if ($requiresFinalDecisionCount > 0) {
            $stats[] = Stat::make('Applications Under Review', $requiresFinalDecisionCount)
                ->description('Applications needing approval or rejection')
                ->descriptionIcon('heroicon-m-check-circle')
                ->color('danger')
                ->url(FinalDecision::getUrl());
        }

        // Only show pending fostering applications if fostering is enabled
        if (Setting::get('enable_foster_applications', true)) {
            $pendingFosteringCount = $this->cached('pending_fostering', fn () => FosteringApplication::query()
                ->where('status', 'submitted')
                ->count());

            if ($pendingFosteringCount > 0) {
                $stats[] = Stat::make('Pending Fostering Applications', $pendingFosteringCount)
                    ->description('Fostering applications awaiting review')
                    ->descriptionIcon('heroicon-m-home')
                    ->color('danger')
                    ->url(FosteringApplicationResource::getUrl('index', ['tab' => 'submitted']));
            }
        }

        // Only show pending assistance applications if assistance is enabled
        if (Setting::get('enable_assistance_applications', true)) {
            $pendingAssistanceCount = $this->cached('pending_assistance', fn () => AssistanceApplication::query()
                ->where('status', 'submitted')
                ->count());

            if ($pendingAssistanceCount > 0) {
                $stats[] = Stat::make('Pending Assistance Applications', $pendingAssistanceCount)
                    ->description('Assistance applications awaiting review')
                    ->descriptionIcon('heroicon-m-heart')
                    ->color('danger')
                    ->url(AssistanceApplicationResource::getUrl('index', ['tab' => 'submitted']));
            }
        }

        // Only show pending ticket requests if 50/50 draws are enabled
        if (Setting::get('enable_draws', false)) {
            $pendingTicketRequestsCount = $this->cached('pending_tickets', fn () => TicketPurchaseRequest::query()
                ->where('status', 'pending')
                ->count());

            if ($pendingTicketRequestsCount > 0) {
                $stats[] = Stat::make('Pending Ticket Requests', $pendingTicketRequestsCount)
                    ->description('Ticket purchases awaiting processing')
                    ->descriptionIcon('heroicon-m-ticket')
                    ->color('danger')
                    ->url(TicketPurchaseRequestResource::getUrl('index'));
            }
        }

        if (Setting::get('require_application_for_manual_adoption', false)) {
            $needsBackfillCount = $this->cached('needs_backfill', fn () => Pet::query()
                ->where('status', 'adopted')
                ->where('adoption_date', '>=', now()->subMonth())
                ->whereNotExists(function ($query) {
                    $query->selectRaw(1)
                        ->from('adoption_applications')
                        ->where(function ($q) {
                            $q->whereColumn('adoption_applications.pet_id', 'pets.id')
                                ->orWhereColumn('adoption_applications.second_pet_id', 'pets.id');
                        })
                        ->whereNotIn('adoption_applications.status', ['cancelled', 'rejected', 'archived']);
                })
                ->count());

            if ($needsBackfillCount > 0) {
                $stats[] = Stat::make('Adopted Without Application', $needsBackfillCount)
                    ->description('Adopted pets with no linked application (last 30 days)')
                    ->descriptionIcon('heroicon-m-document-text')
                    ->color('warning')
                    ->url(PetResource::getUrl('index', ['tab' => 'needs_backfill']));
            }
        }

        return $stats;
    }
}
