<?php

namespace Modules\AiAgent\Filament\Pages;

use BackedEnum;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Contracts\View\View;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\Shared\Bnfexpress\BnfexpressAdminClient;
use Modules\Shared\Bnfexpress\Exceptions\BnfexpressApiException;
use UnitEnum;

/**
 * Read-only browse of all users' EV chat sessions. No create/edit/delete —
 * this is a support/QA tool, not a data-management screen.
 */
class ViewEvChatHistory extends Page implements HasTable
{
    use InteractsWithTable;

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

    protected static string|UnitEnum|null $navigationGroup = 'AI Agent';

    protected static ?string $navigationLabel = 'EV Chat History';

    protected static ?string $title = 'EV Chat History';

    protected string $view = 'ai-agent::filament.pages.view-ev-chat-history';

    public static function canAccess(): bool
    {
        return auth()->user()?->can('manage_ai_agent') ?? false;
    }

    public function table(Table $table): Table
    {
        return $table
            ->records(function (int $page, int $recordsPerPage): LengthAwarePaginator {
                $result = app(BnfexpressAdminClient::class)->listSessions(
                    limit: $recordsPerPage,
                    offset: ($page - 1) * $recordsPerPage,
                );

                $sessions = $result['sessions'] ?? [];

                return new LengthAwarePaginator(
                    items: collect($sessions)->mapWithKeys(
                        fn (array $session): array => ["{$session['user_id']}:{$session['session_id']}" => $session]
                    ),
                    total: $result['total'] ?? count($sessions),
                    perPage: $result['limit'] ?? $recordsPerPage,
                    currentPage: $page,
                );
            })
            ->columns([
                TextColumn::make('session_id')
                    ->limit(20)
                    ->tooltip(fn (TextColumn $column): ?string => $this->tooltipIfTruncated($column)),
                TextColumn::make('user_id')
                    ->limit(20)
                    ->tooltip(fn (TextColumn $column): ?string => $this->tooltipIfTruncated($column)),
                TextColumn::make('title')->limit(50),
                TextColumn::make('last_message')->limit(80)->wrap(),
                TextColumn::make('updated_at')->dateTime(),
            ])
            ->recordActions([
                Action::make('view')
                    ->label('View Transcript')
                    ->icon(Heroicon::OutlinedEye)
                    ->modalHeading(fn (array $record): string => "Transcript — {$record['session_id']}")
                    ->modalContent(fn (array $record): View => $this->transcriptView($record))
                    ->modalWidth('2xl')
                    ->modalSubmitAction(false)
                    ->modalCancelActionLabel('Close'),
            ]);
    }

    private function tooltipIfTruncated(TextColumn $column): ?string
    {
        $state = (string) $column->getState();

        return strlen($state) > $column->getCharacterLimit() ? $state : null;
    }

    private function transcriptView(array $record): View
    {
        try {
            $transcript = app(BnfexpressAdminClient::class)->getSessionTranscript($record['user_id'], $record['session_id']);

            return view('ai-agent::filament.pages.partials.transcript', ['transcript' => $transcript]);
        } catch (BnfexpressApiException $exception) {
            Notification::make()
                ->title('Could not load transcript')
                ->body($exception->getMessage())
                ->danger()
                ->send();

            return view('ai-agent::filament.pages.partials.transcript-error', ['message' => $exception->getMessage()]);
        }
    }
}
