<?php

namespace App\Providers\Filament;

use Althinect\FilamentSpatieRolesPermissions\FilamentSpatieRolesPermissionsPlugin;
use App\Filament\Pages\InvoiceDashboard;
use App\Filament\Pages\NotificationSettings;
use Filament\Facades\Filament;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Navigation\MenuItem;
use Filament\Navigation\NavigationGroup;
use Filament\Navigation\NavigationItem;
use Filament\Pages;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Widgets;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use Althinect\FilamentSpatieRolesPermissions\Middleware\SyncSpatiePermissionsWithFilamentTenants;
use App\Filament\Auth\CustomLogin as AuthCustomLogin;
use App\Filament\Pages\CustomLogin;
use Filament\View\PanelsRenderHook;
use Filament\Support\Facades\FilamentView;
use Illuminate\Support\Facades\Blade;
use Filament\Pages\Auth\PasswordReset\RequestPasswordReset;
use Filament\Pages\Auth\PasswordReset\ResetPassword;


class AdminPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {

        return $panel
            ->default()
            ->id('admin')
            ->path('admin')
            ->login()
            ->passwordReset(
                RequestPasswordReset::class,
                ResetPassword::class,
            )
        //->maxContentWidth(MaxWidth::Small)
        //->simplePageMaxContentWidth(MaxWidth::Medium)

        //     ->login(Login::class, function (Login $login) {
        //     $login->formActions([
        //         ...$login->getFormActions(),
        //         Action::make('forgotPassword')
        //             ->label('Forgot your password?')
        //             ->url(route('password.request')),
        //     ]);
        // })
            // ->favicon(asset('/assets/crilogo1.png'))
            ->favicon(asset('assets/crilogo1.png'))
            ->colors([
                'primary' => Color::Amber,
            ])
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'App\\Filament\\Pages')
            ->pages([

            ])
            ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
            // ->widgets([
            //     Widgets\AccountWidget::class,
            //     Widgets\FilamentInfoWidget::class,
            // ])
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                VerifyCsrfToken::class,
                SubstituteBindings::class,
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
            ])
            ->authMiddleware([
                Authenticate::class,
            ])
            ->tenantMiddleware([
                SyncSpatiePermissionsWithFilamentTenants::class,
            ], isPersistent: true)
            ->databaseNotifications()
        //     ->renderHook(PanelsRenderHook::AUTH_LOGIN_FORM_AFTER, function () {
        //     // Use Filament panel helper for login URL and custom route for forgot password
        //     return '<div class="mt-4 text-center">
        //                 <a href="' . route('filament.admin.forgot-password') . '" class="text-primary-600 hover:underline">
        //                     Forgot your password?
        //                 </a>
        //             </div>';
        // })
        //->renderHook('panels::body.end', fn () => view('components.pages.folder-picker-script'))
            ->renderHook(
                PanelsRenderHook::SIDEBAR_NAV_START,
                fn () => view('components.navigation-filter')
            )
            ->plugin(FilamentSpatieRolesPermissionsPlugin::make());
    }

    // public function boot(): void
    // {
    //     FilamentView::registerRenderHook(
    //         'panels::head.end',
    //         fn() => '
    //             <link rel="manifest" href="' . asset('manifest.json') . '">
    //             <meta name="theme-color" content="#007bff">
    //             <script>
    //                 if ("serviceWorker" in navigator) {
    //                     navigator.serviceWorker.register("/sw.js")
    //                         .then(reg => console.log("Service Worker registered:", reg.scope))
    //                         .catch(err => console.error("Service Worker registration failed:", err));
    //                 }
    //             </script>
    //         '
    //     );

    //     FilamentView::registerRenderHook('panels::body.end', function () {
    //         return '<script src="' . asset('js/pwa-install.js') . '"></script>';
    //     });
    // }

    public function boot(): void
    {

        FilamentView::registerRenderHook('panels::body.end', function () {
            if (url()->current() == config('app.url') . '/admin') {
                return '<script src="' . asset('js/push.js') . '"></script>';
            }

            return '';
        });

        FilamentView::registerRenderHook('panels::head.end', function () {
            // Only inject on the "home" page (or specific route)
            if (url()->current() == config('app.url') . '/admin') {
                return '
                    <link rel="manifest" href="' . asset('manifest.json') . '">
                    <meta name="theme-color" content="#007bff">
                    <script>
                        if ("serviceWorker" in navigator) {
                            navigator.serviceWorker.register("/sw.js")
                                .then(reg => console.log("Service Worker registered:", reg.scope))
                                .catch(err => console.error("Service Worker registration failed:", err));
                        }
                    </script>
                ';
            }

            return ''; // Do not inject on other pages
        });

        // Only include PWA install script if on home page
        FilamentView::registerRenderHook('panels::body.end', function () {
            if (url()->current() == config('app.url') . '/admin') {
                return '<script src="' . asset('js/pwa-install.js') . '"></script>';
            }
            return '';
        });

        FilamentView::registerRenderHook(
            PanelsRenderHook::BODY_END,
            fn (): string => Blade::render("@livewire('chat-bot')"),
        );
    }
}
