<?php

namespace App\Filament\Pages;

use App\Models\Setting;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Support\Exceptions\Halt;
use Filament\Forms\Components\Tabs; // Added
use Filament\Forms\Components\RichEditor; // Added
use BezhanSalleh\FilamentShield\Traits\HasPageShield;


class WebsiteSettings extends \Filament\Pages\SettingsPage
{
    // use HasPageShield;

    private $ar_terms = null;
    private $en_terms = null;
    private $notify_users = false;

    protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';

    protected static string $settings = Setting::class;
    protected static ?string $navigationGroup = 'Settings'; // Revert to string, use getter

    protected static ?int $navigationSort = 3;

    public static function getNavigationGroup(): ?string
    {
        return __('Settings');
    }

    public function getTitle(): string
    {
        return __('Website Settings');
    }

    public static function getNavigationLabel(): string
    {
        return __('Website Settings');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Tabs::make(__('Content')) // Translated
                    ->tabs([
                        Tabs\Tab::make(__('English')) // Translated
                            ->schema([
                                RichEditor::make('about_us_en')
                                    ->label(__('About Us (English)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                RichEditor::make('terms_and_conditions_en')
                                    ->label(__('Terms and Conditions (English)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                RichEditor::make('privacy_policy_en')
                                    ->label(__('Privacy Policy (English)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                // RichEditor::make('payment_description_en')
                                //     ->label(__('Payment Description (English)'))
                                //     ->required()
                                //     ->columnSpanFull(),
                            ]),
                        Tabs\Tab::make(__('Arabic')) // Translated
                            ->schema([
                                RichEditor::make('about_us_ar')
                                    ->label(__('About Us (Arabic)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                RichEditor::make('terms_and_conditions_ar')
                                    ->label(__('Terms and Conditions (Arabic)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                RichEditor::make('privacy_policy_ar')
                                    ->label(__('Privacy Policy (Arabic)')) // Translated
                                    ->required()
                                    ->columnSpanFull(),
                                // RichEditor::make('payment_description_ar')
                                //     ->label(__('Payment Description (Arabic)'))
                                //     ->required()
                                //     ->columnSpanFull(),
                            ]),
                    ])->columnSpanFull(),

                Forms\Components\Section::make(__('Contact Information')) // Translated
                    ->description(__('Basic contact details and social media links.')) // Translated
                    ->schema([
                        Forms\Components\TextInput::make('cancellation_window')
                            ->label(__('Cancellation Window'))
                            ->numeric()
                            ->minValue(0)
                            ->required(),
                        // Forms\Components\TextInput::make('app_fee')
                        //     ->label(__('Application Fee'))
                        //     ->numeric()
                        //     ->suffix('%') // Translated
                        //     ->minValue(0)
                        //     ->required(),
                        // Forms\Components\TextInput::make('app_bank_name')
                        //     ->label(__('Bank Name')) // Translated
                        //     ->nullable(),
                        // Forms\Components\TextInput::make('app_bank_user_name')
                        //     ->label(__('Account Holder Name')) // Translated
                        //     ->nullable(),
                        // Forms\Components\TextInput::make('app_bank_iban')
                        //     ->label(__('IBAN')) // Translated
                        //     ->nullable(),
                        Forms\Components\TextInput::make('contact_phone')
                            ->label(__('Phone Number')) // Translated
                            ->tel()
                            ->nullable(),
                        Forms\Components\TextInput::make('contact_email')
                            ->label(__('Email Address')) // Translated
                            ->email()
                            ->nullable(),
                        Forms\Components\TextInput::make('social_facebook')
                            ->label(__('Facebook URL')) // Translated
                            ->url()
                            ->nullable(),
                        Forms\Components\TextInput::make('social_x')
                            ->label(__('X (Twitter) URL')) // Translated
                            ->url()
                            ->nullable(),
                        Forms\Components\TextInput::make('social_instagram')
                            ->label(__('Instagram URL')) // Translated
                            ->url()
                            ->nullable(),
                        Forms\Components\TextInput::make('social_snapchat')
                            ->label(__('Snapchat URL')) // Translated
                            ->url()
                            ->nullable(),
                        Forms\Components\TextInput::make('social_tiktok')
                            ->label(__('TikTok URL')) // Translated
                            ->url()
                            ->nullable(),

                    ])->columns(2),
            ]);
    }

    public function save(): void
    {
        try {
            $this->callHook('beforeValidate');

            $data = $this->form->getState();

            $this->callHook('afterValidate');

            $data = $this->mutateFormDataBeforeSave($data);

            $this->callHook('beforeSave');

            $settings = Setting::create(['key' => 'website']);

            // Manually assign the transformed data
            $settings->value_en = $data['value_en'];
            $settings->value_ar = $data['value_ar'];
            $settings->save();
            // if ($this->notify_users) {
            //     User::query()->update(['terms_and_conditions_accepted' => false]);
            // }

            $this->callHook('afterSave');
        } catch (Halt $exception) {
            return;
        }
        $this->getSavedNotification()?->send();
        if ($redirectUrl = $this->getRedirectUrl()) {
            $this->redirect($redirectUrl);
        }
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Transform flat form data into nested structure for 'value_en' and 'value_ar'
        $transformedData = [
            'value_en' => [
                'about_us' => $data['about_us_en'] ?? null,
                'terms_and_conditions' => $data['terms_and_conditions_en'] ?? null,
                'privacy_policy' => $data['privacy_policy_en'] ?? null,
                // 'payment_description' => $data['payment_description_en'] ?? null,
                // 'app_bank_name' => $data['app_bank_name'] ?? null,
                // 'app_bank_user_name' => $data['app_bank_user_name'] ?? null,
                // 'app_bank_iban' => $data['app_bank_iban'] ?? null,
                'contact_phone' => $data['contact_phone'] ?? null,
                'contact_email' => $data['contact_email'] ?? null,
                'social_facebook' => $data['social_facebook'] ?? null,
                'social_x' => $data['social_x'] ?? null,
                'social_instagram' => $data['social_instagram'] ?? null,
                'social_snapchat' => $data['social_snapchat'] ?? null,
                'social_tiktok' => $data['social_tiktok'] ?? null,
                'app_fee' => $data['app_fee'] ?? null,
                'cancellation_window' => $data['cancellation_window'] ?? null,
            ],
            'value_ar' => [
                'about_us' => $data['about_us_ar'] ?? null,
                'terms_and_conditions' => $data['terms_and_conditions_ar'] ?? null,
                'privacy_policy' => $data['privacy_policy_ar'] ?? null,
                // 'payment_description' => $data['payment_description_ar'] ?? null,
            ],
        ];

        // notify_users is if terms and conditions are updated
        if ($this->ar_terms != $data['terms_and_conditions_ar'] || $this->en_terms !== $data['terms_and_conditions_en']) {
            $this->notify_users = true;
        }

        return $transformedData;
    }

    protected function fillForm(): void
    {
        $this->callHook('beforeFill');

        $settings = Setting::where('key', 'website')->latest()->limit(1)->first();
        if (! $settings) {
            $settings = Setting::create(['key' => 'website']);
        }

        // Pass the settings as an array to mutateFormDataBeforeFill
        $data = $this->mutateFormDataBeforeFill($settings->toArray());

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

        $this->callHook('afterFill');
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        // Transform nested 'value_en' and 'value_ar' from Setting model into flat form data
        $transformedData = [];

        $valueEn = is_string($data['value_en'] ?? null) ? json_decode($data['value_en'], true) : ($data['value_en'] ?? []);
        $valueAr = is_string($data['value_ar'] ?? null) ? json_decode($data['value_ar'], true) : ($data['value_ar'] ?? []);

        $transformedData['about_us_en'] = $valueEn['about_us'] ?? null;
        $transformedData['terms_and_conditions_en'] = $valueEn['terms_and_conditions'] ?? null;
        $transformedData['privacy_policy_en'] = $valueEn['privacy_policy'] ?? null;
        // $transformedData['payment_description_en'] = $valueEn['payment_description'] ?? null;
        // $transformedData['app_bank_iban'] = $valueEn['app_bank_iban'] ?? null;
        // $transformedData['app_bank_name'] = $valueEn['app_bank_name'] ?? null;
        // $transformedData['app_bank_user_name'] = $valueEn['app_bank_user_name'] ?? null;
        $transformedData['contact_phone'] = $valueEn['contact_phone'] ?? null;
        $transformedData['contact_email'] = $valueEn['contact_email'] ?? null;
        $transformedData['social_facebook'] = $valueEn['social_facebook'] ?? null;
        $transformedData['social_x'] = $valueEn['social_x'] ?? null;
        $transformedData['social_instagram'] = $valueEn['social_instagram'] ?? null;
        $transformedData['social_snapchat'] = $valueEn['social_snapchat'] ?? null;
        $transformedData['social_tiktok'] = $valueEn['social_tiktok'] ?? null;
        $transformedData['app_fee'] = $valueEn['app_fee'] ?? null;
        $transformedData['cancellation_window'] = $valueEn['cancellation_window'] ?? null;

        $transformedData['about_us_ar'] = $valueAr['about_us'] ?? null;
        $transformedData['terms_and_conditions_ar'] = $valueAr['terms_and_conditions'] ?? null;
        $transformedData['privacy_policy_ar'] = $valueAr['privacy_policy'] ?? null;
        // $transformedData['payment_description_ar'] = $valueAr['payment_description'] ?? null;

        $this->ar_terms = $transformedData['terms_and_conditions_ar'];
        $this->en_terms = $transformedData['terms_and_conditions_en'];

        return $transformedData;
    }
}
