<?php

declare(strict_types=1);

namespace App\Filament\Resources\Payments\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Enums\Status;
use App\Models\Payment;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class PaymentsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                \App\Filament\Components\Table\UserTextColumn::create(),
                TextColumn::make('project.name')
                    ->label('پروژه')
                    ->sortable()
                    ->toggleable()
                    ->toggledHiddenByDefault(),
                \App\Filament\Components\Table\TransactionIdTextColumn::create(),
                \App\Filament\Components\Table\RefIdTextColumn::create(),
                \App\Filament\Components\Table\RefUrlTextColumn::create(),
                \App\Filament\Components\Table\PriceTextColumn::create(),
                TextColumn::make('cellphone')
                    ->label('شماره همراه')
                    ->searchable()
                    ->sortable()
                    ->toggleable()
                    ->toggledHiddenByDefault(),
                TextColumn::make('email')
                    ->label('ایمیل')
                    ->searchable()
                    ->sortable()
                    ->toggleable()
                    ->toggledHiddenByDefault(),
                TextColumn::make('card_number')
                    ->label('شماره کارت')
                    ->searchable()
                    ->sortable()
                    ->toggleable()
                    ->toggledHiddenByDefault(),
                \App\Filament\Components\Table\TokenTextColumn::create(),
                \App\Filament\Components\Table\GatewayTextColumn::create(),
                \App\Filament\Components\Table\ModelTypeTextColumn::create(),
                \App\Filament\Components\Table\ModelTextColumn::create(),
                \App\Filament\Components\Table\StatusTextColumn::create(Payment::class),
                \App\Filament\Components\Table\CreatedByTextColumn::create(),
                \App\Filament\Components\Table\UpdatedByTextColumn::create(),
                \App\Filament\Components\Table\CreatedAtTextColumn::create(),
            ])
            ->filters([
                TrashedFilter::make(),
                Filter::make('date_range')
                    ->label('بازه زمانی')
                    ->schema([
                        DatePicker::make('date_from')->label('از تاریخ')->jalali(),
                        DatePicker::make('date_to')->label('تا تاریخ')->jalali(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        if (filled($data['date_from'] ?? null)) {
                            $query->whereDate('created_at', '>=', $data['date_from']);
                        }
                        if (filled($data['date_to'] ?? null)) {
                            $query->whereDate('created_at', '<=', $data['date_to']);
                        }
                        return $query;
                    }),
                SelectFilter::make('project_id')
                    ->label('پروژه')
                    ->relationship('project', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::project($record))
                    ->searchable()
                    ->preload(),
                SelectFilter::make('user_id')
                    ->label('حساب کاربری')
                    ->relationship('user', 'first_name', function (Builder $query, ?string $search = null): Builder {
                        if (filled($search)) {
                            $query->where(function (Builder $q) use ($search): void {
                                $q->where('first_name', 'like', "%{$search}%")
                                    ->orWhere('last_name', 'like', "%{$search}%")
                                    ->orWhere('cellphone', 'like', "%{$search}%")
                                    ->orWhere('email', 'like', "%{$search}%")
                                    ->orWhere('national_code', 'like', "%{$search}%");
                            });
                        }
                        return $query;
                    })
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::user($record))
                    ->searchable(['first_name', 'last_name', 'cellphone', 'email', 'national_code'])
                    ->preload(),
                Filter::make('ref_id')
                    ->label('کد پیگیری')
                    ->form([TextInput::make('ref_id')->label('کد پیگیری / ref_id')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['ref_id'] ?? null),
                        fn (Builder $q) => $q->where('ref_id', 'like', '%' . $data['ref_id'] . '%')
                    )),
                Filter::make('transaction_id')
                    ->label('شناسه تراکنش')
                    ->form([TextInput::make('transaction_id')->label('شناسه تراکنش')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['transaction_id'] ?? null),
                        fn (Builder $q) => $q->where('transaction_id', 'like', '%' . $data['transaction_id'] . '%')
                    )),
                Filter::make('cellphone')
                    ->form([TextInput::make('cellphone')->label('شماره همراه')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['cellphone'] ?? null),
                        fn (Builder $q) => $q->where('cellphone', 'like', '%' . $data['cellphone'] . '%')
                    )),
                Filter::make('email')
                    ->form([TextInput::make('email')->label('ایمیل')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['email'] ?? null),
                        fn (Builder $q) => $q->where('email', 'like', '%' . $data['email'] . '%')
                    )),
                Filter::make('card_number')
                    ->form([TextInput::make('card_number')->label('شماره کارت')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['card_number'] ?? null),
                        fn (Builder $q) => $q->where('card_number', 'like', '%' . $data['card_number'] . '%')
                    )),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options(collect(Status::get())->mapWithKeys(fn ($state) => [$state['value'] => $state['label']])->all()),
            ])
            ->recordActions([
                ViewAction::make()
                    ->slideOver()
                    ->modalWidth('2xl'),
                EditAction::make(),
            ])
            ->headerActions([
                \Filament\Actions\ExportAction::make()
                    ->exporter(\App\Filament\Exports\PaymentExporter::class)
                    ->label('خروجی اکسل/CSV'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
