<?php

namespace App\Filament\Resources;

use App\Filament\Resources\DonorFinancialPortfolioResource\Pages;
use App\Models\DonorFinancialPortfolio;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;

class DonorFinancialPortfolioResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = DonorFinancialPortfolio::class;

    protected static ?string $navigationIcon = 'heroicon-o-banknotes';

    protected static ?int $navigationSort = 6;

    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 static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.donors');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make(__('donor_financial_portfolio.portfolio_information'))
                    ->description(__('donor_financial_portfolio.portfolio_information_description'))
                    ->schema([
                        TextInput::make('name')
                            ->label(__('donor_financial_portfolio.name'))
                            ->required()
                            ->maxLength(255)
                            ->placeholder(__('donor_financial_portfolio.name_placeholder')),

                        TextInput::make('balance')
                            ->label(__('donor_financial_portfolio.balance'))
                            ->required()
                            ->numeric()
                            ->prefix('SAR')
                            ->step(0.01)
                            ->minValue(0)
                            ->helperText(__('donor_financial_portfolio.balance_helper')),

                        TextInput::make('operating_percentage')
                            ->label(__('donor_financial_portfolio.operating_percentage'))
                            ->required()
                            ->numeric()
                            ->suffix('%')
                            ->step(0.01)
                            ->minValue(0)
                            ->maxValue(100)
                            ->placeholder(__('donor_financial_portfolio.operating_percentage_placeholder'))
                            ->helperText(__('donor_financial_portfolio.operating_percentage_helper')),

                        Select::make('tags')
                            ->columnSpanFull()
                            ->label(__('donor_financial_portfolio.tags'))
                            ->multiple()
                            ->relationship('tags', 'name')
                            ->searchable()
                            ->preload()
                            ->live()
                            ->createOptionForm([
                                TextInput::make('name')
                                    ->label(__('donor_financial_portfolio.tag'))
                                    ->required()
                                    ->unique()
                                    ->maxLength(255),
                            ])
                            ->createOptionAction(function (Action $action) {
                                return $action->modalHeading(__('donor_financial_portfolio.new_tag'));
                            }),
                    ])
                    ->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label(__('donor_financial_portfolio.name'))
                    ->searchable()
                    ->sortable(),

                TextColumn::make('balance')
                    ->label(__('donor_financial_portfolio.balance'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('operating_percentage')
                    ->label(__('donor_financial_portfolio.operating_percentage'))
                    ->numeric(2)
                    ->suffix('%')
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('total_operating_value')
                    ->label(__('donor_financial_portfolio.total_operating_value'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('total_allocated')
                    ->label(__('donor_financial_portfolio.total_allocated'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('remaining_balance')
                    ->label(__('donor_financial_portfolio.remaining_balance'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->toggleable()
                    ->color(fn ($state) => $state < 0 ? 'danger' : ($state == 0 ? 'warning' : 'success')),

                TextColumn::make('orders_count')
                    ->label(__('donor_financial_portfolio.orders_count'))
                    ->counts('orders')
                    ->badge()
                    ->toggleable(),

                TextColumn::make('creator.name')
                    ->label(__('common.created_by'))
                    ->sortable()
                    ->toggleable(),

                TextColumn::make('created_at')
                    ->label(__('donor_financial_portfolio.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                TextColumn::make('updated_at')
                    ->label(__('donor_financial_portfolio.updated_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\Filter::make('has_balance')
                    ->label(__('donor_financial_portfolio.has_balance'))
                    ->query(fn (Builder $query): Builder => $query->whereRaw('balance > (
                        SELECT COALESCE(SUM(allocated_amount), 0)
                        FROM donor_portfolio_order
                        WHERE donor_financial_portfolio_id = donor_financial_portfolios.id
                    )')),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListDonorFinancialPortfolios::route('/'),
            'create' => Pages\CreateDonorFinancialPortfolio::route('/create'),
            'view' => Pages\ViewDonorFinancialPortfolio::route('/{record}'),
            'edit' => Pages\EditDonorFinancialPortfolio::route('/{record}/edit'),
        ];
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',

            // custom for dashboard
            'view_all_portfolios',
        ];
    }
}
