<?php

namespace App\Filament\Pages;

use App\Models\AiUsageLog;
use App\Models\TravelAgent;
use Filament\Pages\Page;
use Illuminate\Support\Facades\DB;
use BackedEnum;
use UnitEnum;

class AiUsageOverview extends Page
{
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';

    protected string $view = 'filament.pages.ai-usage-overview';

    protected static UnitEnum|string|null $navigationGroup = 'Analytics';

    protected static ?string $navigationLabel = 'AI Usage Overview';

    protected static ?int $navigationSort = 1;

    // Computed properties for the view
    public function getTotalRequestsProperty()
    {
        return number_format(AiUsageLog::count());
    }

    public function getTotalWordsProperty()
    {
        return number_format(AiUsageLog::sum('word_count'));
    }

    public function getFreeCreditsUsedProperty()
    {
        return number_format(AiUsageLog::where('used_free_credit', true)->count());
    }

    public function getTotalCostProperty()
    {
        return '₹' . number_format(AiUsageLog::sum('cost'), 2);
    }

    public function getAvgWordsPerRequestProperty()
    {
        return number_format(AiUsageLog::avg('word_count') ?? 0, 0);
    }

    public function getTodaysRequestsProperty()
    {
        return number_format(AiUsageLog::whereDate('created_at', today())->count());
    }

    public function getAvgCostPerRequestProperty()
    {
        return '₹' . number_format(AiUsageLog::avg('cost') ?? 0, 2);
    }

    public function getTotalAgentsProperty()
    {
        return number_format(TravelAgent::count());
    }

    // Helper methods for the view
    public function getTopAgentsByUsage()
    {
        return AiUsageLog::select('travel_agent_id', DB::raw('SUM(word_count) as total_words'))
            ->with('travelAgent')
            ->groupBy('travel_agent_id')
            ->orderBy('total_words', 'desc')
            ->limit(10)
            ->get();
    }

    public function getDailyUsageTrend()
    {
        return AiUsageLog::selectRaw('DATE(created_at) as date, COUNT(*) as requests, SUM(word_count) as words')
            ->where('created_at', '>=', now()->subDays(30))
            ->groupBy('date')
            ->orderBy('date')
            ->get();
    }

    public function getUsageByHour()
    {
        return AiUsageLog::selectRaw('HOUR(created_at) as hour, COUNT(*) as requests')
            ->groupBy('hour')
            ->orderBy('hour')
            ->get();
    }
}