<?php

namespace App\Filament\Resources\OrderResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Actions\AttachAction;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;

class DonorFinancialPortfoliosRelationManager extends RelationManager
{
    protected static string $relationship = 'donorFinancialPortfolios';

    public static function getTitle(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): string
    {
        return __('donor_financial_portfolio.donor_financial_portfolios');
    }

    public static function getModelLabel(): string
    {
        return __('donor_financial_portfolio.donor_financial_portfolio');
    }

    public static function getPluralModelLabel(): string
    {
        return __('donor_financial_portfolio.donor_financial_portfolios');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('name')
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label(__('donor_financial_portfolio.name')),
                Tables\Columns\TextColumn::make('remainingBalance')
                    ->label(__('donor_financial_portfolio.remaining_balance'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable(true),
                Tables\Columns\TextColumn::make('allocated_amount')
                    ->label(__('donor_financial_portfolio.allocated_amount'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable(true),
                Tables\Columns\TextColumn::make('allocated_percentage')
                    ->label(__('donor_financial_portfolio.allocation_percentage'))
                    ->getStateUsing(function ($record) {
                        $order = $this->getOwnerRecord();
                        $approvedPrice = (float) ($order->finance?->approved_price ?? 0);
                        $allocatedAmount = (float) ($record->pivot->allocated_amount ?? 0);

                        if ($approvedPrice <= 0) {
                            return '0.00%';
                        }

                        $percentage = ($allocatedAmount / $approvedPrice) * 100;

                        return number_format($percentage, 2).'%';
                    })
                    ->sortable(false),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\AttachAction::make()
                    ->preloadRecordSelect()
                    ->form(fn (AttachAction $action): array => [
                        $action->getRecordSelect(),
                        ...$this->getAllocationFormSchema(),
                    ])
                    ->mutateFormDataUsing(function (array $data): array {
                        // Convert percentage to allocated_amount
                        $order = $this->getOwnerRecord();
                        $approvedPrice = (float) ($order->finance?->approved_price ?? 0);
                        $percentage = (float) ($data['allocation_percentage'] ?? 0);

                        $data['allocated_amount'] = ($approvedPrice * $percentage) / 100;
                        unset($data['allocation_percentage']); // Remove percentage from data

                        return $data;
                    }),
            ])
            ->actions([
                Tables\Actions\DetachAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DetachBulkAction::make(),
                ]),
            ]);
    }

    private function getAllocationFormSchema(): array
    {
        $order = $this->getOwnerRecord();
        $approvedPrice = (float) ($order->finance?->approved_price ?? 0);
        $currentTotal = $order->getTotalAllocatedFunding();
        $remainingAmount = $approvedPrice - $currentTotal;
        $remainingPercentage = $approvedPrice > 0 ? ($remainingAmount / $approvedPrice) * 100 : 0;

        return [
            Forms\Components\Grid::make(2)
                ->schema([
                    Forms\Components\Placeholder::make('approved_price_info')
                        ->label(__('order_finance.approved_price'))
                        ->content(fn () => number_format($approvedPrice, 2).' SAR'),

                    Forms\Components\Placeholder::make('remaining_amount_info')
                        ->label(__('donor_financial_portfolio.remaining_funding_needed'))
                        ->content(fn () => number_format($remainingAmount, 2).' SAR'),
                    // ->color($remainingAmount <= 0 ? 'success' : 'warning'),
                ]),

            Forms\Components\TextInput::make('allocation_percentage')
                ->label(__('donor_financial_portfolio.allocation_percentage'))
                ->required()
                ->numeric()
                ->suffix('%')
                ->minValue(0.01)
                ->maxValue($remainingPercentage)
                ->step(0.01)
                ->live()
                ->helperText(__('donor_financial_portfolio.allocation_percentage_helper'))
                ->rules([
                    function () use ($remainingPercentage) {
                        return function (string $attribute, $value, \Closure $fail) use ($remainingPercentage) {
                            if ($value > $remainingPercentage) {
                                $fail(__('donor_financial_portfolio.allocation_exceeds_remaining', [
                                    'max' => number_format($remainingPercentage, 2),
                                ]));
                            }
                        };
                    },
                ]),

            Forms\Components\Placeholder::make('calculated_amount')
                ->label(__('donor_financial_portfolio.allocated_amount'))
                ->content(function (Get $get) use ($approvedPrice) {
                    $percentage = (float) ($get('allocation_percentage') ?? 0);
                    $amount = ($approvedPrice * $percentage) / 100;

                    return number_format($amount, 2).' SAR';
                })
                ->live(),
        ];
    }

    public function isReadOnly(): bool
    {
        return false;
    }
}
