<?php

namespace App\Filament\Resources\Campaigns;

use App\Filament\Resources\Campaigns\Pages\CreateCampaign;
use App\Filament\Resources\Campaigns\Pages\EditCampaign;
use App\Filament\Resources\Campaigns\Pages\ListCampaigns;
use App\Models\Assessment;
use App\Models\Campaign;
use BackedEnum;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\Str;

class CampaignResource extends Resource
{
    protected static ?string $model = Campaign::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-megaphone';

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

    protected static ?int $navigationSort = 4;

    protected static ?string $recordTitleAttribute = 'name';

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Campaign')
                ->description('Create a shareable Health Check link for a specific group or event. Every completion from this link is tagged so you can see that group\'s leads together.')
                ->columns(2)
                ->schema([
                    TextInput::make('name')
                        ->required()
                        ->live(onBlur: true)
                        ->helperText('Internal name, e.g. "Acme staff wellness, Aug 2026".')
                        ->afterStateUpdated(fn ($state, callable $set, $get) => $get('slug') ? null : $set('slug', Str::slug($state ?? ''))),
                    TextInput::make('slug')
                        ->required()
                        ->unique(ignoreRecord: true)
                        ->helperText('Used in the link. Lowercase, no spaces.'),
                    Select::make('assessment')
                        ->options(fn () => Assessment::query()->where('is_active', true)->pluck('title', 'slug')->all())
                        ->default('financial-health')
                        ->required(),
                    Toggle::make('is_active')->default(true)->inline(false),
                    TextInput::make('headline')
                        ->label('Custom welcome badge (optional)')
                        ->placeholder('e.g. Welcome, Acme team!')
                        ->columnSpanFull(),
                    Textarea::make('intro')
                        ->label('Custom intro text (optional)')
                        ->rows(2)
                        ->helperText('Replaces the default intro line for people who use this link.')
                        ->columnSpanFull(),
                    Placeholder::make('share_link')
                        ->label('Shareable link')
                        ->visible(fn (Get $get) => filled($get('slug')) && filled($get('assessment')))
                        ->content(fn (Get $get) => url('/assessments/'.$get('assessment').'?campaign='.$get('slug')))
                        ->columnSpanFull(),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('name')->searchable()->weight('bold'),
                TextColumn::make('assessment')->badge()->color('gray'),
                TextColumn::make('shareUrl')
                    ->label('Shareable link')
                    ->getStateUsing(fn (Campaign $record) => $record->shareUrl())
                    ->copyable()
                    ->copyMessage('Link copied')
                    ->limit(48)
                    ->color('primary'),
                TextColumn::make('leads_count')->label('Leads')->badge()->sortable(),
                IconColumn::make('is_active')->boolean()->label('Active'),
                TextColumn::make('created_at')->dateTime('j M Y')->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->recordActions([EditAction::make()]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListCampaigns::route('/'),
            'create' => CreateCampaign::route('/create'),
            'edit' => EditCampaign::route('/{record}/edit'),
        ];
    }
}
