<?php

declare(strict_types=1);

namespace App\Filament\Resources\OwnerResource\Pages;

use App\Enums\OwnerLedgerEntryType;
use App\Filament\Resources\OwnerResource;
use App\Models\OwnerLedgerEntry;
use App\Models\OwnerPayout;
use Filament\Actions;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Facades\DB;
use Throwable;

class ViewOwner extends ViewRecord
{
    protected static string $resource = OwnerResource::class;

    protected function getHeaderActions(): array
    {
        return [
            // View statement button (already added earlier)
            Actions\Action::make('statement')
                ->label('View Statement')
                ->icon('heroicon-o-document-text')
                ->url(fn () => OwnerResource::getUrl('statement', ['record' => $this->record->id]))
                ->color('secondary'),

            // NEW: Create payout
            Actions\Action::make('createPayout')
                ->label('Create payout')
                ->icon('heroicon-o-banknotes')
                ->color('primary')
                ->visible(fn () => $this->record->balance_cents > 0)
                ->form([
                    Forms\Components\TextInput::make('amount')
                        ->label('Amount (NZD)')
                        ->prefix('$')
                        ->numeric()
                        ->required()
                        ->default(function ($livewire): ?string {
                            $owner = $livewire->record;
                            if (! $owner || $owner->balance_cents <= 0) {
                                return null;
                            }

                            return number_format($owner->balance_cents / 100, 2, '.', '');
                        })
                        ->rule(function () {
                            return function (string $attribute, $value, $fail) {
                                $norm = preg_replace('/[^\d.]/', '', (string) $value);
                                $cents = (int) round(((float) $norm) * 100);

                                if ($cents <= 0) {
                                    $fail('Amount must be greater than zero.');
                                }

                                /** @var \App\Models\Owner $owner */
                                $owner = $this->record;

                                if ($cents > $owner->balance_cents) {
                                    $fail('Amount cannot be greater than the current balance.');
                                }
                            };
                        }),

                    Forms\Components\TextInput::make('reference')
                        ->label('Reference')
                        ->maxLength(100)
                        ->placeholder('e.g. November payout'),

                    Forms\Components\Textarea::make('notes')
                        ->label('Notes')
                        ->rows(3)
                        ->columnSpanFull(),

                    Forms\Components\DateTimePicker::make('paid_at')
                        ->label('Paid at')
                        ->default(now()),
                ])
                ->action(function (array $data): void {
                    /** @var \App\Models\Owner $owner */
                    $owner = $this->record;

                    $amountStr   = (string) ($data['amount'] ?? '0');
                    $amountNorm  = preg_replace('/[^\d.]/', '', $amountStr);
                    $amountCents = (int) round(((float) $amountNorm) * 100);

                    if ($amountCents <= 0) {
                        Notification::make()
                            ->title('Invalid amount')
                            ->body('Please enter an amount greater than zero.')
                            ->danger()
                            ->send();

                        return;
                    }

                    if ($amountCents > $owner->balance_cents) {
                        Notification::make()
                            ->title('Amount too high')
                            ->body('The payout amount cannot exceed the current balance.')
                            ->danger()
                            ->send();

                        return;
                    }

                    try {
                        DB::beginTransaction();

                        // 1) Create the payout record
                        /** @var OwnerPayout $payout */
                        $payout = OwnerPayout::create([
                            'owner_id'     => $owner->id,
                            'amount_cents' => $amountCents,
                            'reference'    => $data['reference'] ?? null,
                            'notes'        => $data['notes'] ?? null,
                            'paid_at'      => $data['paid_at'] ?? now(),
                            // Add currency_code if your table has it, e.g. 'NZD'
                        ]);

                        // 2) Create the matching ledger entry (type payout)
                        OwnerLedgerEntry::create([
                            'owner_id'     => $owner->id,
                            'vehicle_id'   => null,
                            'job_id'       => null,
                            'type'         => OwnerLedgerEntryType::PAYOUT,
                            'amount_cents' => $amountCents,
                            'occurred_at'  => $payout->paid_at ?? now(),
                            'description'  => $data['reference']
                                ? 'Payout: ' . $data['reference']
                                : 'Payout',
                            // 'currency_code' => 'NZD', // if column exists
                        ]);

                        DB::commit();

                        Notification::make()
                            ->title('Payout created')
                            ->body('Payout recorded and ledger updated.')
                            ->success()
                            ->send();

                        $this->refreshFormData(['record']); // refresh page so balance updates
                    } catch (Throwable $e) {
                        DB::rollBack();
                        report($e);

                        Notification::make()
                            ->title('Payout failed')
                            ->body('There was an error creating the payout. Check the logs for details.')
                            ->danger()
                            ->send();
                    }
                }),

            Actions\EditAction::make(),
        ];
    }
}
