<?php

namespace App\Filament\Pages;

use App\Filament\Forms\Components\EmailPreviewToggle;
use App\Filament\Forms\Components\ThemePreview;
use App\Helpers\PayPalCurrencies;
use App\Models\Setting;
use App\Services\EmailPreviewService;
use App\Services\ThemeService;
use BackedEnum;
use DateTimeZone;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;

/**
 * @property-read Schema $form
 */
class ManageSettings extends Page
{
    protected static ?string $panel = 'config';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCog6Tooth;

    protected static ?string $navigationLabel = 'Settings';

    protected static ?int $navigationSort = 100;

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

    public static function shouldRegisterNavigation(): bool
    {
        return filament()->getCurrentPanel()->getId() === 'config';
    }

    /**
     * @var array<string, mixed> | null
     */
    public ?array $data = [];

    public function mount(): void
    {
        $settings = Setting::all()->keyBy('key');

        $data = [];
        foreach ($settings as $key => $setting) {
            $data[$key] = $setting->getTypedValue();
        }

        $this->form->fill($data);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([
                    Tabs::make('Settings')
                        ->tabs([
                            Tabs\Tab::make('General')
                                ->icon(Heroicon::OutlinedInformationCircle)
                                ->schema([
                                    Section::make('Website Information')
                                        ->description('Basic information about your website')
                                        ->schema([
                                            TextInput::make('site_name')
                                                ->label('Site Name')
                                                ->required()
                                                ->maxLength(255),
                                            TextInput::make('site_tagline')
                                                ->label('Tagline')
                                                ->maxLength(255),
                                            Textarea::make('site_description')
                                                ->label('Description')
                                                ->rows(3)
                                                ->maxLength(500),
                                        ])
                                        ->columns(1),
                                    Section::make('Branding')
                                        ->description('Upload your logo and hero images')
                                        ->schema([
                                            FileUpload::make('site_logo')
                                                ->label('Site Logo')
                                                ->helperText('Logo image (will be compressed to 400x400 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('header_image')
                                                ->label('Header Image')
                                                ->helperText('Background image for the hero section (will be compressed to 1280x460 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('middle_image')
                                                ->label('Middle Section Image')
                                                ->helperText('Background image for the middle section (will be compressed to 600x600 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('footer_image')
                                                ->label('Footer Image')
                                                ->helperText('Background image for the footer section (will be compressed to 1280x460 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('application_form_header_image')
                                                ->label('Application Form Header Image')
                                                ->helperText('Background image for application form headers (will be compressed to 1280x460 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('pets_page_header_image')
                                                ->label('Pets Page Header Image')
                                                ->helperText('Background image for the pets page header (will be compressed to 1280x460 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                            FileUpload::make('blog_header_image')
                                                ->label('Blog Header Image')
                                                ->helperText('Background image for the blog page header (will be compressed to 1280x460 WebP)')
                                                ->image()
                                                ->disk('public')
                                                ->directory('branding')
                                                ->maxSize(12288)
                                                ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']),
                                        ])
                                        ->columns(1),
                                    Section::make('Localization')
                                        ->description('Configure timezone settings')
                                        ->schema([
                                            Select::make('default_timezone')
                                                ->label('Default Timezone')
                                                ->options(fn () => collect(DateTimeZone::listIdentifiers())
                                                    ->mapWithKeys(fn ($tz) => [$tz => $tz])
                                                    ->toArray())
                                                ->searchable()
                                                ->required()
                                                ->default(fn () => Setting::get('default_timezone'))
                                                ->helperText('Default timezone for new users'),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('SEO')
                                ->icon(Heroicon::OutlinedMagnifyingGlass)
                                ->schema([
                                    Section::make('Meta Tags')
                                        ->description('Default SEO meta tags for your website')
                                        ->schema([
                                            TextInput::make('seo_title')
                                                ->label('SEO Title')
                                                ->maxLength(60)
                                                ->helperText('Recommended: 50-60 characters'),
                                            Textarea::make('seo_description')
                                                ->label('Meta Description')
                                                ->rows(3)
                                                ->maxLength(160)
                                                ->helperText('Recommended: 150-160 characters'),
                                            TextInput::make('seo_keywords')
                                                ->label('Keywords')
                                                ->maxLength(255)
                                                ->helperText('Comma-separated keywords'),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('Contact')
                                ->icon(Heroicon::OutlinedEnvelope)
                                ->schema([
                                    Section::make('Contact Information')
                                        ->schema([
                                            TextInput::make('contact_email')
                                                ->label('Email Address')
                                                ->email()
                                                ->required()
                                                ->maxLength(255),
                                            TextInput::make('contact_phone')
                                                ->label('Phone Number')
                                                ->tel()
                                                ->maxLength(255),
                                            TextInput::make('contact_address')
                                                ->label('Physical Address')
                                                ->maxLength(500),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('Social Media')
                                ->icon(Heroicon::OutlinedShare)
                                ->schema([
                                    Section::make('Social Media Links')
                                        ->description('Add links to your social media profiles')
                                        ->schema([
                                            TextInput::make('social_facebook')
                                                ->label('Facebook')
                                                ->url()
                                                ->maxLength(255)
                                                ->placeholder('https://facebook.com/yourpage'),
                                            TextInput::make('social_twitter')
                                                ->label('Twitter / X')
                                                ->url()
                                                ->maxLength(255)
                                                ->placeholder('https://twitter.com/yourprofile'),
                                            TextInput::make('social_instagram')
                                                ->label('Instagram')
                                                ->url()
                                                ->maxLength(255)
                                                ->placeholder('https://instagram.com/yourprofile'),
                                            TextInput::make('social_youtube')
                                                ->label('YouTube')
                                                ->url()
                                                ->maxLength(255)
                                                ->placeholder('https://youtube.com/yourchannel'),
                                            TextInput::make('social_linkedin')
                                                ->label('LinkedIn')
                                                ->url()
                                                ->maxLength(255)
                                                ->placeholder('https://linkedin.com/company/yourcompany'),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('Fundraising')
                                ->icon(Heroicon::CurrencyDollar)
                                ->schema([
                                    Section::make('Feature Toggles')
                                        ->description('Enable or disable fundraising features')
                                        ->schema([
                                            Toggle::make('enable_draws')
                                                ->label('Enable 50/50 Draws')
                                                ->helperText('Enable or disable 50/50 draw functionality'),
                                            Toggle::make('enable_memberships')
                                                ->label('Enable Memberships')
                                                ->helperText('Enable or disable membership donation functionality'),
                                        ])
                                        ->columns(2),
                                    Section::make('PayPal Settings')
                                        ->description('Configure PayPal integration for payments')
                                        ->schema([
                                            Select::make('paypal_mode')
                                                ->label('PayPal Mode')
                                                ->options([
                                                    'sandbox' => 'Sandbox (Testing)',
                                                    'live' => 'Live (Production)',
                                                ])
                                                ->required()
                                                ->default('sandbox')
                                                ->helperText('Select sandbox for testing or live for production payments'),
                                            TextInput::make('paypal_email')
                                                ->label('PayPal Email Address')
                                                ->email()
                                                ->required()
                                                ->maxLength(255)
                                                ->helperText('PayPal email address for receiving payments'),
                                            Select::make('currency')
                                                ->label('Payment Currency')
                                                ->options(PayPalCurrencies::options())
                                                ->required()
                                                ->default('CAD')
                                                ->searchable()
                                                ->helperText('Currency used for membership payments. This must match the currency configured in your PayPal account, and must be one of the currencies PayPal supports.'),
                                        ])
                                        ->columns(2),
                                    Section::make('Draw Settings')
                                        ->description('Configure settings for 50/50 draws')
                                        ->schema([
                                            Textarea::make('draw_payment_info_text')
                                                ->label('Payment Information Message')
                                                ->rows(3)
                                                ->maxLength(500)
                                                ->helperText('Message displayed to users when purchasing draw tickets')
                                                ->required(),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('Applications')
                                ->icon(Heroicon::OutlinedDocumentText)
                                ->schema([
                                    Section::make('Application Settings')
                                        ->description('Configure settings for adoption, fostering, and assistance applications')
                                        ->schema([
                                            Toggle::make('enable_foster_applications')
                                                ->label('Enable Foster Applications')
                                                ->helperText('Allow users to submit foster application forms'),
                                            Toggle::make('enable_assistance_applications')
                                                ->label('Enable Assistance Applications')
                                                ->helperText('Allow users to submit assistance application forms'),
                                            Toggle::make('view_submissions_online')
                                                ->label('View Submissions Online')
                                                ->helperText('Allow users to view their application submissions online on the dashboard'),
                                            Toggle::make('require_application_for_manual_adoption')
                                                ->label('Require Application for Manual Adoptions')
                                                ->helperText('When enabled, pets marked as adopted without a linked application will be flagged on the dashboard and in a dedicated Pets list tab.'),
                                            TextInput::make('max_active_adoption_applications')
                                                ->label('Max Active Adoption Applications Per User')
                                                ->helperText('Maximum number of non-archived adoption applications a user can have at once')
                                                ->numeric()
                                                ->required()
                                                ->minValue(1)
                                                ->maxValue(10)
                                                ->default(2),
                                            TextInput::make('max_active_assistance_applications')
                                                ->label('Max Active Assistance Applications Per User')
                                                ->helperText('Maximum number of non-archived assistance applications a user can have at once')
                                                ->numeric()
                                                ->required()
                                                ->minValue(1)
                                                ->maxValue(10)
                                                ->default(2),
                                        ])
                                        ->columns(2),
                                    Section::make('Authentication Requirements')
                                        ->description('Control whether users must be authenticated to submit applications')
                                        ->schema([
                                            Toggle::make('require_auth_for_adoption_applications')
                                                ->label('Require Authentication for Adoption Applications')
                                                ->helperText('When disabled, unauthenticated users can submit adoption applications by providing their contact information')
                                                ->default(true),
                                            Toggle::make('require_auth_for_fostering_applications')
                                                ->label('Require Authentication for Fostering Applications')
                                                ->helperText('When disabled, unauthenticated users can submit fostering applications by providing their contact information')
                                                ->default(true),
                                            Toggle::make('require_auth_for_assistance_applications')
                                                ->label('Require Authentication for Assistance Applications')
                                                ->helperText('When disabled, unauthenticated users can submit assistance applications by providing their contact information')
                                                ->default(true),
                                        ])
                                        ->columns(2),
                                ]),
                            Tabs\Tab::make('Communication')
                                ->icon(Heroicon::OutlinedBell)
                                ->schema([
                                    View::make('filament.schemas.components.email-configuration'),
                                    Section::make('General')
                                        ->description('General user notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_welcome_enabled')
                                                ->label('Welcome Email')
                                                ->helperText('Send welcome email after user email verification')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('welcome')),
                                        ])
                                        ->columns(2),
                                    Section::make('Adoptions')
                                        ->description('Adoption application notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_adoption_application_received_enabled')
                                                ->label('Application Received')
                                                ->helperText('Send confirmation email when adoption application is received')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('adoption_application_received')),
                                            EmailPreviewToggle::make('email_adoption_application_approved_enabled')
                                                ->label('Application Approved')
                                                ->helperText('Send email when adoption application is approved')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('adoption_application_approved')),
                                            EmailPreviewToggle::make('email_adoption_application_rejected_enabled')
                                                ->label('Application Rejected')
                                                ->helperText('Send email when adoption application is rejected')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('adoption_application_rejected')),
                                        ])
                                        ->columns(2),
                                    Section::make('Fostering')
                                        ->description('Fostering application notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_fostering_application_received_enabled')
                                                ->label('Application Received')
                                                ->helperText('Send confirmation email when fostering application is received')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('fostering_application_received')),
                                            EmailPreviewToggle::make('email_fostering_application_approved_enabled')
                                                ->label('Application Approved')
                                                ->helperText('Send email when fostering application is approved')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('fostering_application_approved')),
                                            EmailPreviewToggle::make('email_fostering_application_rejected_enabled')
                                                ->label('Application Rejected')
                                                ->helperText('Send email when fostering application is rejected')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('fostering_application_rejected')),
                                        ])
                                        ->columns(2),
                                    Section::make('Assistance')
                                        ->description('Assistance application notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_assistance_application_received_enabled')
                                                ->label('Application Received')
                                                ->helperText('Send confirmation email when assistance application is received')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('assistance_application_received')),
                                            EmailPreviewToggle::make('email_assistance_application_approved_enabled')
                                                ->label('Application Approved')
                                                ->helperText('Send email when assistance application is approved')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('assistance_application_approved')),
                                            EmailPreviewToggle::make('email_assistance_application_rejected_enabled')
                                                ->label('Application Rejected')
                                                ->helperText('Send email when assistance application is rejected')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('assistance_application_rejected')),
                                        ])
                                        ->columns(2),
                                    Section::make('Interviews')
                                        ->description('Interview scheduling notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_interview_scheduled_enabled')
                                                ->label('Interview Scheduled (Applicant)')
                                                ->helperText('Send email to applicant when interview is scheduled')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('interview_scheduled')),
                                            EmailPreviewToggle::make('email_interview_rescheduled_enabled')
                                                ->label('Interview Rescheduled (Applicant)')
                                                ->helperText('Send email to applicant when interview is rescheduled')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('interview_rescheduled')),
                                            EmailPreviewToggle::make('email_interview_scheduled_admin_enabled')
                                                ->label('Interview Scheduled (Admin)')
                                                ->helperText('Send email to admin when interview is scheduled')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('interview_scheduled_admin')),
                                            EmailPreviewToggle::make('email_interview_rescheduled_admin_enabled')
                                                ->label('Interview Rescheduled (Admin)')
                                                ->helperText('Send email to admin when interview is rescheduled')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('interview_rescheduled_admin')),
                                        ])
                                        ->columns(2),
                                    Section::make('Fundraising')
                                        ->description('Draw and membership notifications')
                                        ->schema([
                                            EmailPreviewToggle::make('email_draw_winner_enabled')
                                                ->label('Draw Winner Notification')
                                                ->helperText('Send email to draw winner')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('draw_winner')),
                                            EmailPreviewToggle::make('email_ticket_registration_confirmation_enabled')
                                                ->label('Ticket Registration Confirmation')
                                                ->helperText('Send confirmation email when draw tickets are registered')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('ticket_registration_confirmation')),
                                            EmailPreviewToggle::make('email_membership_purchase_enabled')
                                                ->label('Membership Purchase Thank You')
                                                ->helperText('Send thank you email after membership purchase')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('membership_purchase')),
                                            EmailPreviewToggle::make('email_membership_expiring_enabled')
                                                ->label('Membership Expiring Soon')
                                                ->helperText('Send reminder email when membership is expiring soon')
                                                ->emailPreview(fn () => app(EmailPreviewService::class)->getPreview('membership_expiring')),
                                        ])
                                        ->columns(2),
                                ]),
                            Tabs\Tab::make('Theme')
                                ->icon(Heroicon::OutlinedPaintBrush)
                                ->schema([
                                    Section::make('Color Theme')
                                        ->description('Customize the color scheme for your frontend pages')
                                        ->schema([
                                            Select::make('theme_preset')
                                                ->label('Color Theme Preset')
                                                ->options(fn () => app(ThemeService::class)->getPresetOptions())
                                                ->required()
                                                ->default('ocean-blue')
                                                ->helperText('Select a color theme for your website. Changes will apply to all frontend pages after saving.')
                                                ->live(),
                                            ThemePreview::make('theme_preview')
                                                ->preset(fn ($get) => $get('theme_preset')),
                                        ])
                                        ->columns(1),
                                ]),
                            Tabs\Tab::make('Frontend')
                                ->icon(Heroicon::OutlinedGlobeAlt)
                                ->schema([
                                    Section::make('Navigation')
                                        ->description('Configure public-facing navigation options')
                                        ->schema([
                                            Toggle::make('show_auth_links')
                                                ->label('Show Sign In / Sign Up buttons')
                                                ->helperText('When enabled, Sign In and Sign Up buttons appear in the navigation header. When disabled, only a quiet "Admin" link appears in the footer.'),
                                        ])
                                        ->columns(1),
                                    Section::make('Print Bio')
                                        ->description('Configure the printable pet bio/PDF document')
                                        ->schema([
                                            Toggle::make('show_print_bio_qr_code')
                                                ->label('Show QR Code')
                                                ->helperText('When enabled, a QR code linking to the pet\'s public page appears on the printable bio. When disabled, the QR code is omitted.'),
                                        ])
                                        ->columns(1),
                                    Section::make('Pet Search Filters')
                                        ->description('Configure which search filters are available on the pets page. At least one filter must be enabled.')
                                        ->schema([
                                            Toggle::make('pet_search_name_enabled')
                                                ->label('Name Search')
                                                ->helperText('Allow users to search pets by name')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_name_enabled'))
                                                ->rules([
                                                    fn (): \Closure => function (string $attribute, $value, \Closure $fail) {
                                                        if (! $this->hasAtLeastOneSearchEnabled()) {
                                                            $fail('At least one pet search filter must be enabled.');
                                                        }
                                                    },
                                                ]),
                                            Toggle::make('pet_search_species_enabled')
                                                ->label('Species Filter')
                                                ->helperText('Allow users to filter pets by species')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_species_enabled')),
                                            Toggle::make('pet_search_breed_enabled')
                                                ->label('Breed Filter')
                                                ->helperText('Allow users to filter pets by breed')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_breed_enabled')),
                                            Toggle::make('pet_search_gender_enabled')
                                                ->label('Gender Filter')
                                                ->helperText('Allow users to filter pets by gender')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_gender_enabled')),
                                            Toggle::make('pet_search_size_enabled')
                                                ->label('Size Filter')
                                                ->helperText('Allow users to filter pets by size')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_size_enabled')),
                                            Toggle::make('pet_search_age_range_enabled')
                                                ->label('Age Range Filter')
                                                ->helperText('Allow users to filter pets by age range')
                                                ->live()
                                                ->afterStateUpdated(fn ($state, $set, $get) => $this->ensureAtLeastOneSearchEnabled($state, $set, $get, 'pet_search_age_range_enabled')),
                                        ])
                                        ->columns(2),
                                ]),
                        ])
                        ->columnSpanFull(),
                ])
                    ->livewireSubmitHandler('save')
                    ->footer([
                        Actions::make([
                            Action::make('save')
                                ->label('Save Settings')
                                ->icon(Heroicon::OutlinedCheck)
                                ->submit('save')
                                ->keyBindings(['mod+s']),
                        ]),
                    ]),
            ])
            ->statePath('data');
    }

    /**
     * Get the list of pet search setting keys.
     *
     * @return array<string>
     */
    protected function getPetSearchSettingKeys(): array
    {
        return [
            'pet_search_name_enabled',
            'pet_search_species_enabled',
            'pet_search_breed_enabled',
            'pet_search_gender_enabled',
            'pet_search_size_enabled',
            'pet_search_age_range_enabled',
        ];
    }

    /**
     * Check if at least one pet search setting is enabled.
     */
    protected function hasAtLeastOneSearchEnabled(): bool
    {
        foreach ($this->getPetSearchSettingKeys() as $key) {
            if (! empty($this->data[$key])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Ensure at least one search setting remains enabled by re-enabling the current one if it was the last.
     */
    protected function ensureAtLeastOneSearchEnabled(bool $state, callable $set, callable $get, string $currentKey): void
    {
        if ($state) {
            return;
        }

        $enabledCount = 0;
        foreach ($this->getPetSearchSettingKeys() as $key) {
            if ($key !== $currentKey && $get($key)) {
                $enabledCount++;
            }
        }

        if ($enabledCount === 0) {
            $set($currentKey, true);

            Notification::make()
                ->warning()
                ->title('Cannot Disable')
                ->body('At least one pet search filter must be enabled.')
                ->send();
        }
    }

    public function save(): void
    {
        $data = $this->form->getState();

        foreach ($data as $key => $value) {
            $setting = Setting::where('key', $key)->first();

            if ($setting) {
                $setting->setTypedValue($value);
                $setting->save();
            }
        }

        Setting::clearCache();

        // Clear theme cache if theme settings were changed
        if (isset($data['theme_preset']) || isset($data['theme_primary_color']) || isset($data['theme_secondary_color'])) {
            app(ThemeService::class)->clearCache();
        }

        Notification::make()
            ->success()
            ->title('Settings Saved')
            ->body('Your settings have been saved successfully.')
            ->send();
    }
}
