<?php

namespace App\Filament\Pages;

use Filament\Actions\Action;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Str;

class Documentation extends Page
{
    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedBookOpen;

    protected static ?string $navigationLabel = 'Documentation';

    protected static ?string $title = 'Documentation API';

    protected static ?int $navigationSort = 0;

    protected string $view = 'filament.pages.documentation';

    public string $htmlContent = '';

    public function mount(): void
    {
        $markdownPath = base_path('documentation/documentation_api_logistics.md');
        $markdown = file_get_contents($markdownPath);
        $html = (string) Str::markdown($markdown);

        $this->htmlContent = preg_replace_callback(
            '/<(h[1-6])>(.*?)<\/\1>/i',
            function (array $matches): string {
                $tag = $matches[1];
                $content = $matches[2];
                $slug = self::slugify(strip_tags($content));

                return "<{$tag} id=\"{$slug}\">{$content}</{$tag}>";
            },
            $html,
        ) ?? $html;
    }

    private static function slugify(string $text): string
    {
        $slug = mb_strtolower($text, 'UTF-8');
        $slug = preg_replace('/[.\s]+/', '-', $slug);
        $slug = preg_replace('/[^\w\x{00C0}-\x{024F}-]/u', '', $slug);
        $slug = preg_replace('/-+/', '-', $slug);

        return trim($slug, '-');
    }

    public function getHeaderActions(): array
    {
        return [
            Action::make('download')
                ->label('Télécharger en PDF')
                ->icon(Heroicon::OutlinedArrowDownTray)
                ->url(route('documentation.download-pdf'))
                ->openUrlInNewTab(),

            Action::make('see_in_another_tab')
                ->label('Voir dans un nouvel onglet')
                ->icon(Heroicon::OutlinedArrowTopRightOnSquare)
                ->url(Documentation::getUrl())
                ->openUrlInNewTab(),
        ];
    }
}
