<?php

namespace App\Filament\Tenant\Resources\WorkOrderResource\RelationManagers;

use App\Models\Tenant\Payment;
use Filament\Actions;
use Filament\Forms;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;

class PaymentsRelationManager extends RelationManager
{
    protected static string $relationship = 'payments';

    protected static ?string $title = 'Plăți';

    public function form(Schema $schema): Schema
    {
        return $schema->components([
            Forms\Components\DatePicker::make('paid_at')->label('Data')->default(today())->required(),
            Forms\Components\TextInput::make('amount')->label('Sumă')->numeric()->required(),
            Forms\Components\Select::make('method')
                ->options(Payment::METHODS)
                ->default('cash')
                ->required(),
            Forms\Components\TextInput::make('reference')->label('Referință')->maxLength(64),
            Forms\Components\Textarea::make('notes')->label('Notițe')->columnSpanFull()->rows(2),
        ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('amount')
            ->columns([
                Tables\Columns\TextColumn::make('paid_at')->label('Data')->date('d.m.Y'),
                Tables\Columns\TextColumn::make('amount')->money('MDL')->alignRight()
                    ->summarize(Tables\Columns\Summarizers\Sum::make()->money('MDL')->label('Plătit')),
                Tables\Columns\TextColumn::make('method')
                    ->formatStateUsing(fn ($s) => Payment::METHODS[$s] ?? $s)
                    ->badge(),
                Tables\Columns\TextColumn::make('reference')->placeholder('—'),
            ])
            ->headerActions([
                Actions\CreateAction::make()->mutateFormDataUsing(function (array $data, RelationManager $livewire): array {
                    $wo = $livewire->getOwnerRecord();
                    $data['client_id'] = $wo->client_id;
                    $data['user_id'] = auth()->id();
                    return $data;
                }),
            ])
            ->actions([
                Actions\EditAction::make(),
                Actions\DeleteAction::make(),
            ])
            ->defaultSort('paid_at', 'desc');
    }
}
