<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\Lead;
use App\Models\Product;
use App\Models\Category;
use App\Models\Blog;
use App\Models\Banner;
use App\Models\Brand;
use App\Models\Page;
use App\Models\User;
use Carbon\Carbon;

#[Layout('components.admin-layout')]
class Dashboard extends Component
{
    public $stats = [];
    public $recentLeads = [];
    public $topProducts = [];

    public function mount()
    {
        $this->loadStats();
        $this->loadRecentLeads();
        $this->loadTopProducts();
    }

    public function loadStats()
    {
        $totalLeads = Lead::count();
        $totalProducts = Product::count();
        $totalCategories = Category::count();
        $totalBlogs = Blog::count();
        $totalBanners = Banner::count();
        $totalBrands = Brand::count();
        $totalPages = Page::count();
        $totalUsers = User::count();

        // Today's leads
        $todayLeads = Lead::whereDate('created_at', Carbon::today())->count();
        
        // Yesterday's leads for comparison
        $yesterdayLeads = Lead::whereDate('created_at', Carbon::yesterday())->count();
        $leadsChange = $yesterdayLeads > 0 ? 
            round((($todayLeads - $yesterdayLeads) / $yesterdayLeads) * 100, 1) : 
            ($todayLeads > 0 ? 100 : 0);

        // Products change (last 30 days vs previous 30 days)
        $currentMonthProducts = Product::where('created_at', '>=', Carbon::now()->subDays(30))->count();
        $previousMonthProducts = Product::whereBetween('created_at', 
            [Carbon::now()->subDays(60), Carbon::now()->subDays(30)])->count();
        $productsChange = $previousMonthProducts > 0 ? 
            round((($currentMonthProducts - $previousMonthProducts) / $previousMonthProducts) * 100, 1) : 
            ($currentMonthProducts > 0 ? 100 : 0);

        // Categories change
        $currentMonthCategories = Category::where('created_at', '>=', Carbon::now()->subDays(30))->count();
        $previousMonthCategories = Category::whereBetween('created_at', 
            [Carbon::now()->subDays(60), Carbon::now()->subDays(30)])->count();
        $categoriesChange = $previousMonthCategories > 0 ? 
            round((($currentMonthCategories - $previousMonthCategories) / $previousMonthCategories) * 100, 1) : 
            ($currentMonthCategories > 0 ? 100 : 0);

        // Blogs change
        $currentMonthBlogs = Blog::where('created_at', '>=', Carbon::now()->subDays(30))->count();
        $previousMonthBlogs = Blog::whereBetween('created_at', 
            [Carbon::now()->subDays(60), Carbon::now()->subDays(30)])->count();
        $blogsChange = $previousMonthBlogs > 0 ? 
            round((($currentMonthBlogs - $previousMonthBlogs) / $previousMonthBlogs) * 100, 1) : 
            ($currentMonthBlogs > 0 ? 100 : 0);

        // Users change
        $currentMonthUsers = User::where('created_at', '>=', Carbon::now()->subDays(30))->count();
        $previousMonthUsers = User::whereBetween('created_at', 
            [Carbon::now()->subDays(60), Carbon::now()->subDays(30)])->count();
        $usersChange = $previousMonthUsers > 0 ? 
            round((($currentMonthUsers - $previousMonthUsers) / $previousMonthUsers) * 100, 1) : 
            ($currentMonthUsers > 0 ? 100 : 0);

        $this->stats = [
            [
                'title' => 'New Leads Today',
                'value' => number_format($todayLeads),
                'icon' => 'chart-bar',
                'color' => 'purple',
                'change' => $leadsChange >= 0 ? '+' . $leadsChange . '%' : $leadsChange . '%',
                'change_type' => $leadsChange >= 0 ? 'increase' : 'decrease'
            ],
            [
                'title' => 'Total Leads',
                'value' => number_format($totalLeads),
                'icon' => 'users',
                'color' => 'blue',
                'change' => $leadsChange >= 0 ? '+' . $leadsChange . '%' : $leadsChange . '%',
                'change_type' => $leadsChange >= 0 ? 'increase' : 'decrease'
            ],
            [
                'title' => 'Total Products',
                'value' => number_format($totalProducts),
                'icon' => 'cube',
                'color' => 'green',
                'change' => $productsChange >= 0 ? '+' . $productsChange . '%' : $productsChange . '%',
                'change_type' => $productsChange >= 0 ? 'increase' : 'decrease'
            ],
            [
                'title' => 'Categories',
                'value' => number_format($totalCategories),
                'icon' => 'folder',
                'color' => 'yellow',
                'change' => $categoriesChange >= 0 ? '+' . $categoriesChange . '%' : $categoriesChange . '%',
                'change_type' => $categoriesChange >= 0 ? 'increase' : 'decrease'
            ],
            
            [
                'title' => 'Blog Posts',
                'value' => number_format($totalBlogs),
                'icon' => 'file-alt',
                'color' => 'indigo',
                'change' => $blogsChange >= 0 ? '+' . $blogsChange . '%' : $blogsChange . '%',
                'change_type' => $blogsChange >= 0 ? 'increase' : 'decrease'
            ],
            [
                'title' => 'Active Users',
                'value' => number_format($totalUsers),
                'icon' => 'user-friends',
                'color' => 'red',
                'change' => $usersChange >= 0 ? '+' . $usersChange . '%' : $usersChange . '%',
                'change_type' => $usersChange >= 0 ? 'increase' : 'decrease'
            ]
        ];
    }

    public function loadRecentLeads()
    {
        $this->recentLeads = Lead::latest()
            ->take(5)
            ->get()
            ->map(function ($lead) {
                return [
                    'id' => $lead->id,
                    'name' => $lead->firstname . ' ' . $lead->lastname,
                    'email' => $lead->email ?? 'N/A',
                    'phone' => $lead->phone ?? 'N/A',
                    'company' => $lead->companyname ?? 'N/A',
                    'created_at' => $lead->created_at->diffForHumans(),
                    'source' => $lead->source ?? 'Website'
                ];
            })
            ->toArray();
    }

    public function loadTopProducts()
    {
        // Get latest products instead of top products by leads
        $this->topProducts = Product::latest()
            ->take(5)
            ->get()
            ->map(function ($product) {
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'image' => $product->image ?? null,
                    'price' => $product->price ?? null,
                    'category' => $product->category_id ? 
                        (Category::find($product->category_id)->name ?? 'Uncategorized') : 
                        'Uncategorized',
                    'created_at' => $product->created_at->diffForHumans()
                ];
            })
            ->toArray();
    }

    public function getLeadStats()
    {
        // Lead source distribution (since there's no status field)
        $leadSources = Lead::groupBy('source')
            ->selectRaw('source, count(*) as count')
            ->get()
            ->pluck('count', 'source')
            ->toArray();

        // Country distribution
        $leadCountries = Lead::whereNotNull('country')
            ->groupBy('country')
            ->selectRaw('country, count(*) as count')
            ->get()
            ->pluck('count', 'country')
            ->toArray();

        return [
            'sources' => $leadSources,
            'countries' => $leadCountries
        ];
    }

    public function getRecentActivity()
    {
        // Get recent activities from different models
        $recentLeads = Lead::latest()->take(3)->get();
        $recentProducts = Product::latest()->take(3)->get();
        $recentBlogs = Blog::latest()->take(3)->get();

        return [
            'leads' => $recentLeads,
            'products' => $recentProducts,
            'blogs' => $recentBlogs
        ];
    }

    public function getSystemOverview()
    {
        return [
            'total_banners' => Banner::count(),
            'total_brands' => Brand::count(),
            'total_pages' => Page::count(),
            'latest_user' => User::latest()->first(),
            'server_time' => now()->format('M j, Y g:i A')
        ];
    }

    public function refreshData()
    {
        $this->loadStats();
        $this->loadRecentLeads();
        $this->loadTopProducts();
        
        // You can add a success message here
        session()->flash('message', 'Dashboard data refreshed successfully!');
    }

    public function render()
    {
        $leadStats = $this->getLeadStats();
        $recentActivity = $this->getRecentActivity();
        $systemOverview = $this->getSystemOverview();

        return view('livewire.admin.dashboard', [
            'leadStats' => $leadStats,
            'recentActivity' => $recentActivity,
            'systemOverview' => $systemOverview
        ]);
    }
}