<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Placeholder;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\HtmlString;

class BrandSettings extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-adjustments-horizontal';
    protected string $view = 'filament.pages.brand-settings';
    protected static ?int $navigationSort = 7;
    protected static ?string $title = 'Brand & System Settings';

    public function editGeneralAction(): Action
    {
        return Action::make('editGeneral')
            ->modalHeading('General Brand Settings')
            ->modalWidth('lg')
            ->fillForm([
                'brand_name' => setting('brand_name', 'AroraPay'),
                'brand_title' => setting('brand_title', 'Secure Payment Gateway'),
                'support_email' => setting('support_email'),
                'support_phone' => setting('support_phone'),
                'currency' => setting('currency', 'BDT'),
                'currency_symbol' => setting('currency_symbol', '৳'),
                'usd_rate' => setting('usd_rate', '115'),
                'footer_text' => setting('footer_text', 'All rights reserved.'),
            ])
            ->form([
                TextInput::make('brand_name')->label('Brand / Company Name')->required(),
                TextInput::make('brand_title')->label('Tagline / Brand Slogan')->placeholder('e.g. Secure & Fast Payment Gateway'),
                TextInput::make('support_email')->label('Customer Support Email')->email(),
                TextInput::make('support_phone')->label('Support Phone / WhatsApp'),
                TextInput::make('currency')->label('Default Currency Code')->default('BDT')->required(),
                TextInput::make('currency_symbol')->label('Currency Symbol')->default('৳')->required(),
                TextInput::make('usd_rate')
                    ->label('USD Exchange Rate (1 USD = ? BDT)')
                    ->numeric()
                    ->required()
                    ->default(115),
                TextInput::make('footer_text')->label('Footer Copyright Notice')->placeholder('e.g. © 2026 AroraPay. All rights reserved.'),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('General settings updated successfully.')->success()->send();
                $this->js('window.location.reload()');
            });
    }

    public function editLogoAction(): Action
    {
        return Action::make('editLogo')
            ->modalHeading('Logo & Favicon Customization')
            ->modalWidth('xl')
            ->fillForm(function () {
                $logo = setting('brand_logo');
                $favicon = setting('brand_favicon');
                $invoiceLogo = setting('invoice_logo');

                return [
                    'brand_logo' => ($logo && file_exists(public_path('uploads/' . $logo))) ? $logo : null,
                    'brand_favicon' => ($favicon && file_exists(public_path('uploads/' . $favicon))) ? $favicon : null,
                    'invoice_logo' => ($invoiceLogo && file_exists(public_path('uploads/' . $invoiceLogo))) ? $invoiceLogo : null,
                ];
            })
            ->form([
                Placeholder::make('current_logo_preview')
                    ->label('Current Brand Logo')
                    ->content(function () {
                        $logo = setting('brand_logo');
                        if ($logo && file_exists(public_path('uploads/' . $logo))) {
                            return new HtmlString(
                                '<div style="padding: 12px 16px; background: rgba(15, 23, 42, 0.6); border: 1px dashed rgba(148, 163, 184, 0.3); border-radius: 12px; display: inline-flex; align-items: center; gap: 16px;">'
                                . '<img src="' . asset('uploads/' . $logo) . '" style="max-height: 48px; max-width: 160px; object-fit: contain;">'
                                . '<div><span style="font-size: 12px; color: #10b981; font-weight: 700; display: block;">✓ Active Logo</span><span style="font-size: 11px; color: #94a3b8;">' . htmlspecialchars($logo) . '</span></div>'
                                . '</div>'
                            );
                        }
                        return new HtmlString('<div style="font-size: 12px; color: #94a3b8; font-style: italic;">No custom logo uploaded yet. Upload one below.</div>');
                    }),

                FileUpload::make('brand_logo')
                    ->label('Upload Main Logo')
                    ->disk('uploads')
                    ->directory('brand')
                    ->visibility('public')
                    ->image()
                    ->imageEditor()
                    ->imagePreviewHeight('120px')
                    ->openable()
                    ->downloadable()
                    ->maxSize(5120)
                    ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'])
                    ->helperText('Recommended: Transparent PNG or SVG. Max height: 60px.'),

                Placeholder::make('current_favicon_preview')
                    ->label('Current Favicon')
                    ->content(function () {
                        $favicon = setting('brand_favicon');
                        if ($favicon && file_exists(public_path('uploads/' . $favicon))) {
                            return new HtmlString(
                                '<div style="padding: 10px 14px; background: rgba(15, 23, 42, 0.6); border: 1px dashed rgba(148, 163, 184, 0.3); border-radius: 12px; display: inline-flex; align-items: center; gap: 12px;">'
                                . '<img src="' . asset('uploads/' . $favicon) . '" style="width: 32px; height: 32px; object-fit: contain;">'
                                . '<div><span style="font-size: 12px; color: #10b981; font-weight: 700; display: block;">✓ Active Favicon</span><span style="font-size: 11px; color: #94a3b8;">' . htmlspecialchars($favicon) . '</span></div>'
                                . '</div>'
                            );
                        }
                        return new HtmlString('<div style="font-size: 12px; color: #94a3b8; font-style: italic;">No custom favicon uploaded. Upload one below.</div>');
                    }),

                FileUpload::make('brand_favicon')
                    ->label('Upload Browser Favicon')
                    ->disk('uploads')
                    ->directory('brand')
                    ->visibility('public')
                    ->image()
                    ->imageEditor()
                    ->imagePreviewHeight('80px')
                    ->openable()
                    ->downloadable()
                    ->maxSize(2048)
                    ->acceptedFileTypes(['image/png', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/svg+xml', 'image/webp'])
                    ->helperText('Recommended: 32x32 or 64x64 PNG or ICO icon.'),

                FileUpload::make('invoice_logo')
                    ->label('Receipt / Invoice Logo (Optional)')
                    ->disk('uploads')
                    ->directory('brand')
                    ->visibility('public')
                    ->image()
                    ->imageEditor()
                    ->imagePreviewHeight('100px')
                    ->openable()
                    ->downloadable()
                    ->maxSize(5120)
                    ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'])
                    ->helperText('Optional separate logo for email receipts and invoices.'),
            ])
            ->action(function (array $data) {
                if (array_key_exists('brand_logo', $data) && !empty($data['brand_logo'])) {
                    set_setting('brand_logo', $data['brand_logo']);
                }
                if (array_key_exists('brand_favicon', $data) && !empty($data['brand_favicon'])) {
                    set_setting('brand_favicon', $data['brand_favicon']);
                }
                if (array_key_exists('invoice_logo', $data) && !empty($data['invoice_logo'])) {
                    set_setting('invoice_logo', $data['invoice_logo']);
                }
                Notification::make()->title('Logo & Favicon updated successfully.')->success()->send();
                $this->js('window.location.reload()');
            });
    }

    public function editMailAction(): Action
    {
        return Action::make('editMail')
            ->modalHeading('Mail & SMTP Settings')
            ->modalWidth('xl')
            ->fillForm([
                'mail_host' => setting('mail_host', 'smtp.gmail.com'),
                'mail_port' => setting('mail_port', '587'),
                'mail_username' => setting('mail_username'),
                'mail_password' => setting('mail_password'),
                'mail_encryption' => setting('mail_encryption', 'tls'),
                'mail_from_address' => setting('mail_from_address'),
                'mail_from_name' => setting('mail_from_name', setting('brand_name', 'AroraPay')),
                'admin_alert_email' => setting('admin_alert_email', setting('support_email')),
                'customer_mail_notification' => (bool) setting('customer_mail_notification', 1),
            ])
            ->form([
                TextInput::make('mail_host')->label('SMTP Host')->placeholder('smtp.gmail.com or mail.yourdomain.com')->required(),
                TextInput::make('mail_port')->label('SMTP Port')->numeric()->default(587)->required(),
                TextInput::make('mail_username')->label('SMTP Username / Email')->required(),
                TextInput::make('mail_password')->label('SMTP Password / App Password')->password()->revealable()->required(),
                Select::make('mail_encryption')
                    ->label('Encryption')
                    ->options([
                        'tls' => 'TLS (Recommended)',
                        'ssl' => 'SSL',
                        'none' => 'None',
                    ])
                    ->default('tls')
                    ->required(),
                TextInput::make('mail_from_address')->label('From Email Address')->placeholder('noreply@yourdomain.com'),
                TextInput::make('mail_from_name')->label('From Sender Name')->placeholder('AroraPay Notifications'),
                TextInput::make('admin_alert_email')
                    ->label('Admin Payment Alert Email (Send Notifications To)')
                    ->helperText('All new payment receipts will be sent to this email address')
                    ->email()
                    ->required(),
                Toggle::make('customer_mail_notification')
                    ->label('Send Payment Receipt to Customer')
                    ->helperText('Automatically send an email receipt when customer email is provided')
                    ->default(true),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('Mail & SMTP settings saved.')->success()->send();
            });
    }

    public function editTelegramAction(): Action
    {
        return Action::make('editTelegram')
            ->modalHeading('Telegram Notification Settings')
            ->modalWidth('lg')
            ->fillForm([
                'telegram_enabled' => (bool) setting('telegram_enabled', 1),
                'telegram_bot_token' => setting('telegram_bot_token'),
                'telegram_chat_id' => setting('telegram_chat_id'),
            ])
            ->form([
                Toggle::make('telegram_enabled')->label('Enable Telegram Instant Notifications')->default(true),
                TextInput::make('telegram_bot_token')
                    ->label('Telegram Bot Token')
                    ->placeholder('123456789:ABCdefGHIjklMNOpqrSTUvwxYZ')
                    ->helperText('Create a bot on Telegram via @BotFather to get this token')
                    ->required(),
                TextInput::make('telegram_chat_id')
                    ->label('Telegram Chat ID / Group ID')
                    ->placeholder('123456789 or -100123456789')
                    ->helperText('Your personal Telegram ID or group/channel ID where alerts are sent')
                    ->required(),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }

                // Send test message if credentials provided
                if (!empty($data['telegram_bot_token']) && !empty($data['telegram_chat_id'])) {
                    try {
                        Http::timeout(5)->post("https://api.telegram.org/bot{$data['telegram_bot_token']}/sendMessage", [
                            'chat_id' => $data['telegram_chat_id'],
                            'text' => "🎉 *Telegram Notifications Connected!*\n\nYour " . setting('brand_name', 'Payment Gateway') . " is now connected to Telegram. You will receive live payment alerts here.",
                            'parse_mode' => 'Markdown',
                        ]);
                        Notification::make()->title('Telegram settings saved & test notification sent!')->success()->send();
                    } catch (\Exception $e) {
                        Notification::make()->title('Settings saved, but test message failed. Check token/Chat ID.')->warning()->send();
                    }
                } else {
                    Notification::make()->title('Telegram settings saved.')->success()->send();
                }
            });
    }

    public function editThemesAction(): Action
    {
        return Action::make('editThemes')
            ->modalHeading('Theme & Appearance Settings')
            ->modalWidth('lg')
            ->fillForm([
                'default_theme' => setting('default_theme', 'dark'),
                'primary_color' => setting('primary_color', '#6366f1'),
                'show_theme_toggle' => (bool) setting('show_theme_toggle', 1),
                'checkout_theme_layout' => setting('checkout_theme_layout', 'modern_card'),
            ])
            ->form([
                Select::make('default_theme')
                    ->label('Default Website / Checkout Theme')
                    ->options([
                        'dark' => '🌙 Dark Theme (Recommended)',
                        'light' => '☀️ Light Theme',
                        'system' => '💻 System / Auto',
                    ])
                    ->default('dark')
                    ->required(),
                ColorPicker::make('primary_color')
                    ->label('Brand Primary Accent Color')
                    ->default('#6366f1'),
                Toggle::make('show_theme_toggle')
                    ->label('Show Theme Switcher (Dark/Light Button) on Checkout Page')
                    ->default(true),
                Select::make('checkout_theme_layout')
                    ->label('Checkout Page Style')
                    ->options([
                        'modern_card' => 'Modern Floating Card',
                        'minimal' => 'Minimal Compact Layout',
                        'glass' => 'Glassmorphism Style',
                    ])
                    ->default('modern_card'),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('Theme settings updated successfully.')->success()->send();
                $this->js('window.location.reload()');
            });
    }

    public function editFaqAction(): Action
    {
        return Action::make('editFaq')
            ->modalHeading('Frequently Asked Questions (FAQ)')
            ->modalWidth('2xl')
            ->fillForm([
                'show_faq_on_checkout' => (bool) setting('show_faq_on_checkout', 1),
                'faqs' => setting('faqs', [
                    [
                        'question' => 'How does the automatic verification work?',
                        'answer' => 'After completing your transaction via bKash, Nagad, or Rocket, enter your TrxID. Our system automatically matches it within seconds.',
                    ],
                    [
                        'question' => 'How long does it take to verify?',
                        'answer' => 'Verification usually completes instantly (within 5 to 30 seconds).',
                    ],
                    [
                        'question' => 'What if my TrxID is not verified?',
                        'answer' => 'Please double check your TrxID and Sender Number. If you need help, contact our support team.',
                    ],
                ]),
            ])
            ->form([
                Toggle::make('show_faq_on_checkout')
                    ->label('Display FAQ Section on Checkout Page')
                    ->helperText('Allows customers to view answers to common questions directly on checkout')
                    ->default(true),
                Repeater::make('faqs')
                    ->label('FAQ Items')
                    ->schema([
                        TextInput::make('question')->label('Question')->required(),
                        Textarea::make('answer')->label('Answer')->rows(3)->required(),
                    ])
                    ->collapsible()
                    ->itemLabel(fn (array $state): ?string => $state['question'] ?? 'New FAQ')
                    ->defaultItems(2),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('FAQ settings saved successfully.')->success()->send();
            });
    }

    public function editSeoAction(): Action
    {
        return Action::make('editSeo')
            ->modalHeading('Search Engine Optimization (SEO) Settings')
            ->modalWidth('xl')
            ->fillForm([
                'seo_meta_title' => setting('seo_meta_title', setting('brand_name', 'AroraPay') . ' - Fast & Secure Payment Gateway'),
                'seo_meta_description' => setting('seo_meta_description', 'Accept and verify automated bKash, Nagad, and Rocket payments with instant webhook confirmations.'),
                'seo_meta_keywords' => setting('seo_meta_keywords', 'payment gateway, bKash auto verify, Nagad merchant, Bangladesh payment gateway'),
                'seo_og_image' => setting('seo_og_image'),
                'google_analytics_id' => setting('google_analytics_id'),
            ])
            ->form([
                TextInput::make('seo_meta_title')
                    ->label('Meta Title')
                    ->required(),
                Textarea::make('seo_meta_description')
                    ->label('Meta Description')
                    ->rows(3)
                    ->helperText('Recommended: 150-160 characters'),
                TextInput::make('seo_meta_keywords')
                    ->label('Meta Keywords')
                    ->placeholder('e.g. payment, bkash, nagad, rocket, checkout'),
                FileUpload::make('seo_og_image')
                    ->disk('uploads')
                    ->image()
                    ->directory('seo')
                    ->label('Social Sharing Image (OG Image)')
                    ->helperText('Recommended size: 1200x630 pixels'),
                TextInput::make('google_analytics_id')
                    ->label('Google Analytics Measurement ID')
                    ->placeholder('e.g. G-XXXXXXXXXX'),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('SEO settings updated.')->success()->send();
            });
    }

    public function editApiAction(): Action
    {
        return Action::make('editApi')
            ->modalHeading('API & Webhook Configuration')
            ->modalWidth('lg')
            ->fillForm([
                'api_webhook_secret' => setting('api_webhook_secret', \Illuminate\Support\Str::random(32)),
                'ipn_timeout_seconds' => setting('ipn_timeout_seconds', '30'),
                'sandbox_mode' => (bool) setting('sandbox_mode', 0),
            ])
            ->form([
                TextInput::make('api_webhook_secret')
                    ->label('Default Webhook Secret')
                    ->helperText('Secret key used for signing webhook callbacks'),
                TextInput::make('ipn_timeout_seconds')
                    ->label('Webhook / IPN Request Timeout (seconds)')
                    ->numeric()
                    ->default(30)
                    ->required(),
                Toggle::make('sandbox_mode')
                    ->label('Enable Sandbox / Test Mode')
                    ->helperText('When enabled, test payments will not process real monetary transactions'),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('API settings updated.')->success()->send();
            });
    }

    public function editMetaPixelAction(): Action
    {
        return Action::make('editMetaPixel')
            ->modalHeading('Meta Pixel & CAPI Settings')
            ->modalWidth('lg')
            ->fillForm([
                'meta_pixel_enabled' => (bool) setting('meta_pixel_enabled', 0),
                'meta_pixel_id' => setting('meta_pixel_id'),
                'meta_pixel_access_token' => setting('meta_pixel_access_token'),
                'meta_pixel_test_code' => setting('meta_pixel_test_code'),
            ])
            ->form([
                Toggle::make('meta_pixel_enabled')
                    ->label('Enable Meta Pixel & Conversion API')
                    ->default(false),
                TextInput::make('meta_pixel_id')
                    ->label('Meta Pixel ID')
                    ->placeholder('e.g. 123456789012345'),
                TextInput::make('meta_pixel_access_token')
                    ->label('Conversion API Access Token')
                    ->password()
                    ->revealable(),
                TextInput::make('meta_pixel_test_code')
                    ->label('Test Event Code (Optional)')
                    ->placeholder('e.g. TEST12345'),
            ])
            ->action(function (array $data) {
                foreach ($data as $key => $value) {
                    set_setting($key, $value);
                }
                Notification::make()->title('Meta Pixel settings updated.')->success()->send();
            });
    }
}
