<?php

namespace App\Livewire\Google;

use Livewire\Component;
use App\Services\GoogleAnalyticsService;
use App\Services\GoogleSearchConsoleService;
use Illuminate\Support\Facades\Log;
use Livewire\Attributes\Layout;

#[Layout('components.admin-layout')]
class AnalyticsDashboard extends Component
{
    public $activeTab = 'overview';
    public $daysFilter = 30;
    
    public $realtimeData = [];
    public $trafficData = [];
    public $trafficChartData = [];
    public $geoData = [];
    public $deviceData = [];
    public $topPages = [];
    public $searchAnalytics = [];
    public $topQueries = [];
    public $searchTopPages = [];
    public $isConfigured = false;
    public $loading = true;
    public $tabLoading = false;
    public $error = null;

    protected $googleAnalytics;

    public function boot(GoogleAnalyticsService $googleAnalytics)
    {
        $this->googleAnalytics = $googleAnalytics;
    }

    public function mount()
    {
        $this->loadOverviewData();
    }

    public function loadOverviewData()
    {
        $this->loading = true;
        $this->error = null;

        try {
            $this->isConfigured = $this->googleAnalytics->isConfigured();
            
            // Load essential data for overview
            $this->realtimeData = $this->googleAnalytics->getRealTimeData() ?? [];
            $this->trafficChartData = $this->googleAnalytics->getTrafficChartData($this->daysFilter) ?? [];
            $this->geoData = $this->googleAnalytics->getGeoData($this->daysFilter) ?? [];
            $this->deviceData = $this->googleAnalytics->getDeviceData($this->daysFilter) ?? [];
            $this->topPages = $this->googleAnalytics->getTopPages(7) ?? []; // Last 7 days for overview

        } catch (\Exception $e) {
            $this->error = 'Failed to load analytics data: ' . $e->getMessage();
            Log::error('Analytics Dashboard Error: ' . $e->getMessage());
        } finally {
            $this->loading = false;
            $this->tabLoading = false;
        }
    }

    public function switchTab($tab)
    {
        $this->activeTab = $tab;
        $this->tabLoading = true;

        // Load tab-specific data only when needed
        if ($tab === 'analytics') {
            $this->loadAnalyticsData();
        } elseif ($tab === 'search') {
            $this->loadSearchData();
        } else {
            $this->tabLoading = false;
        }
    }

    public function loadAnalyticsData()
    {
        try {
            $this->trafficData = $this->googleAnalytics->getTrafficData($this->daysFilter) ?? [];
        } catch (\Exception $e) {
            Log::error('Analytics Tab Error: ' . $e->getMessage());
        } finally {
            $this->tabLoading = false;
        }
    }

    public function loadSearchData()
    {
        try {
            // Uncomment when Search Console is ready
            $this->searchAnalytics = $this->googleSearchConsole->getSearchAnalytics($this->daysFilter) ?? [];
            $this->topQueries = $this->googleSearchConsole->getTopQueries($this->daysFilter) ?? [];
            $this->searchTopPages = $this->googleSearchConsole->getTopPages($this->daysFilter) ?? [];
        } catch (\Exception $e) {
            Log::error('Search Console Tab Error: ' . $e->getMessage());
        } finally {
            $this->tabLoading = false;
        }
    }

    public function updatedDaysFilter()
    {
        $this->loading = true;
        $this->loadOverviewData();
    }

    public function refreshData()
    {
        cache()->forget('ga_realtime');
        cache()->forget("ga_traffic_{$this->daysFilter}");
        cache()->forget("ga_traffic_chart_{$this->daysFilter}");
        cache()->forget("ga_geo_{$this->daysFilter}");
        cache()->forget("ga_devices_{$this->daysFilter}");
        cache()->forget("ga_toppages_7");
        
        $this->loading = true;
        $this->loadOverviewData();
        $this->dispatch('notify', message: 'Data refreshed successfully!', type: 'success');
    }

    // Computed properties
    public function getTotalSessionsProperty()
    {
        return !empty($this->trafficChartData['sessions']) ? 
            array_sum($this->trafficChartData['sessions']) : 0;
    }

    public function getTotalUsersProperty()
    {
        return !empty($this->trafficChartData['users']) ? 
            array_sum($this->trafficChartData['users']) : 0;
    }

    public function getActiveUsersProperty()
    {
        return $this->realtimeData['activeUsers'] ?? 0;
    }

    public function getTopCountriesProperty()
    {
        if (empty($this->geoData)) return [];
        
        $countries = [];
        foreach ($this->geoData as $geo) {
            $country = $geo['country'];
            if (!isset($countries[$country])) {
                $countries[$country] = 0;
            }
            $countries[$country] += $geo['sessions'];
        }
        
        arsort($countries);
        return array_slice($countries, 0, 5, true);
    }

    public function render()
    {
        return view('livewire.google.analytics-dashboard');
    }
}