<?php

namespace App\Filament\Pages;

use App\Models\BlogPost;
use App\Models\ClickLog;
use App\Models\Link;
use App\Models\PaymentTransaction;
use App\Models\Plan;
use App\Models\User;
use App\Services\MailSettings;
use App\Services\WebsiteSettings;
use Composer\InstalledVersions;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Callout;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\HtmlString;
use PDO;
use Throwable;
use UnitEnum;

class About extends Page
{
    protected static string|UnitEnum|null $navigationGroup = 'About';

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

    protected static ?int $navigationSort = 999;

    protected static ?string $navigationLabel = 'About';

    protected static ?string $slug = 'about';

    protected string $view = 'filament-panels::pages.page';

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

    public function mount(): void
    {
        $this->form->fill([
            'test' => [
                'email' => auth()->user()?->email,
                'subject' => 'urless mail test',
                'message' => 'This is a test email from the urless admin About page.',
            ],
        ]);
    }

    public function defaultForm(Schema $schema): Schema
    {
        return $schema
            ->statePath('data');
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Tabs::make('About urless')
                    ->persistTabInQueryString('about_tab')
                    ->columnSpanFull()
                    ->tabs([
                        Tab::make('Project')
                            ->icon('heroicon-m-information-circle')
                            ->schema([
                                Callout::make('urless platform')
                                    ->info()
                                    ->description('Advanced URL shortener, monetized redirect platform, realtime analytics dashboard, CMS, subscriptions, and admin control panel.'),

                                Section::make('Project snapshot')
                                    ->schema([
                                        Placeholder::make('project_snapshot')
                                            ->hiddenLabel()
                                            ->content(fn (): HtmlString => new HtmlString($this->projectSnapshotHtml()))
                                            ->columnSpanFull(),
                                    ]),
                            ]),

                        Tab::make('Stack & Versions')
                            ->icon('heroicon-m-cpu-chip')
                            ->schema([
                                Section::make('Frameworks, languages, and services')
                                    ->description('Runtime versions and key package versions detected from Composer, package.json, and the running Laravel app.')
                                    ->schema([
                                        Placeholder::make('stack_versions')
                                            ->hiddenLabel()
                                            ->content(fn (): HtmlString => new HtmlString($this->stackVersionsHtml()))
                                            ->columnSpanFull(),
                                    ]),
                            ]),

                        Tab::make('Mail Test')
                            ->icon('heroicon-m-envelope')
                            ->schema([
                                Section::make('Current mail sender')
                                    ->description('Use this section to confirm the active mailer after changing Admin > Settings > Mailer.')
                                    ->schema([
                                        Placeholder::make('mailer_overview')
                                            ->hiddenLabel()
                                            ->content(fn (): HtmlString => new HtmlString($this->mailerOverviewHtml()))
                                            ->columnSpanFull(),
                                    ]),

                                Section::make('Send test email')
                                    ->columns(2)
                                    ->schema([
                                        TextInput::make('test.email')
                                            ->label('Recipient email')
                                            ->email()
                                            ->required(),

                                        TextInput::make('test.subject')
                                            ->label('Subject')
                                            ->required()
                                            ->maxLength(120),

                                        Textarea::make('test.message')
                                            ->label('Message')
                                            ->rows(5)
                                            ->required()
                                            ->columnSpanFull(),
                                    ]),
                            ]),
                    ]),
            ]);
    }

    public function sendTestEmail(MailSettings $mailSettings): void
    {
        $state = $this->form->getState()['test'] ?? [];

        $validated = Validator::make($state, [
            'email' => ['required', 'email'],
            'subject' => ['required', 'string', 'max:120'],
            'message' => ['required', 'string', 'max:2000'],
        ])->validate();

        $mailSettings->apply();

        if ($mailSettings->isLogOnlyDriver()) {
            Notification::make()
                ->title('Mailer is log-only')
                ->body($mailSettings->logOnlyDeliveryMessage('No inbox email was sent.'))
                ->warning()
                ->send();

            return;
        }

        $html = $this->testEmailHtml($validated['message']);
        $text = (string) $validated['message'];

        try {
            Mail::send([
                'html' => 'emails.raw-html',
                'text' => 'emails.raw-text',
            ], [
                'html' => $html,
                'text' => $text,
            ], function ($message) use ($validated): void {
                $message
                    ->to($validated['email'])
                    ->subject($validated['subject']);
            });
        } catch (Throwable $exception) {
            report($exception);

            Notification::make()
                ->title('Test email could not be sent')
                ->body($mailSettings->deliveryFailureMessage($exception, 'Mail sender test failed.'))
                ->danger()
                ->send();

            return;
        }

        Notification::make()
            ->title('Test email sent')
            ->body('Mailer: '.config('mail.default').' | Recipient: '.$validated['email'])
            ->success()
            ->send();
    }

    public function content(Schema $schema): Schema
    {
        return $schema
            ->components([
                $this->getFormContentComponent(),
            ]);
    }

    public function getFormContentComponent(): Component
    {
        return Form::make([EmbeddedSchema::make('form')])
            ->id('form')
            ->livewireSubmitHandler('sendTestEmail')
            ->footer([
                Actions::make($this->getFormActions())
                    ->key('form-actions'),
            ]);
    }

    /**
     * @return array<Action|ActionGroup>
     */
    protected function getFormActions(): array
    {
        return [
            Action::make('sendTestEmail')
                ->label('Send mail test')
                ->icon('heroicon-m-paper-airplane')
                ->submit('sendTestEmail'),
        ];
    }

    private function projectSnapshotHtml(): string
    {
        $settings = app(WebsiteSettings::class)->settings();
        $siteName = e($settings['site_name'] ?? config('app.name', 'urless'));
        $appUrl = e((string) config('app.url'));
        $environment = e((string) app()->environment());

        $stats = [
            ['Users', User::query()->count(), '#4648d4'],
            ['Short links', Link::query()->count(), '#006c49'],
            ['Click logs', ClickLog::query()->count(), '#0f172a'],
            ['Plans', Plan::query()->count(), '#7c3aed'],
            ['Blog posts', BlogPost::query()->count(), '#0284c7'],
            ['Transactions', PaymentTransaction::query()->count(), '#d97706'],
        ];

        $statsHtml = collect($stats)
            ->map(function (array $stat): string {
                [$label, $value, $color] = $stat;

                return '<article class="urless-about-card" style="--accent: '.$color.'"><span>'.e($label).'</span><strong>'.number_format((int) $value).'</strong></article>';
            })
            ->implode('');

        return <<<HTML
            {$this->aboutStyles()}
            <div class="urless-about">
                <section class="urless-about-hero">
                    <span class="urless-about-pill">Project identity</span>
                    <h2>{$siteName}</h2>
                    <p>Advanced URL shortener and monetized redirect platform built with Laravel, Filament, Livewire, Blade, Tailwind CSS, Stripe, realtime click analytics, CMS, and admin-managed plans.</p>
                    <div class="urless-about-meta">
                        <span>URL: {$appUrl}</span>
                        <span>Environment: {$environment}</span>
                    </div>
                </section>

                <section class="urless-about-grid">
                    {$statsHtml}
                </section>
            </div>
        HTML;
    }

    private function stackVersionsHtml(): string
    {
        $packageJson = $this->packageJson();
        $devDependencies = $packageJson['devDependencies'] ?? [];

        $items = [
            ['PHP', PHP_VERSION, 'Language runtime'],
            ['Laravel', app()->version(), 'Backend framework'],
            ['Filament', $this->composerVersion('filament/filament'), 'Admin panel'],
            ['Livewire', $this->composerVersion('livewire/livewire'), 'Reactive UI'],
            ['Livewire Volt', $this->composerVersion('livewire/volt'), 'User dashboard stack'],
            ['Laravel Sanctum', $this->composerVersion('laravel/sanctum'), 'API tokens'],
            ['Spatie Permission', $this->composerVersion('spatie/laravel-permission'), 'Roles and permissions'],
            ['Stripe PHP', $this->composerVersion('stripe/stripe-php'), 'Subscriptions and checkout'],
            ['Stevebauman Location', $this->composerVersion('stevebauman/location'), 'GeoIP lookup'],
            ['Tailwind CSS', $devDependencies['tailwindcss'] ?? 'Installed', 'Frontend styling'],
            ['Alpine.js', $devDependencies['alpinejs'] ?? 'Installed', 'Frontend interaction'],
            ['Vite', $devDependencies['vite'] ?? 'Installed', 'Asset bundling'],
            ['Database', config('database.default').' '.$this->databaseVersion(), 'Storage'],
            ['Queue', (string) config('queue.default'), 'Background jobs'],
            ['Cache', (string) config('cache.default'), 'Caching'],
            ['Mailer', (string) config('mail.default'), 'Current sender'],
        ];

        $rows = collect($items)->map(function (array $item): string {
            [$name, $version, $description] = array_map(fn (mixed $value): string => e((string) $value), $item);

            return <<<HTML
                <tr>
                    <td>{$name}</td>
                    <td><strong>{$version}</strong></td>
                    <td>{$description}</td>
                </tr>
            HTML;
        })->implode('');

        return <<<HTML
            {$this->aboutStyles()}
            <div class="urless-about-table-wrap">
                <table class="urless-about-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Version / Driver</th>
                            <th>Used for</th>
                        </tr>
                    </thead>
                    <tbody>
                        {$rows}
                    </tbody>
                </table>
            </div>
        HTML;
    }

    private function mailerOverviewHtml(): string
    {
        $settings = app(MailSettings::class)->settings();
        $driver = e((string) ($settings['driver'] ?? config('mail.default')));
        $activeMailer = e((string) config('mail.default'));
        $host = e((string) ($settings['host'] ?? config('mail.mailers.smtp.host', '')));
        $port = e((string) ($settings['port'] ?? config('mail.mailers.smtp.port', '')));
        $from = e(($settings['from_name'] ?? config('mail.from.name')).' <'.($settings['from_address'] ?? config('mail.from.address')).'>');
        $username = e((string) ($settings['username'] ?: 'Not set'));
        $debugNote = app()->environment('local') || config('app.debug')
            ? '<p class="urless-about-note">Local/debug mode shows detailed mailer errors when delivery fails.</p>'
            : '<p class="urless-about-note">Production mode hides detailed mailer errors from users.</p>';

        return <<<HTML
            {$this->aboutStyles()}
            <div class="urless-mail-grid">
                <article>
                    <span>Admin selected driver</span>
                    <strong>{$driver}</strong>
                </article>
                <article>
                    <span>Laravel active mailer</span>
                    <strong>{$activeMailer}</strong>
                </article>
                <article>
                    <span>SMTP host</span>
                    <strong>{$host}:{$port}</strong>
                </article>
                <article>
                    <span>SMTP username</span>
                    <strong>{$username}</strong>
                </article>
                <article class="is-wide">
                    <span>From address</span>
                    <strong>{$from}</strong>
                </article>
            </div>
            {$debugNote}
        HTML;
    }

    private function testEmailHtml(string $message): string
    {
        $message = nl2br(e($message));
        $siteName = e((string) (app(WebsiteSettings::class)->settings()['site_name'] ?? 'urless'));
        $now = e(now()->format('M d, Y h:i A'));

        return <<<HTML
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f7f9fb;padding:32px;font-family:Inter,Arial,sans-serif;color:#191c1e;">
                <tr>
                    <td align="center">
                        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:620px;background:#ffffff;border:1px solid #e0e3e5;border-radius:8px;overflow:hidden;">
                            <tr>
                                <td style="padding:24px 28px;background:#4648d4;color:#ffffff;">
                                    <div style="font-size:22px;font-weight:900;">{$siteName}</div>
                                    <div style="margin-top:6px;font-size:12px;font-weight:800;text-transform:uppercase;color:#e1e0ff;">Admin mail sender test</div>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding:28px;">
                                    <h1 style="margin:0 0 16px;font-size:28px;line-height:1.2;font-weight:900;color:#191c1e;">Mail delivery is being tested</h1>
                                    <p style="margin:0 0 18px;color:#515f74;font-size:16px;line-height:1.7;">{$message}</p>
                                    <p style="margin:0;padding:14px 16px;border-radius:8px;background:#f2f4f6;color:#515f74;font-size:13px;line-height:1.6;">Sent from the urless admin About page at {$now}.</p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        HTML;
    }

    private function composerVersion(string $package): string
    {
        return InstalledVersions::isInstalled($package)
            ? (InstalledVersions::getPrettyVersion($package) ?? InstalledVersions::getVersion($package) ?? 'Installed')
            : 'Not installed';
    }

    /**
     * @return array<string, mixed>
     */
    private function packageJson(): array
    {
        $path = base_path('package.json');

        if (! is_file($path)) {
            return [];
        }

        $decoded = json_decode((string) file_get_contents($path), true);

        return is_array($decoded) ? $decoded : [];
    }

    private function databaseVersion(): string
    {
        try {
            $version = DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION);

            return is_string($version) ? $version : '';
        } catch (Throwable) {
            return '';
        }
    }

    private function aboutStyles(): string
    {
        return <<<'HTML'
            <style>
                .urless-about { display: grid; gap: 18px; }
                .urless-about-hero {
                    border: 1px solid rgba(99, 102, 241, .18);
                    border-radius: 24px;
                    background: linear-gradient(135deg, rgba(70,72,212,.12), rgba(0,108,73,.08)), #fff;
                    padding: 28px;
                }
                .dark .urless-about-hero { background: linear-gradient(135deg, rgba(99,102,241,.18), rgba(16,185,129,.10)), rgba(255,255,255,.035); border-color: rgba(255,255,255,.12); }
                .urless-about-pill {
                    display: inline-flex;
                    border-radius: 999px;
                    background: rgba(70, 72, 212, .12);
                    color: #4648d4;
                    font-size: 11px;
                    font-weight: 900;
                    padding: 7px 10px;
                    text-transform: uppercase;
                }
                .urless-about-hero h2 { color: #0f172a; font-size: clamp(30px, 5vw, 54px); font-weight: 950; letter-spacing: -.04em; line-height: 1; margin: 18px 0 14px; }
                .dark .urless-about-hero h2 { color: #f8fafc; }
                .urless-about-hero p { color: #475569; font-size: 15px; line-height: 1.75; max-width: 860px; margin: 0; }
                .dark .urless-about-hero p { color: #cbd5e1; }
                .urless-about-meta { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
                .urless-about-meta span {
                    border: 1px solid rgba(15,23,42,.08);
                    border-radius: 12px;
                    background: rgba(255,255,255,.72);
                    color: #475569;
                    font-size: 12px;
                    font-weight: 800;
                    padding: 10px 12px;
                }
                .dark .urless-about-meta span { background: rgba(255,255,255,.06); border-color: rgba(255,255,255,.10); color: #cbd5e1; }
                .urless-about-grid { display: grid; gap: 14px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
                .urless-about-card {
                    border: 1px solid rgba(148,163,184,.24);
                    border-radius: 18px;
                    background: #fff;
                    box-shadow: 0 18px 45px rgba(15,23,42,.05);
                    padding: 20px;
                }
                .dark .urless-about-card { background: rgba(255,255,255,.035); border-color: rgba(255,255,255,.10); box-shadow: none; }
                .urless-about-card span, .urless-mail-grid span {
                    color: #64748b;
                    display: block;
                    font-size: 11px;
                    font-weight: 900;
                    letter-spacing: .08em;
                    text-transform: uppercase;
                }
                .urless-about-card strong {
                    color: var(--accent);
                    display: block;
                    font-size: 30px;
                    font-weight: 950;
                    margin-top: 12px;
                }
                .urless-about-table-wrap {
                    border: 1px solid rgba(148,163,184,.24);
                    border-radius: 18px;
                    overflow: hidden;
                }
                .urless-about-table { border-collapse: collapse; width: 100%; }
                .urless-about-table th, .urless-about-table td {
                    border-bottom: 1px solid rgba(148,163,184,.20);
                    padding: 14px 16px;
                    text-align: left;
                    vertical-align: top;
                }
                .urless-about-table th {
                    background: #f8fafc;
                    color: #64748b;
                    font-size: 11px;
                    font-weight: 900;
                    letter-spacing: .08em;
                    text-transform: uppercase;
                }
                .dark .urless-about-table th { background: rgba(255,255,255,.04); color: #94a3b8; }
                .urless-about-table td { color: #334155; font-size: 14px; }
                .dark .urless-about-table td { color: #cbd5e1; }
                .urless-about-table strong { color: #0f172a; font-weight: 900; }
                .dark .urless-about-table strong { color: #f8fafc; }
                .urless-mail-grid { display: grid; gap: 14px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
                .urless-mail-grid article {
                    border: 1px solid rgba(148,163,184,.24);
                    border-radius: 16px;
                    background: #fff;
                    padding: 18px;
                }
                .dark .urless-mail-grid article { background: rgba(255,255,255,.035); border-color: rgba(255,255,255,.10); }
                .urless-mail-grid article.is-wide { grid-column: 1 / -1; }
                .urless-mail-grid strong {
                    color: #0f172a;
                    display: block;
                    font-size: 18px;
                    font-weight: 950;
                    margin-top: 10px;
                    word-break: break-word;
                }
                .dark .urless-mail-grid strong { color: #f8fafc; }
                .urless-about-note {
                    color: #64748b;
                    font-size: 13px;
                    font-weight: 700;
                    margin: 14px 0 0;
                }
                @media (max-width: 900px) {
                    .urless-about-grid, .urless-mail-grid { grid-template-columns: 1fr; }
                }
            </style>
        HTML;
    }
}
