<?php

namespace App\Filament\Resources\Consultants;

use App\Filament\Resources\Consultants\Pages\CreateConsultant;
use App\Filament\Resources\Consultants\Pages\EditConsultant;
use App\Filament\Resources\Consultants\Pages\ListConsultants;
use App\Filament\Resources\Consultants\RelationManagers\AssignmentsRelationManager;
use App\Models\Consultant;
use BackedEnum;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;

class ConsultantResource extends Resource
{
    protected static ?string $model = Consultant::class;

    protected static ?string $slug = 'consultants';

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

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

    protected static ?string $navigationLabel = 'Consultants';

    protected static ?int $navigationSort = 2;

    public static function getNavigationBadge(): ?string
    {
        $count = Consultant::query()->where('status', 'submitted')->count();

        return $count ? (string) $count : null;
    }

    public static function getNavigationBadgeColor(): string|array|null
    {
        return 'warning';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Section::make('Consultant')
                ->description('Creating a consultant sends them a personal onboarding invite by email. You can also copy the link from the list and share it on WhatsApp.')
                ->schema([
                    TextInput::make('name')->required()->maxLength(120),
                    TextInput::make('email')->email()->required()->unique(ignoreRecord: true),
                    TextInput::make('phone')->tel()->maxLength(32),
                    TextInput::make('title')
                        ->label('Professional title')
                        ->placeholder('e.g. Personal Finance Coach')
                        ->maxLength(120),
                    Select::make('status')
                        ->options([
                            'invited' => 'Invited',
                            'onboarding' => 'Onboarding',
                            'submitted' => 'Submitted for review',
                            'approved' => 'Approved',
                            'inactive' => 'Inactive',
                        ])
                        ->default('invited')
                        ->required()
                        ->helperText('Approve after reviewing the submitted profile. Inactive hides the invite link.'),
                ])->columns(2),

            Section::make('Onboarding progress')
                ->schema([
                    Placeholder::make('progress')
                        ->hiddenLabel()
                        ->content(fn (?Consultant $record) => new HtmlString(
                            $record ? self::progressHtml($record) : 'Progress appears once the invite is sent.'
                        )),
                ])
                ->collapsible()
                ->hiddenOn('create'),
        ]);
    }

    private static function progressHtml(Consultant $record): string
    {
        $answers = $record->onboarding ?? [];
        $percent = $record->progressPercent();

        $rows = collect([
            'Phone' => $answers['phone'] ?? null,
            'Title' => $answers['title'] ?? null,
            'Experience' => $answers['years_experience'] ?? null,
            'Location' => $answers['location'] ?? null,
            'Specialties' => implode(', ', $answers['specialties'] ?? []),
            'Certifications' => $answers['certifications'] ?? null,
            'Languages' => $answers['languages'] ?? null,
            'Session mode' => $answers['mode'] ?? null,
            'Available days' => implode(', ', $answers['days'] ?? []),
            'Capacity / month' => $answers['capacity'] ?? null,
            'Philosophy' => $answers['philosophy'] ?? null,
            'LinkedIn' => $answers['linkedin'] ?? null,
            'Bio' => $answers['bio'] ?? null,
            'Agreements accepted' => ($answers['agree_confidentiality'] ?? false) && ($answers['agree_conduct'] ?? false) ? 'Yes' : 'Not yet',
        ])->filter(fn ($v) => filled($v));

        $bar = '<div style="background:#eef1f9;border-radius:999px;height:10px;max-width:280px;overflow:hidden">'
            .'<div style="background:#58b9e6;height:100%;width:'.$percent.'%"></div></div>'
            .'<p style="margin:6px 0 14px;font-size:12px;color:#6b7aa8">'
            .$percent.'% complete · step '.min($record->onboarding_step + 1, count(Consultant::STEPS)).' of '.count(Consultant::STEPS)
            .($record->submitted_at ? ' · submitted '.$record->submitted_at->diffForHumans() : '')
            .'</p>';

        if ($rows->isEmpty()) {
            return $bar.'<p style="font-size:13px;color:#93a1c6">No answers yet. Share the onboarding link to get them started.</p>';
        }

        return $bar.'<dl style="display:grid;grid-template-columns:160px 1fr;gap:6px 16px;font-size:13px">'
            .$rows->map(fn ($v, $k) => '<dt style="font-weight:600;color:#6b7aa8">'.e($k).'</dt><dd style="color:#15204a">'.nl2br(e($v)).'</dd>')->implode('')
            .'</dl>';
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')->searchable()->weight('bold')->description(fn (Consultant $r) => $r->title),
                TextColumn::make('email')->searchable()->toggleable(),
                TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state) => match ($state) {
                        'approved' => 'success',
                        'submitted' => 'info',
                        'onboarding' => 'warning',
                        'inactive' => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('onboarding_step')
                    ->label('Progress')
                    ->formatStateUsing(fn (Consultant $r) => $r->progressPercent().'%'),
                TextColumn::make('active_assignments_count')
                    ->counts('activeAssignments')
                    ->label('Members')
                    ->badge(),
                TextColumn::make('invited_at')->since()->label('Invited')->toggleable(),
            ])
            ->recordActions([
                \Filament\Actions\Action::make('copy_link')
                    ->label('Copy invite link')
                    ->icon('heroicon-o-link')
                    ->action(fn () => null)
                    ->extraAttributes(fn (Consultant $record) => [
                        'x-on:click' => 'window.navigator.clipboard.writeText('.json_encode($record->onboardingUrl()).'); $tooltip("Link copied")',
                    ]),
                \Filament\Actions\EditAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [AssignmentsRelationManager::class];
    }

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