<?php

namespace App\Filament\Resources\DelayedGoods\Tables;

use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\TextInput;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;

class DelayedGoodsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('stored_date')
                    ->label('Tanggal Penyimpanan')
                    ->date('l, d F Y')
                    ->sortable(),

                TextColumn::make('customer.name')
                    ->label('Pelanggan')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('warehouse.name')
                    ->label('Gudang')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('quantity')
                    ->label('Jumlah')
                    ->getStateUsing(function ($record) {
                        return str_replace('.', ',', (float) $record->quantity)." {$record->unit?->alias}";
                    })
                    ->sortable(),

                TextColumn::make('unit_price')
                    ->label('Harga per Satuan')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                TextColumn::make('total_amount')
                    ->label('Total')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                TextColumn::make('paid_amount')
                    ->label('Sudah Dibayar')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable()
                    ->color(fn ($record) => $record->paid_amount >= $record->total_amount ? 'success' : 'warning'),

                TextColumn::make('remaining_amount')
                    ->label('Sisa')
                    ->getStateUsing(fn ($record) => max(0, $record->total_amount - $record->paid_amount))
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable()
                    ->color(fn ($record) => $record->paid_amount >= $record->total_amount ? 'success' : 'danger'),

                IconColumn::make('is_paid')
                    ->label('Status')
                    ->boolean()
                    ->trueIcon(Heroicon::CheckCircle)
                    ->falseIcon(Heroicon::XCircle)
                    ->trueColor('success')
                    ->falseColor('warning')
                    ->sortable(),

                TextColumn::make('notes')
                    ->label('Catatan')
                    ->limit(30),

                TextColumn::make('payment_date')
                    ->label('Tanggal Lunas')
                    ->date('l, d F Y')
                    ->sortable(),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
            ])
            ->recordActions([
                Action::make('pelunasan')
                    ->label('Pelunasan')
                    ->icon(Heroicon::CurrencyDollar)
                    ->color('success')
                    ->visible(fn ($record) => ! $record->is_paid)
                    ->schema([
                        TextInput::make('amount')
                            ->label('Jumlah yang dibayar')
                            ->required()
                            ->default(fn ($record) => max(0, $record->total_amount - $record->paid_amount))
                            ->helperText(fn ($record) => 'sisa: Rp '.number_format(max(0, $record->total_amount - $record->paid_amount), 0, ',', '.'))
                            ->prefix('Rp')
                            ->live()
                            ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                            ->dehydrateStateUsing(fn ($state) => (float) str()->replace(',', '.', str()->replace('.', '', (string) ($state ?? 0)))),
                    ])
                    ->requiresConfirmation()
                    ->action(function (array $data, $record) {
                        $amount = $data['amount'] ?? 0;
                        $record->paid_amount += $amount;
                        if ($record->paid_amount >= $record->total_amount) {
                            $record->paid_amount = $record->total_amount;
                            $record->is_paid = true;
                            $record->payment_date = now();
                        }
                        $record->save();
                    }),

                EditAction::make()
                    ->label('Ubah'),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Barang Tertunda'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::Clock)
            ->emptyStateDescription('Setelah Anda membuat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }
}
