<?php

namespace App\Filament\Pages;

use App\Models\SystemSetting;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form; // CRITICAL: The correct class
use Filament\Schemas\Schema;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use UnitEnum;
use BackedEnum;

class SystemSettings extends Page implements HasForms
{
    use InteractsWithForms;

    protected string $view = 'filament.pages.system-settings';

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-cog-6-tooth';

    protected static UnitEnum|string|null $navigationGroup = 'Configuration';

    public ?array $data = [];

    public function mount(): void
    {
        // Populate the form data array
        $this->form->fill([
            'app_name' => SystemSetting::getValue('app_name', 'TripCup'),
            'app_timezone' => config('app.timezone', 'UTC'),
            'registration_enabled' => SystemSetting::getValue('registration_enabled', true),
            'ai_features_enabled' => SystemSetting::getValue('ai_features_enabled', true),
            'maintenance_mode' => SystemSetting::getValue('maintenance_mode', false),
            'razorpay_enabled' => !empty(env('RAZORPAY_KEY_ID')),
            'firebase_enabled' => !empty(env('FIREBASE_CREDENTIALS')),
            // Email settings
            'mail_mailer' => SystemSetting::getValue('mail_mailer', config('mail.default', 'smtp')),
            'mail_host' => SystemSetting::getValue('mail_host', config('mail.mailers.smtp.host')),
            'mail_port' => SystemSetting::getValue('mail_port', config('mail.mailers.smtp.port')),
            'mail_username' => SystemSetting::getValue('mail_username', config('mail.mailers.smtp.username')),
            'mail_password' => SystemSetting::getValue('mail_password', config('mail.mailers.smtp.password')),
        ]);
    }

    /**
     * Corrected Signature: Non-static method accepting and returning Filament\Forms\Form.
     */
    public static function form(Schema $schema): Schema
    {
        return $schema
            // All components are listed in a flat array, removing layout complexity.
            ->schema([
                // Application Settings
                \Filament\Forms\Components\TextInput::make('app_name')
                    ->label('Application Name')
                    ->required()
                    ->maxLength(255),
                
                \Filament\Forms\Components\Select::make('app_timezone')
                    ->label('Default Timezone')
                    ->options([
                        'Asia/Kolkata' => 'India (IST)',
                        'UTC' => 'UTC',
                        'America/New_York' => 'Eastern Time',
                        'Europe/London' => 'London',
                    ])
                    ->required(),

                // Feature Toggles
                \Filament\Forms\Components\Toggle::make('registration_enabled')
                    ->label('User Registration')
                    ->helperText('Allow new travel agents to register'),
                
                \Filament\Forms\Components\Toggle::make('ai_features_enabled')
                    ->label('AI Features')
                    ->helperText('Enable AI content generation features'),
                
                \Filament\Forms\Components\Toggle::make('maintenance_mode')
                    ->label('Maintenance Mode')
                    ->helperText('Put the system in maintenance mode'),

                // Third-party Services (Disabled/Read-only)
                \Filament\Forms\Components\Toggle::make('razorpay_enabled')
                    ->label('Razorpay Payments')
                    ->helperText('Status based on ENV configuration')
                    ->disabled(),
                
                \Filament\Forms\Components\Toggle::make('firebase_enabled')
                    ->label('Firebase Authentication')
                    ->helperText('Status based on ENV configuration')
                    ->disabled(),

                // Email Settings
                \Filament\Forms\Components\Select::make('mail_mailer')
                    ->label('Mail Driver')
                    ->options([
                        'smtp' => 'SMTP',
                        'mailgun' => 'Mailgun',
                        'ses' => 'Amazon SES',
                        'postmark' => 'Postmark',
                    ]),
                
                \Filament\Forms\Components\TextInput::make('mail_host')->label('SMTP Host'),
                
                \Filament\Forms\Components\TextInput::make('mail_port')
                    ->label('SMTP Port')
                    ->numeric(),
                
                \Filament\Forms\Components\TextInput::make('mail_username')->label('SMTP Username'),
                
                \Filament\Forms\Components\TextInput::make('mail_password')
                    ->label('SMTP Password')
                    ->password(),

                // System Information (Read-only)
                \Filament\Forms\Components\TextInput::make('app_version')
                    ->label('App Version')
                    ->default('1.0.0')
                    ->disabled(),
                
                \Filament\Forms\Components\TextInput::make('laravel_version')
                    ->label('Laravel Version')
                    ->default(fn () => app()->version())
                    ->disabled(),
                
                \Filament\Forms\Components\TextInput::make('php_version')
                    ->label('PHP Version')
                    ->default(fn () => PHP_VERSION)
                    ->disabled(),
            ])
            ->statePath('data'); // Binds form fields to the public $data property
    }

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

    public function save(): void
    {
        // Validate and retrieve data from the form
        $data = $this->form->getState();

        // Save application settings
        SystemSetting::setValue('app_name', $data['app_name'], 'string', 'Application name');
        SystemSetting::setValue('app_timezone', $data['app_timezone'], 'string', 'Application timezone');
        SystemSetting::setValue('registration_enabled', $data['registration_enabled'], 'boolean', 'Allow new registrations');
        SystemSetting::setValue('ai_features_enabled', $data['ai_features_enabled'], 'boolean', 'Enable AI features');
        SystemSetting::setValue('maintenance_mode', $data['maintenance_mode'], 'boolean', 'Maintenance mode');
        
        // Save email settings
        SystemSetting::setValue('mail_mailer', $data['mail_mailer'], 'string', 'Mail driver');
        SystemSetting::setValue('mail_host', $data['mail_host'], 'string', 'SMTP host');
        SystemSetting::setValue('mail_port', $data['mail_port'], 'string', 'SMTP port');
        SystemSetting::setValue('mail_username', $data['mail_username'], 'string', 'SMTP username');
        SystemSetting::setValue('mail_password', $data['mail_password'], 'string', 'SMTP password');

        // Show success notification
        Notification::make()
            ->title('Settings saved successfully!')
            ->success()
            ->send();
    }
}