<?php

namespace App\Filament\Resources\Documents\Schemas;

use App\Enums\FormType;
use App\Filament\RichEditor\DisableAutolinkPlugin;
use App\Services\DocumentTemplateService;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;

class DocumentForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('Document Information')
                    ->columnSpanFull()
                    ->columns(3)
                    ->schema([
                        TextInput::make('name')
                            ->required()
                            ->maxLength(255)
                            ->live(onBlur: true)
                            ->afterStateUpdated(fn ($state, callable $set) => $set('slug', Str::slug($state))),
                        TextInput::make('slug')
                            ->required()
                            ->maxLength(255)
                            ->unique(ignoreRecord: true),
                        Select::make('form_type')
                            ->label('Form Type')
                            ->options(FormType::class)
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->live()
                            ->helperText('Each form type can only have one document template.'),
                        Textarea::make('description')
                            ->rows(2)
                            ->maxLength(1000)
                            ->columnSpanFull(),
                    ]),

                Section::make('Template Content')
                    ->columnSpanFull()
                    ->schema([
                        RichEditor::make('content')
                            ->required()
                            ->columnSpanFull()
                            ->toolbarButtons([
                                ['bold', 'italic', 'underline', 'strike', 'subscript', 'superscript', 'link'],
                                ['h1', 'h2', 'h3', 'alignStart', 'alignCenter', 'alignEnd'],
                                ['blockquote', 'bulletList', 'orderedList'],
                                ['code', 'small', 'textColor', 'highlight', 'clearFormatting'],
                                ['grid', 'table'],
                                ['undo', 'redo'],
                            ])
                            ->plugins([
                                DisableAutolinkPlugin::make(),
                            ]),
                    ]),

                Section::make('Available Template Tags')
                    ->columnSpanFull()
                    ->collapsed()
                    ->description('Use these tags in your template to insert dynamic data.')
                    ->schema([
                        Placeholder::make('template_tags_help')
                            ->label('')
                            ->content(fn ($get) => new HtmlString(self::getTemplateTagsHelp($get('form_type')))),
                    ]),
            ]);
    }

    protected static function getTemplateTagsHelp(FormType|string|null $formType): string
    {
        if ($formType instanceof FormType) {
            $formTypeEnum = $formType;
        } else {
            $formTypeEnum = $formType ? FormType::tryFrom($formType) : FormType::Adoption;
        }

        $tags = app(DocumentTemplateService::class)->getAvailableTags($formTypeEnum ?? FormType::Adoption);

        $html = '<div class="space-y-4">';

        foreach ($tags as $category => $categoryTags) {
            $html .= '<div class="border rounded-lg p-4 bg-gray-50 dark:bg-gray-800">';
            $html .= '<h4 class="font-semibold text-sm mb-2">'.e($category).'</h4>';
            $html .= '<div class="grid gap-1">';

            foreach ($categoryTags as $tag => $description) {
                $html .= '<div class="flex items-start gap-2 text-sm">';
                $html .= '<code class="bg-gray-200 dark:bg-gray-700 px-1.5 py-0.5 rounded text-xs font-mono">'.e($tag).'</code>';
                $html .= '<span class="text-gray-600 dark:text-gray-400">'.e($description).'</span>';
                $html .= '</div>';
            }

            $html .= '</div></div>';
        }

        $html .= '</div>';

        return $html;
    }
}
