<?php

declare(strict_types=1);

namespace App\Filament\Resources\Leads\Tables;

use App\Models\Lead;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class LeadsTable
{
    /** @var array<string,string> */
    private const STATUS_COLORS = [
        Lead::STATUS_NEW => 'warning',
        Lead::STATUS_CONTACTED => 'info',
        Lead::STATUS_CONVERTED => 'success',
        Lead::STATUS_DISCARDED => 'gray',
    ];

    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('created_at')
                    ->label('Fecha')
                    ->dateTime('d/m/Y H:i')
                    ->sortable(),

                TextColumn::make('name')
                    ->label('Nombre')
                    ->searchable()
                    ->weight('bold'),

                TextColumn::make('phone')
                    ->label('WhatsApp')
                    ->searchable()
                    ->copyable(),

                TextColumn::make('email')
                    ->label('Correo')
                    ->placeholder('—')
                    ->searchable()
                    ->toggleable(),

                TextColumn::make('message')
                    ->label('Mensaje')
                    ->placeholder('—')
                    ->limit(40)
                    ->tooltip(fn (Lead $record): ?string => $record->message),

                TextColumn::make('source')
                    ->label('Origen')
                    ->badge()
                    ->color('gray')
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('status')
                    ->label('Estado')
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => Lead::STATUS_LABELS[$state] ?? (string) $state)
                    ->color(fn (?string $state): string => self::STATUS_COLORS[$state] ?? 'gray')
                    ->sortable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                SelectFilter::make('status')
                    ->label('Estado')
                    ->options(Lead::STATUS_LABELS),
            ])
            ->recordActions([
                Action::make('email')
                    ->label('Correo')
                    ->icon('heroicon-o-envelope')
                    ->color('primary')
                    ->url(fn (Lead $record): ?string => filled($record->email) ? 'mailto:'.$record->email : null)
                    ->openUrlInNewTab()
                    ->visible(fn (Lead $record): bool => filled($record->email)),

                Action::make('whatsapp')
                    ->label('WhatsApp')
                    ->icon('heroicon-o-chat-bubble-left-right')
                    ->color('success')
                    ->url(fn (Lead $record): string => 'https://wa.me/'.preg_replace('/\D/', '', (string) $record->phone))
                    ->openUrlInNewTab(),

                ActionGroup::make([
                    Action::make('markContacted')
                        ->label('Marcar contactado')
                        ->icon('heroicon-o-phone')
                        ->color('info')
                        ->visible(fn (Lead $record): bool => $record->status === Lead::STATUS_NEW)
                        ->action(fn (Lead $record) => self::setStatus($record, Lead::STATUS_CONTACTED)),

                    Action::make('markConverted')
                        ->label('Marcar convertido')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->action(fn (Lead $record) => self::setStatus($record, Lead::STATUS_CONVERTED)),

                    Action::make('discard')
                        ->label('Descartar')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->requiresConfirmation()
                        ->action(fn (Lead $record) => self::setStatus($record, Lead::STATUS_DISCARDED)),
                ])->label('Estado'),
            ]);
    }

    private static function setStatus(Lead $record, string $status): void
    {
        $record->update(['status' => $status]);

        Notification::make()
            ->title('Lead actualizado')
            ->body('Estado: '.(Lead::STATUS_LABELS[$status] ?? $status))
            ->success()
            ->send();
    }
}
