<?php

namespace App\Filament\Resources;

use App\Filament\Exports\ExchangeRequestExporter;
use App\Filament\Resources\ExchangeRequestResource\Pages;
use App\Models\CompletionReport;
use App\Models\ExchangeRequest;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class ExchangeRequestResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ExchangeRequest::class;

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

    protected static ?int $navigationSort = 7;

    public static function getNavigationLabel(): string
    {
        return __('exchange_request.exchange_requests');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('exchange_request.exchange_requests');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.project_management');
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->ownScope();
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('exchange_request.request_details'))
                    ->description(__('exchange_request.request_details_description'))
                    ->schema([
                        Forms\Components\Select::make('completion_report_id')
                            ->label(__('exchange_request.completion_report'))
                            ->relationship('completionReport', 'description')
                            ->required()
                            ->searchable()
                            ->preload()
                            ->getOptionLabelFromRecordUsing(function (CompletionReport $record): string {
                                return "#{$record->id} - ".Str::limit($record->description, 50).' ($'.number_format((float) $record->value, 2).')';
                            })
                            ->disabled(fn (?ExchangeRequest $record) => $record !== null),

                        Forms\Components\Select::make('status')
                            ->label(__('exchange_request.status'))
                            ->options(ExchangeRequest::getStatuses())
                            ->default(ExchangeRequest::STATUS_DRAFT)
                            ->disabled()
                            ->required(),

                        Forms\Components\DatePicker::make('transaction_date')
                            ->label(__('exchange_request.transaction_date'))
                            ->placeholder(__('exchange_request.transaction_date_placeholder'))
                            ->maxDate(now())
                            ->helperText(__('exchange_request.transaction_date_helper')),

                        Forms\Components\Hidden::make('created_by')
                            ->default(fn () => Auth::id()),
                    ])
                    ->columns(2),

                Forms\Components\Section::make(__('exchange_request.additional_files'))
                    ->description(__('exchange_request.additional_files_description'))
                    ->relationship('completionReport')
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('er_files')
                            ->label(__('exchange_request.files'))
                            ->collection('er_files')
                            ->visibility('private')
                            ->multiple()
                            ->acceptedFileTypes([
                                'application/pdf',
                                'image/jpeg',
                                'image/png',
                                'image/jpg',
                            ])
                            ->maxSize(10240) // 10MB per file
                            ->maxFiles(5) // Limit to 5 files
                            ->downloadable()
                            ->helperText(__('exchange_request.files_helper')),
                    ])
                    ->columns(1),

                Forms\Components\Section::make(__('exchange_request.approval_workflow'))
                    ->description(__('exchange_request.approval_workflow_description'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('transaction_file')
                            ->label(__('exchange_request.transaction_file'))
                            ->collection('transaction_file')
                            ->visibility('private')
                            ->acceptedFileTypes([
                                'application/pdf',
                                'image/jpeg',
                                'image/png',
                                'image/jpg',
                            ])
                            ->maxSize(10240) // 10MB
                            ->downloadable()
                            ->helperText(__('exchange_request.transaction_file_helper')),
                    ])
                    ->columns(1),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label(__('exchange_request.id'))
                    ->sortable()
                    ->searchable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('completionReport.description')
                    ->label(__('completion_report.description'))
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->completionReport?->description)
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('completionReport.value')
                    ->label(__('completion_report.value'))
                    ->formatStateUsing(function ($state) {
                        return number_format((float) $state, 2);
                    })
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('transaction_date')
                    ->label(__('exchange_request.transaction_date'))
                    ->date()
                    ->sortable()
                    ->placeholder(__('common.not_set'))
                    ->toggleable(),

                BadgeColumn::make('status')
                    ->label(__('exchange_request.status'))
                    ->colors([
                        'slate' => 'draft',
                        'gray' => 'created',
                        'warning' => 'financial_approved',
                        'info' => 'shared_services_approved',
                        'primary' => 'ceo_approved',
                        'violet' => 'transaction_approved',
                        'success' => 'approved',
                        'danger' => 'rejected',
                    ])
                    ->formatStateUsing(function (string $state): string {
                        return match ($state) {
                            'draft' => __('exchange_request.status_draft'),
                            'created' => __('exchange_request.status_created'),
                            'financial_approved' => __('exchange_request.status_financial_approved'),
                            'shared_services_approved' => __('exchange_request.status_shared_services_approved'),
                            'ceo_approved' => __('exchange_request.status_ceo_approved'),
                            'transaction_approved' => __('exchange_request.status_transaction_approved'),
                            'approved' => __('exchange_request.status_approved'),
                            'rejected' => __('exchange_request.status_rejected'),
                            default => $state,
                        };
                    })
                    ->searchable()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('createdBy.name')
                    ->label(__('common.created_by'))
                    ->searchable()
                    ->sortable()
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->createdBy?->name)
                    ->toggleable(),

                Tables\Columns\IconColumn::make('has_transaction_file')
                    ->label(__('exchange_request.transaction_file'))
                    ->boolean()
                    ->getStateUsing(fn ($record) => $record->getFirstMedia('transaction_file') !== null)
                    ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('common.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label(__('common.updated_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('exchange_request.status'))
                    ->options([
                        'draft' => __('exchange_request.status_draft'),
                        'created' => __('exchange_request.status_created'),
                        'financial_approved' => __('exchange_request.status_financial_approved'),
                        'shared_services_approved' => __('exchange_request.status_shared_services_approved'),
                        'ceo_approved' => __('exchange_request.status_ceo_approved'),
                        'transaction_approved' => __('exchange_request.status_transaction_approved'),
                        'approved' => __('exchange_request.status_approved'),
                        'rejected' => __('exchange_request.status_rejected'),
                    ]),
            ])
            ->headerActions([
                ExportAction::make()
                    ->exporter(ExchangeRequestExporter::class),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make()
                    ->visible(fn ($record) => $record->status !== 'approved' && $record->status !== 'rejected'),
                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\ListExchangeRequests::route('/'),
            // 'create' => Pages\CreateExchangeRequest::route('/create'),
            'view' => Pages\ViewExchangeRequest::route('/{record}'),
            'edit' => Pages\EditExchangeRequest::route('/{record}/edit'),
        ];
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'delete',
            'delete_any',
            // Step-specific permissions
            'approve_created_er',
            'approve_financial_er',
            'approve_shared_services_er',
            'approve_ceo_er',
            'approve_final_er',

            'view_all',
        ];
    }

    public static function canCreate(): bool
    {
        return false;
    }
}
