<?php

declare(strict_types=1);

namespace App\Filament\Resources\Partners\RelationManagers;

use App\Enums\ContributionType;
use App\Filament\Resources\Incomes\IncomeResource;
use App\Models\CapitalContribution;
use App\Services\PartnerInvestmentService;
use Carbon\Carbon;
use Filament\Actions\Action as TableAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class ContributionsRelationManager extends RelationManager
{
    protected static string $relationship = 'contributions';

    protected static ?string $title = 'Aportes de capital';

    protected static ?string $recordTitleAttribute = 'id';

    public function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('id')
                    ->label('#')
                    ->sortable(),

                TextColumn::make('amount')
                    ->label('Monto')
                    ->money('COP', locale: 'es_CO')
                    ->sortable()
                    ->color('success'),

                TextColumn::make('type')
                    ->label('Tipo')
                    ->badge()
                    ->formatStateUsing(fn ($state) => $state instanceof ContributionType
                        ? $state->getLabel()
                        : (is_string($state) ? (ContributionType::tryFrom($state)?->getLabel() ?? $state) : '-')
                    )
                    ->color(fn ($state) => $state instanceof ContributionType
                        ? $state->getColor()
                        : 'gray'
                    ),

                TextColumn::make('method')
                    ->label('Metodo')
                    ->formatStateUsing(fn ($state) => match ($state) {
                        'cash' => 'Efectivo',
                        'transfer' => 'Transferencia',
                        'card' => 'Tarjeta',
                        'mobile_money' => 'Billetera digital',
                        'other' => 'Otro',
                        default => $state ?? '-',
                    })
                    ->toggleable(),

                TextColumn::make('operation_date')
                    ->label('Fecha')
                    ->date('d/m/Y')
                    ->sortable(),

                TextColumn::make('reference')
                    ->label('Referencia')
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('user.name')
                    ->label('Registrado por')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->headerActions([
                TableAction::make('register_contribution')
                    ->label('Registrar aporte')
                    ->icon('heroicon-o-plus-circle')
                    ->color('success')
                    ->form([
                        TextInput::make('amount')
                            ->label('Monto')
                            ->required()
                            ->numeric()
                            ->minValue(0.01)
                            ->prefix('$'),

                        Select::make('type')
                            ->label('Tipo de aporte')
                            ->options([
                                'initial' => 'Aporte inicial',
                                'additional' => 'Aporte adicional',
                                'reinvestment' => 'Reinversion de utilidades',
                            ])
                            ->default('additional')
                            ->required(),

                        Select::make('method')
                            ->label('Metodo de pago')
                            ->options([
                                'cash' => 'Efectivo',
                                'transfer' => 'Transferencia bancaria',
                                'card' => 'Tarjeta',
                                'mobile_money' => 'Billetera digital',
                                'other' => 'Otro',
                            ]),

                        DatePicker::make('operation_date')
                            ->label('Fecha de operacion')
                            ->required()
                            ->default(now()),

                        TextInput::make('reference')
                            ->label('Referencia'),

                        Textarea::make('notes')
                            ->label('Notas')
                            ->rows(2),
                    ])
                    ->action(function (array $data) {
                        $service = app(PartnerInvestmentService::class);

                        try {
                            $service->registerContribution(
                                partner: $this->ownerRecord,
                                amount: (string) $data['amount'],
                                type: ContributionType::from($data['type']),
                                operationDate: Carbon::parse($data['operation_date']),
                                method: $data['method'] ?? null,
                                reference: $data['reference'] ?? null,
                                notes: $data['notes'] ?? null,
                            );

                            Notification::make()
                                ->success()
                                ->title('Aporte registrado')
                                ->body('El aporte de capital ha sido registrado exitosamente.')
                                ->send();
                        } catch (\Exception $e) {
                            Notification::make()
                                ->danger()
                                ->title('Error al registrar aporte')
                                ->body($e->getMessage())
                                ->send();
                        }
                    }),
            ])
            ->actions([
                TableAction::make('view_income')
                    ->label('Ver ingreso')
                    ->icon('heroicon-o-eye')
                    ->visible(fn (CapitalContribution $record) => (bool) $record->income_id)
                    ->url(fn (CapitalContribution $record) => $record->income_id
                        ? IncomeResource::getUrl('view', ['record' => $record->income_id])
                        : null
                    ),
            ])
            ->defaultSort('operation_date', 'desc')
            ->emptyStateHeading('Sin aportes de capital')
            ->emptyStateDescription('Este socio aun no tiene aportes registrados.')
            ->emptyStateIcon('heroicon-o-banknotes');
    }
}
