<?php

namespace App\Filament\Resources;

use App\Enums\BookingItemStatus;
use App\Enums\PaymentStatus;
use App\Filament\Resources\BookingItemResource;
use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Filament\Resources\UserResource\RelationManagers\UserPaymentDetailsRelationManager;
use App\Models\User;
use App\Models\Transaction;
use Filament\Forms;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Filament\Exports\UserExporter;
use Filament\Actions\Exports\Enums\ExportFormat;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\BulkActionGroup;
use Filament\Tables\Actions\DeleteBulkAction;
use Filament\Tables\Actions\EditAction;
use Filament\Tables\Actions\ViewAction;
use Filament\Tables\Actions\DeleteAction;
use Filament\Tables\Actions\Action;
use Filament\Tables\Actions\ExportBulkAction;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\DatePicker;

class UserResource extends Resource
{
    protected static ?int $navigationSort = 1;
    public static function getNavigationGroup(): ?string
    {
        return __('User Management');
    }
    protected static ?string $model = User::class;

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

    public static function getLabel(): ?string
    {
        return __('User');
    }

    public static function getPluralLabel(): ?string
    {
        return __('Users');
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('User Information'))
                    ->description(__('Basic user profile details.'))
                    ->schema([
                        TextInput::make('first_name')
                            ->label(__('First Name'))
                            ->required()
                            ->disabledOn('edit')
                            ->maxLength(255),
                        TextInput::make('last_name')
                            ->label(__('Last Name'))
                            ->required()
                            ->disabledOn('edit')
                            ->maxLength(255),
                        TextInput::make('email')
                            ->label(__('Email'))
                            ->email()
                            ->disabledOn('edit')
                            ->required()
                            ->maxLength(255),
                        TextInput::make('phone')
                            ->label(__('Phone'))
                            ->tel()
                            ->disabledOn('edit')
                            ->required()
                            ->maxLength(255),
                        TextInput::make('password')
                            ->label(__('Password'))
                            ->password()
                            ->disabledOn('edit')
                            ->required()
                            ->hiddenOn('edit'),
                        Toggle::make('is_active')
                            ->label(__('Is Active'))
                            ->default(true)
                            ->required(),
                    ])->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('id')
                    ->label(__('ID'))
                    ->sortable(),
                TextColumn::make('first_name')->label(__('First Name'))->searchable(),
                TextColumn::make('last_name')->label(__('Last Name'))->searchable(),
                TextColumn::make('email')->label(__('Email'))->searchable(),
                TextColumn::make('phone')->label(__('Phone'))->searchable(),
                IconColumn::make('is_active')
                    ->label(__('Is Active'))
                    ->boolean(),
                TextColumn::make('created_at')
                    ->label(__('Created At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('unpaid_refunded_amount')
                    ->label(__('Unpaid Amount'))
                    ->money('SAR')
                    ->sortable()
                    ->url(fn($record) => BookingItemResource::getUrl('index', ['tableFilters[user_id][values][0]' => $record->id, 'tableFilters[status][values]' => [BookingItemStatus::CANCELED->value, BookingItemStatus::DECLINED->value], 'tableFilters[payment_status][value]' => PaymentStatus::PAID->value, 'tableFilters[is_transfered][value]' => false]))
                    ->openUrlInNewTab(),
                TextColumn::make('refunded_amount')
                    ->label(__('Refunded Amount'))
                    ->money('SAR')
                    ->sortable()
                    ->url(fn($record) => BookingItemResource::getUrl('index', ['tableFilters[user_id][values][0]' => $record->id, 'tableFilters[status][values]' => [BookingItemStatus::CANCELED->value, BookingItemStatus::DECLINED->value], 'tableFilters[payment_status][value]' => PaymentStatus::PAID->value]))
                    ->openUrlInNewTab(),
                TextColumn::make('updated_at')
                    ->label(__('Updated At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                \Filament\Tables\Filters\TernaryFilter::make('is_active')
                    ->label(__('Is Active')),
                \Filament\Tables\Filters\TrashedFilter::make(),
                Filter::make('created_at')
                    ->form([
                        DatePicker::make('created_from')->label(__('created_from')),
                        DatePicker::make('created_until')->label(__('created_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn(Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
                            )
                            ->when(
                                $data['created_until'],
                                fn(Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
                            );
                    })
            ])
            ->actions([
                ViewAction::make()
                    ->label(__('View')),
                EditAction::make()
                    ->label(__('Edit'))
                    ->visible(fn($record) => !$record->trashed()),
                DeleteAction::make()
                    ->label(__('Delete'))
                    ->before(function (DeleteAction $action, User $record) {
                        $record->load('upcomingBookingItems');
                        if ($record->upcomingBookingItems->isNotEmpty()) {
                            $lastBookingDate = $record->upcomingBookingItems->max('service_date');
                            Notification::make()
                                ->title(__('User Deletion Failed'))
                                ->body(__(':name could not be deleted. They have :count upcoming bookings, with the last one on :date.', [
                                    'name' => $record->name,
                                    'count' => $record->upcomingBookingItems->count(),
                                    'date' => $lastBookingDate,
                                ]))
                                ->danger()
                                ->send();
                            $action->cancel();
                        }
                    }),
                // Action::make('Restore')
                //     ->color('success')
                //     ->label(__('Restore'))
                //     ->visible(fn(User $record) => $record->trashed())
                //     ->action(fn(User $record) => $record->restore())
                //     ->requiresConfirmation()
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->label(__('Delete selected'))
                        ->before(function (DeleteBulkAction $action, \Illuminate\Database\Eloquent\Collection $records) {
                            $records->load('upcomingBookingItems');
                            $problematicRecords = $records->filter(fn($record) => $record->upcomingBookingItems->isNotEmpty());

                            if ($problematicRecords->isNotEmpty()) {
                                $names = $problematicRecords->pluck('name')->join(', ');
                                Notification::make()
                                    ->title(__('User Deletion Failed'))
                                    ->body(__(':names could not be deleted because they have upcoming bookings.', ['names' => $names]))
                                    ->danger()
                                    ->send();
                                $action->cancel();
                            }
                        }),
                    // ExportBulkAction::make()
                    //     ->exporter(UserExporter::class)
                    //     ->formats([
                    //         ExportFormat::Xlsx,
                    //         ExportFormat::Csv,
                    //     ])
                    //     ->label(__('Export selected')),
                ]),
            ])
            ->headerActions([
                // ExportAction::make()
                //     ->exporter(UserExporter::class)
                //     ->formats([
                //         ExportFormat::Xlsx,
                //         ExportFormat::Csv,
                //     ])
                //     ->label(__('Export')),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            // RelationManagers\AddressesRelationManager::class,
            // RelationManagers\UserPaymentDetailsRelationManager::class,
            // RelationManagers\PurchaseTransactionsRelationManager::class,
            // RelationManagers\SellTransactionsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUsers::route('/'),
            // 'create' => Pages\CreateUser::route('/create'),
            'view' => Pages\ViewUser::route('/{record}'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with('refundedBookingItems')->withTrashed();
    }
}
