<?php

namespace App\Providers\Filament;

use Filament\Http\Middleware\Authenticate;
use Filament\Navigation\NavigationGroup;
use Filament\Navigation\MenuItem;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use App\Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\View\PanelsRenderHook;
use Filament\Widgets\AccountWidget;
use Filament\Widgets\FilamentInfoWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\Middleware\ShareErrorsFromSession;

class AdminPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->default()
            ->id('admin')
            ->path('admin')
            ->viteTheme('resources/css/filament/admin/theme.css')
            ->sidebarCollapsibleOnDesktop()
            ->sidebarWidth('19rem')
            ->collapsedSidebarWidth('4rem')
            ->login()
            ->colors([
                'purple' => Color::Purple,
                'primary' => (function () {
                    try {
                        if (! app()->runningInConsole() || \Illuminate\Support\Facades\Schema::hasTable('settings')) {
                            $preset = \App\Models\Setting::getValue('theme_preset', 'amber');
                            $hex = match ($preset) {
                                'emerald' => '#10b981',
                                'blue'    => '#3b82f6',
                                'violet'  => '#8b5cf6',
                                'rose'    => '#f43f5e',
                                'teal'    => '#0d9488',
                                'orange'  => '#f97316',
                                'custom'  => \App\Models\Setting::getValue('primary_color', '#f59e0b'),
                                default   => '#f59e0b',
                            };
                            return Color::hex($hex);
                        }
                    } catch (\Throwable $e) {}
                    return Color::Amber;
                })(),
            ])
            ->brandLogo(fn () => \App\Models\Setting::getValue('admin_logo')
                ? asset('storage/' . \App\Models\Setting::getValue('admin_logo'))
                : asset('images/sawdabazar-logo.png')
            )
            ->brandName(fn () => \App\Models\Setting::getValue('site_name', config('app.name', 'Sawdabazar')))
            ->brandLogoHeight('2.5rem')
            ->favicon(fn () => \App\Models\Setting::getValue('admin_favicon')
                ? asset('storage/' . \App\Models\Setting::getValue('admin_favicon'))
                : asset('favicon.ico')
            )
            ->profile(\App\Filament\Pages\Auth\EditProfile::class)
            ->databaseNotifications()
            ->databaseNotificationsPolling('15s')
            ->userMenuItems([
                MenuItem::make()
                    ->label('Admin Branding')
                    ->url(fn (): string => \App\Filament\Pages\AdminBranding::getUrl())
                    ->icon('heroicon-o-swatch'),
            ])
            ->navigationGroups([
                NavigationGroup::make('Orders')->collapsed(),
                NavigationGroup::make('Products')->collapsed(),
                NavigationGroup::make('Customers')->collapsed(),
                NavigationGroup::make('Reseller System')
                    ->label('Reseller System')
                    ->collapsed(),
                NavigationGroup::make('Site Builder')->collapsed(),
                NavigationGroup::make('Marketing')->collapsed(),
                NavigationGroup::make('Analytics')->collapsed(),
                NavigationGroup::make('Settings')->collapsed(),
            ])
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
            ->pages([Dashboard::class])
            ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets')
            ->plugins([
                \Pboivin\FilamentPeek\FilamentPeekPlugin::make(),
            ])
            ->widgets([
                \App\Filament\Widgets\StatsOverviewWidget::class,
                \App\Filament\Widgets\RevenueChartWidget::class,
                \App\Filament\Widgets\OrderStatusChartWidget::class,
                \App\Filament\Widgets\ProfitMarginWidget::class,
                \App\Filament\Widgets\RecentOrdersWidget::class,
            ])
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                PreventRequestForgery::class,
                SubstituteBindings::class,
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
                \App\Http\Middleware\CheckInstalled::class,
            ])
            ->renderHook(
                \Filament\View\PanelsRenderHook::BODY_END,
                fn () => view('filament.custom-js'),
            )
            ->authMiddleware([Authenticate::class]);
    }
}
