<?php

namespace App\Filament\Pages;

use App\Models\Setting;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
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;
use Filament\Forms\Components\Repeater;

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

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

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

    protected static string|\UnitEnum|null $navigationGroup = 'Site Builder';

    protected static ?string $title = 'Basic Information';

    protected static ?string $navigationLabel = 'General Settings';

    protected static ?int $navigationSort = 1;

    public ?array $data = [];

    public function mount()
    {
        $settings = [];
        foreach (Setting::all() as $setting) {
            $settings[$setting->key] = Setting::getValue($setting->key);
        }

        $mergedData = array_merge([
            // Basic Information
            'site_name' => 'Sawdabazar',
            'site_slogan' => 'Pure & Safe Food',
            'home_page_title' => 'Sawdabazar | Premium E-Commerce Store',
            'primary_brand_color' => '#003b20',
            'secondary_brand_color' => '#f37021',
            'currency_symbol' => '৳',
            'vat_percentage' => '0.0',
            'decimal_status' => 'on',
            'currency_direction' => 'left',
            'decimal_separator' => 'dot',
            'thousand_separator' => 'comma',

            // Home Page Themes
            'theme_preset' => 'classic',

            // Media
            'store_logo'      => '',
            'store_favicon'   => '',
            'store_loader'    => '',
            'display_loader'  => 'off',
            'admin_logo'      => '',
            'admin_favicon'   => '',

            // SEO
            'seo_title' => '',
            'seo_image' => '',
            'seo_keywords' => '',
            'seo_description' => '',

            // Custom CSS
            'custom_css' => '',

            // Shop & Checkout Page
            'cod_status' => 'on',
            'delivery_fee_inside_dhaka' => '60',
            'delivery_fee_outside_dhaka' => '120',
            'free_delivery_threshold' => '2000',
            'min_order_amount' => '0',

            // New settings from screenshot
            'show_category_on_header' => 'on',
            'enable_filter_by_attribute' => 'on',
            'enable_filter_by_price_range' => 'on',
            'product_attribute' => '',
            'view_product' => '16',
            'price_range_max' => '10000',
            'enable_single_page_checkout' => 'on',
            'enable_guest_checkout' => 'on',
            'enable_privacy_terms' => 'on',
            'privacy_policy_link' => 'http://localhost/my/omnimart3/privacy-policy',
            'terms_of_service_link' => 'http://localhost/my/omnimart3/terms-and-service',

            // Reviews Section Defaults
            'reviews_title' => 'আমাদের শুভাকাঙ্ক্ষীদের মতামত',
            'reviews_subtitle' => 'সওদাবাজারের সেবা ও পণ্যের মান নিয়ে গ্রাহকদের প্রকৃত রিভিউসমূহ',
            'reviews_list' => [
                [
                    'name' => 'সাজ্জাদ হোসেন',
                    'designation' => 'ধানমন্ডি, ঢাকা',
                    'rating' => 5,
                    'content' => 'সওদাবাজারের মধু এবং ঘিয়ের মান অসাধারণ! এর আগে আমি অনেক জায়গা থেকে কিনেছি কিন্তু এইরকম খাঁটি স্বাদ অন্য কোথাও পাইনি। আমার পুরো ফ্যামিলি এখন এটা রেগুলার খায়।',
                    'image' => null,
                ],
                [
                    'name' => 'আফসানা পারভীন',
                    'designation' => 'বনানী, ঢাকা',
                    'rating' => 5,
                    'content' => 'ডেলিভারি খুব দ্রুত পেয়েছি এবং প্যাকেজিং অসাধারণ ছিল। বিশেষ করে কাঁচের জারে প্যাকিং খুব সুন্দর ছিল যাতে ভাঙার কোনো ভয় নেই। পণ্যের বিশুদ্ধতার নিশ্চয়তা দারুণ লেগেছে।',
                    'image' => null,
                ],
                [
                    'name' => 'মাহমুদুল হাসান',
                    'designation' => 'উত্তরা, ঢাকা',
                    'rating' => 5,
                    'content' => 'সুন্দরবনের মৌচাকের প্রাকৃতিক মধু সত্যিই অসাধারণ। ঘ্রাণ এবং কালার দুটোই একদম পিওর ছিল। যেকোনো প্রাকৃতিক খাবারের জন্য সওদাবাজারের উপর পুরোপুরি ভরসা করা যায়।',
                    'image' => null,
                ],
            ],

            // Footer & Contact Page
            'store_phone' => '',
            'store_email' => '',
            'store_address' => '',
            'store_copyright' => '© ' . date('Y') . ' Sawdabazar. All rights reserved.',
            'store_description' => 'We are committed to delivering 100% pure, safe, and healthy food to our customers. Each of our products is sourced by verifying the highest quality standards.',
            'social_facebook' => '',
            'social_instagram' => '',
            'social_whatsapp' => '',
            'social_youtube' => '',
            'store_payment_image' => '',
        ], $settings);

        // Convert the toggle fields to boolean before filling the form
        $toggleKeys = [
            'show_category_on_header',
            'enable_filter_by_attribute',
            'enable_filter_by_price_range',
            'enable_single_page_checkout',
            'enable_guest_checkout',
            'enable_privacy_terms'
        ];

        foreach ($toggleKeys as $key) {
            if (isset($mergedData[$key])) {
                $mergedData[$key] = ($mergedData[$key] === 'on' || $mergedData[$key] === '1' || $mergedData[$key] === true || $mergedData[$key] === 1);
            }
        }

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

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Tabs::make('Site Settings Tabs')
                    ->tabs([
                        // Tab 1: Basic Information
                        Tabs\Tab::make('Basic Information')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                TextInput::make('site_name')
                                    ->label('App Name')
                                    ->required(),
                                TextInput::make('site_slogan')
                                    ->label('Site Slogan / Subtitle')
                                    ->placeholder('e.g. Pure & Safe Food')
                                    ->required(),
                                TextInput::make('home_page_title')
                                    ->label('Home Page Title')
                                    ->required(),
                                ColorPicker::make('primary_brand_color')
                                    ->label('Primary Colour Code')
                                    ->required(),
                                ColorPicker::make('secondary_brand_color')
                                    ->label('Secondary Colour Code (Orange)')
                                    ->required(),
                                TextInput::make('currency_symbol')
                                    ->label('Currency Symbol')
                                    ->default('৳')
                                    ->required(),
                                TextInput::make('vat_percentage')
                                    ->label('Default VAT (%)')
                                    ->numeric()
                                    ->default(0.0)
                                    ->required(),
                                Select::make('decimal_status')
                                    ->label('Decimal Separator (Status)')
                                    ->options([
                                        'on' => 'On',
                                        'off' => 'Off',
                                    ])
                                    ->required(),
                                Select::make('currency_direction')
                                    ->label('Currency Direction')
                                    ->options([
                                        'left' => 'Left ($100.00)',
                                        'right' => 'Right (100.00$)',
                                    ])
                                    ->required(),
                                Select::make('decimal_separator')
                                    ->label('Decimal Separator')
                                    ->options([
                                        'dot' => 'Dot (.)',
                                        'comma' => 'Comma (,)',
                                    ])
                                    ->required(),
                                Select::make('thousand_separator')
                                    ->label('Thousand Separator')
                                    ->options([
                                        'comma' => 'Comma (,)',
                                        'dot' => 'Dot (.)',
                                        'space' => 'Space ( )',
                                    ])
                                    ->required(),
                            ])->columns(2),

                        // Tab 2: Home Page Themes
                        Tabs\Tab::make('Home Page Themes')
                            ->icon('heroicon-o-paint-brush')
                            ->schema([
                                Hidden::make('theme_preset')
                                    ->required(),
                                Placeholder::make('theme_selector')
                                    ->hiddenLabel()
                                    ->content(fn () => view('filament.components.theme-selector'))
                                    ->columnSpanFull(),
                            ]),

                        // Tab 3: Media
                        Tabs\Tab::make('Media')
                            ->icon('heroicon-o-photo')
                            ->schema([
                                Hidden::make('store_logo'),
                                Hidden::make('store_favicon'),
                                Hidden::make('store_loader'),
                                Hidden::make('display_loader'),
                                Hidden::make('admin_logo'),
                                Hidden::make('admin_favicon'),
                                Placeholder::make('media_uploader')
                                    ->hiddenLabel()
                                    ->content(fn ($get) => view('filament.components.media-uploader', [
                                        'storeLogo'     => $get('store_logo'),
                                        'storeFavicon'  => $get('store_favicon'),
                                        'storeLoader'   => $get('store_loader'),
                                        'displayLoader' => $get('display_loader'),
                                    ]))
                                    ->columnSpanFull(),
                            ]),

                        // Tab 4: Seo
                        Tabs\Tab::make('Seo')
                            ->icon('heroicon-o-globe-alt')
                            ->schema([
                                TextInput::make('seo_title')
                                    ->label('Site Meta Title')
                                    ->placeholder('e.g. Sawdabazar | Pure & Safe Food')
                                    ->columnSpanFull(),
                                FileUpload::make('seo_image')
                                    ->label('Meta Image (OG Image)')
                                    ->helperText('Shown when your store link is shared on Facebook, WhatsApp, Twitter etc. Recommended: 1200x627px')
                                    ->image()
                                    ->directory('site-builder')
                                    ->disk(config('filesystems.default'))
                                    ->visibility('public')
                                    ->maxSize(2048)
                                    ->columnSpanFull(),
                                TextInput::make('seo_keywords')
                                    ->label('Site Meta Keywords')
                                    ->placeholder('e.g. food, organic, safe, grocery')
                                    ->helperText('Separate keywords with commas')
                                    ->columnSpanFull(),
                                Textarea::make('seo_description')
                                    ->label('Site Meta Description')
                                    ->placeholder('Provide a brief summary of your shop for search engines...')
                                    ->rows(5)
                                    ->columnSpanFull(),
                            ]),


                        // Tab 5: Custom Css
                        Tabs\Tab::make('Custom Css')
                            ->icon('heroicon-o-code-bracket')
                            ->schema([
                                Textarea::make('custom_css')
                                    ->label('Custom CSS Injection')
                                    ->rows(15)
                                    ->placeholder('/* Add your custom CSS rules here */')
                            ]),

                        // Tab 6: Shop & Checkout Page
                        Tabs\Tab::make('Shop & Checkout Page')
                            ->icon('heroicon-o-shopping-bag')
                            ->schema([
                                Section::make('Shop Page Settings')
                                    ->schema([
                                        Toggle::make('show_category_on_header')
                                            ->label('Show Category On Header')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        Toggle::make('enable_filter_by_attribute')
                                            ->label('Enable Filter By Attribute & Attribute Options')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        Toggle::make('enable_filter_by_price_range')
                                            ->label('Enable Filter By Price Range')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        TextInput::make('view_product')
                                            ->label('Products Per Page')
                                            ->numeric()
                                            ->required(),
                                        TextInput::make('price_range_max')
                                            ->label('Price Range Max')
                                            ->numeric()
                                            ->required(),
                                    ])->columns(1),

                                Section::make('Checkout Page Settings')
                                    ->schema([
                                        Toggle::make('enable_single_page_checkout')
                                            ->label('Enable Single Page Checkout')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        Toggle::make('enable_guest_checkout')
                                            ->label('Enable Guest Checkout')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        Toggle::make('enable_privacy_terms')
                                            ->label('Enable Privacy & Terms Conditions')
                                            ->dehydrateStateUsing(fn ($state) => $state ? 'on' : 'off')
                                            ->formatStateUsing(fn ($state) => $state === 'on' || $state === '1' || $state === true || $state === 1)
                                            ->inline(false),
                                        TextInput::make('privacy_policy_link')
                                            ->label('Privacy Policy Link')
                                            ->url()
                                            ->required(),
                                        TextInput::make('terms_of_service_link')
                                            ->label('Terms of Service Link')
                                            ->url()
                                            ->required(),
                                    ])->columns(1),
                            ]),

                        Tabs\Tab::make('Customer Reviews')
                            ->icon('heroicon-o-chat-bubble-bottom-center-text')
                            ->schema([
                                TextInput::make('reviews_title')
                                    ->label('Reviews Title')
                                    ->placeholder('e.g. আমাদের শুভাকাঙ্ক্ষীদের মতামত')
                                    ->required(),
                                TextInput::make('reviews_subtitle')
                                    ->label('Reviews Subtitle / Description')
                                    ->placeholder('e.g. সওদাবাজারের সেবা ও পণ্যের মান নিয়ে গ্রাহকদের প্রকৃত রিভিউসমূহ')
                                    ->required(),
                                Repeater::make('reviews_list')
                                    ->label('Reviews list')
                                    ->schema([
                                        TextInput::make('name')
                                            ->label('Reviewer Name')
                                            ->required(),
                                        TextInput::make('designation')
                                            ->label('Reviewer Designation / Location')
                                            ->placeholder('e.g. ধানমন্ডি, ঢাকা')
                                            ->required(),
                                        Select::make('rating')
                                            ->label('Rating (Stars)')
                                            ->options([
                                                1 => '1 Star',
                                                2 => '2 Stars',
                                                3 => '3 Stars',
                                                4 => '4 Stars',
                                                5 => '5 Stars',
                                            ])
                                            ->default(5)
                                            ->required(),
                                        Textarea::make('content')
                                            ->label('Review Content')
                                            ->rows(3)
                                            ->required(),
                                        FileUpload::make('image')
                                            ->label('Reviewer Photo')
                                            ->image()
                                            ->directory('reviews')
                                            ->disk(config('filesystems.default'))
                                            ->visibility('public'),
                                    ])
                                    ->columns(2)
                                    ->defaultItems(3)
                                    ->reorderable()
                                    ->cloneable()
                                    ->collapsible()
                                    ->collapsed()
                                    ->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
                                    ->columnSpanFull(),
                            ]),

                        // Tab 8: Footer & Contact Page
                        Tabs\Tab::make('Footer & Contact Page')
                            ->icon('heroicon-o-envelope')
                            ->schema([
                                TextInput::make('store_phone')
                                    ->label('Contact Phone')
                                    ->tel(),
                                TextInput::make('store_email')
                                    ->label('Contact Email')
                                    ->email(),
                                Textarea::make('store_address')
                                    ->label('Store Address')
                                    ->rows(3)
                                    ->columnSpanFull(),
                                Textarea::make('store_description')
                                    ->label('Store Footer Description')
                                    ->rows(3)
                                    ->columnSpanFull(),
                                TextInput::make('store_copyright')
                                    ->label('Copyright Text')
                                    ->columnSpanFull(),
                                TextInput::make('social_facebook')
                                    ->label('Facebook Page URL')
                                    ->url(),
                                TextInput::make('social_instagram')
                                    ->label('Instagram URL')
                                    ->url(),
                                TextInput::make('social_whatsapp')
                                    ->label('WhatsApp Number')
                                    ->helperText('Include country code, e.g. 88017XXXXXXXX'),
                                TextInput::make('social_youtube')
                                    ->label('YouTube Channel URL')
                                    ->url(),
                                FileUpload::make('store_payment_image')
                                    ->label('Footer Payment Methods Banner')
                                    ->image()
                                    ->directory('settings')
                                    ->columnSpanFull(),
                            ])->columns(2),

                    ])
                    ->vertical()
                    ->columnSpanFull()
            ])
            ->statePath('data');
    }

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

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

        foreach ($state as $key => $value) {
            $group = 'site_builder';
            if ($key === 'currency_symbol' || $key === 'vat_percentage') {
                $group = 'general';
            }

            // Normalize boolean Toggle states to 'on' / 'off'
            if (is_bool($value)) {
                $value = $value ? 'on' : 'off';
            }

            Setting::setValue($key, $value, $group);
        }

        // Trigger Cache clear
        Setting::clearCache();

        Notification::make()
            ->title('Basic Information Saved')
            ->body('Storefront site builder settings have been updated successfully.')
            ->success()
            ->send();
    }
}
