<?php

namespace App\Filament\Clusters\Cards\Cards;

use App\Filament\Clusters\Cards\Cards\Pages\ManageCards;
use App\Filament\Clusters\Cards\CardsCluster;
use App\Modules\AppHelpers\Repositories\DateHelper;
use App\Modules\Card\Models\Card;
use App\Modules\CardBalance\Repositories\CardBalanceRepository;
use App\Modules\CardRequisite\Repositories\CardRequisiteRepository;
use App\Modules\CardTransaction\Repositories\CardTransactionRepository;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;

class CardResource extends Resource
{
    protected static ?int $navigationSort = 1;

    protected static ?string $model = Card::class;

    protected static ?string $cluster = CardsCluster::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCreditCard;

    public static function getNavigationLabel(): string
    {
        return __('My cards');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('Cards');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->columns(3)
            ->components([
                Hidden::make('user_id')
                    ->default(fn () => user()->id),

                TextInput::make('number')
                    ->label(__('Card number'))
                    ->mask('9999 9999 9999 9999')
                    ->dehydrateStateUsing(fn ($state) => str_replace(' ', '', $state))
                    ->columnSpan(1)
                    ->required(),

                Select::make('month')
                    ->label(__('Card month'))
                    ->options(DateHelper::staticNumberMonths())
                    ->native(false)
                    ->columnSpan(1)
                    ->required(),

                Select::make('year')
                    ->label(__('Card year'))
                    ->options(DateHelper::staticNumberYears())
                    ->native(false)
                    ->columnSpan(1)
                    ->required(),

                TextInput::make('name')
                    ->label(__('Card name'))
                    ->maxLength(255)
                    ->columnSpanFull()
                    ->required(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query) {
                $query->where('user_id', user()->id);
            })
            ->columns([
                TextColumn::make('number')
                    ->label(__('Card number'))
                    ->formatStateUsing(fn ($state) => trim(chunk_split($state, 4, ' ')))
                    ->searchable(),

                TextColumn::make('name')
                    ->label(__('Card name'))
                    ->searchable(),

                TextColumn::make('month')
                    ->label(__('Card month'))
                    ->searchable(),

                TextColumn::make('year')
                    ->label(__('Card year'))
                    ->searchable(),

                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->recordActions([
                Action::make('card_balance')
                    ->label(__('Card balance'))
                    ->icon('heroicon-o-credit-card')
                    ->requiresConfirmation(false)
                    ->modal()
                    ->modalContent(fn (Card $record): View => CardBalanceRepository::make()->showCardBalance($record))
                    ->modalFooterActions([]),

                Action::make('card_transactions')
                    ->label(__('Card transactions'))
                    ->icon('heroicon-o-arrows-right-left')
                    ->requiresConfirmation()
                    ->modalIcon('heroicon-m-arrows-right-left')
                    ->schema([
                        DatePicker::make('start_date')
                            ->label(__('Start date'))
                            ->native(false)
                            ->required()
                            ->beforeOrEqual('today'),

                        DatePicker::make('end_date')
                            ->label(__('End date'))
                            ->native(false)
                            ->required()
                            ->beforeOrEqual('today'),
                    ])
                    ->action(
                        fn (array $data, Card $record, Component $livewire) => CardTransactionRepository::make()->downloadCardTransaction($data, $record, $livewire)
                    ),

                Action::make('card_requisite')
                    ->label(__('Card requisite'))
                    ->icon('heroicon-o-document-text')
                    ->requiresConfirmation()
                    ->modalIcon('heroicon-o-document-text')
                    ->action(fn (Card $record) => CardRequisiteRepository::make()->downloadCardRequisite($record)),

                EditAction::make()
                    ->label(''),
                DeleteAction::make()
                    ->label(''),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageCards::route('/'),
        ];
    }
}
