<?php

namespace App\Filament\Pages;

use App\Models\Setting;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Hidden;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Grid;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Actions\Contracts\HasActions;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Notifications\Notification;
use Filament\Actions\Action;

class AdminBranding extends Page implements HasForms, HasActions
{
    use InteractsWithForms, InteractsWithActions;

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-swatch';

    protected string $view = 'filament.pages.admin-branding';

    protected static ?string $title = 'Admin Branding & Theme';

    protected static bool $shouldRegisterNavigation = false;

    public ?array $data = [];

    public function mount()
    {
        $settings = Setting::pluck('value', 'key')->toArray();
        $this->form->fill(array_merge([
            'theme_preset' => 'amber',
            'primary_color' => '#f59e0b',
        ], $settings));
    }

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Grid::make(3)
                    ->schema([
                        // Left block (2/3 width)
                        Grid::make(1)
                            ->schema([
                                Section::make('Admin Panel Identity')
                                    ->description('Customize branding assets.')
                                    ->schema([
                                        FileUpload::make('admin_logo')
                                            ->label('Admin Panel Logo')
                                            ->disk('public')
                                            ->directory('branding')
                                            ->image()
                                            ->maxSize(2048)
                                            ->imagePreviewHeight('80')
                                            ->helperText('Recommended: PNG/SVG. Size: 200x50px (approx. 4:1).'),
                                        FileUpload::make('admin_favicon')
                                            ->label('Admin Panel Favicon')
                                            ->disk('public')
                                            ->directory('branding')
                                            ->image()
                                            ->maxSize(512)
                                            ->imagePreviewHeight('80')
                                            ->helperText('Recommended: ICO/PNG. Size: 32x32px or 48x48px (1:1).'),
                                    ])->columns(2),

                                Section::make('Admin Panel Theme Color')
                                    ->description('Select a theme color.')
                                    ->schema([
                                        Hidden::make('theme_preset')
                                            ->live()
                                            ->required(),
                                        Hidden::make('primary_color')
                                            ->live()
                                            ->required(),
                                        Placeholder::make('theme_picker')
                                            ->hiddenLabel()
                                            ->content(fn () => view('filament.pages.theme-picker-field')),
                                    ]),
                            ])
                            ->columnSpan(2),

                        // Right block (1/3 width)
                        Grid::make(1)
                            ->schema([
                                Section::make('Live Panel Preview')
                                    ->description('Preview branding live.')
                                    ->schema([
                                        Placeholder::make('branding_preview')
                                            ->hiddenLabel()
                                            ->content(fn ($get) => view('filament.pages.branding-preview', [
                                                'theme_preset' => $get('theme_preset'),
                                                'primary_color' => $get('primary_color'),
                                                'admin_logo' => $get('admin_logo'),
                                            ])),
                                    ]),
                            ])
                            ->columnSpan(1),
                    ]),
            ])
            ->statePath('data');
    }

    protected function getFormActions(): array
    {
        return [
            Action::make('save')
                ->label('Save Branding Settings')
                ->submit('save')
                ->color('primary'),
        ];
    }

    public function save()
    {
        $state = $this->form->getState();

        foreach ($state as $key => $value) {
            Setting::setValue($key, $value, 'branding');
        }

        // Sync favicon to public directory so browser gets it from /favicon.ico instantly
        if (!empty($state['admin_favicon'])) {
            $source = storage_path('app/public/' . $state['admin_favicon']);
            if (file_exists($source)) {
                @copy($source, public_path('favicon.ico'));
                @copy($source, public_path('favicon.png'));
            }
        }

        Notification::make()
            ->title('Branding Settings Saved')
            ->body('Admin panel branding and theme settings have been updated successfully.')
            ->success()
            ->send();
    }
}
