<?php

namespace App\Filament\AssociationAdmin\Resources;

use App\Enums\AssociationType;
use App\Filament\AssociationAdmin\Resources\AssociationOrderResource\Pages;
use App\Filament\AssociationAdmin\Resources\AssociationOrderResource\RelationManagers\AssociationRequirementsRelationManager;
use App\Models\Association;
use App\Models\Order;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class AssociationOrderResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = Order::class;

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

    protected static ?int $navigationSort = 1;

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

    public static function getPluralModelLabel(): string
    {
        return __('order.orders');
    }

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

            // Order Management approvals
            'request_order_recommendation',
            'provide_order_recommendation',
            'request_technical_financial_proposal',
            'approve_technical_financial_proposal',
            'approve_project_manager',
            'handle_classification',
            'handle_agreement',
            'approve_ceo',
            'launch_project',
            'accept_order',

            // Order Requirements
            'accept_order_requirement',
            'reject_order_requirement',
            'delete_order_requirement',

            // tabs list permissions
            'view_all_orders',
            'view_created_orders',
            'view_pending_recommendation_orders',
            'view_recommended_orders',
            'view_technical_financial_requested_orders',
            'view_technical_financial_approved_orders',
            'view_project_manager_approved_orders',
            'view_classification_orders',
            'view_agreement_orders',
            'view_ceo_approved_orders',
            'view_launched_orders',
            'view_accepted_orders',
            'view_rejected_orders',
        ];
    }

    public static function form(Form $form): Form
    {
        // Get the base form from OrderResource
        $baseForm = \App\Filament\Resources\OrderResource::form($form);

        // Override the status field to use association-specific labels
        return $baseForm->schema([
            Forms\Components\Section::make(__('order.order_information'))
                ->schema(static::getAssociationOrderInformationFields())
                ->columns(2),

            Forms\Components\Section::make(__('order.location_information'))
                ->schema(\App\Filament\Resources\OrderResource::getLocationInformationFields())
                ->columns(2),

            Forms\Components\Section::make(__('order.water_source_information'))
                ->schema(\App\Filament\Resources\OrderResource::getWaterSourceInformationFields())
                ->columns(2),

            Forms\Components\Section::make(__('order.project_details'))
                ->schema(\App\Filament\Resources\OrderResource::getProjectDetailsFields())
                ->columns(1),

            Forms\Components\Section::make(__('order.required_files'))
                ->schema(function (Get $get) {
                    return \App\Filament\Resources\OrderResource::getRequiredFilesFields($get);
                })
                ->collapsed(false),

            Forms\Components\Section::make(__('order_finance.order_finance'))
                ->schema(function (Get $get) {
                    return \App\Filament\Resources\OrderResource::getOrderFinanceFields($get);
                })
                ->columns(2)
                ->visible(function (Get $get) {
                    return \App\Filament\Resources\OrderResource::shouldShowFinanceSection($get);
                })
                ->collapsed(false),

            Forms\Components\Section::make(__('order_agreement.order_agreement'))
                ->schema(function (Get $get) {
                    return \App\Filament\Resources\OrderResource::getOrderAgreementFields($get);
                })
                ->columns(2)
                ->visible(function (Get $get) {
                    return \App\Filament\Resources\OrderResource::shouldShowAgreementSection($get);
                })
                ->collapsed(false),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query) {
                $user = Auth::user();
                if ($user && $user->association_id) {
                    $query->where('association_id', $user->association_id);
                } else {
                    // If user has no association, show no orders for security
                    $query->whereRaw('1 = 0');
                }
            })
            ->columns([

                Tables\Columns\TextColumn::make('id')
                    ->searchable()
                    ->sortable()
                    ->label(__('order.order_number')),

                Tables\Columns\BadgeColumn::make('type')
                    ->colors([
                        'primary' => Order::TYPE_STATION,
                        'success' => Order::TYPE_TANKER,
                        'warning' => Order::TYPE_DOMESTIC_STORAGE_TANK,
                        'info' => Order::TYPE_CENTRAL_STORAGE_TANK,
                        'secondary' => Order::TYPE_MAINTENANCE_STATION,
                        'danger' => Order::TYPE_MAINTENANCE_TANKER,
                        'primary' => Order::TYPE_MICRO_NETWORK,
                        'gray' => Order::TYPE_OTHER,
                        'success' => Order::TYPE_WELL_DRILLING,
                        'info' => Order::TYPE_RAINWATER_STORAGE,
                        'warning' => Order::TYPE_HOME_FILTERS,
                        'secondary' => Order::TYPE_WATER_BOTTLES,
                        'primary' => Order::TYPE_COOLERS,
                        'gray' => Order::TYPE_PRODUCTS_UNDER_REVIEW,
                    ])
                    ->label(__('order.order_type'))
                    ->formatStateUsing(fn (string $state): string => __(Order::getOrderTypes()[$state] ?? $state)),

                Tables\Columns\BadgeColumn::make('status')
                    ->colors([
                        'warning' => Order::STATUS_CREATED,
                        'primary' => Order::STATUS_PENDING_RECOMMENDATION,
                        'success' => Order::STATUS_RECOMMENDED,
                        'info' => Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED,
                        'info' => Order::STATUS_TECHNICAL_FINANCIAL_APPROVED,
                        'secondary' => Order::STATUS_PROJECT_MANAGER_APPROVED,
                        'primary' => Order::STATUS_CLASSIFICATION,
                        'secondary' => Order::STATUS_AGREEMENT,
                        'info' => Order::STATUS_CEO_APPROVED,
                        'gray' => Order::STATUS_LAUNCHED,
                        'success' => Order::STATUS_ACCEPTED,
                        'danger' => Order::STATUS_REJECTED,
                    ])
                    ->formatStateUsing(fn (string $state): string => static::getAssociationOrderStatuses()[$state] ?? $state)
                    ->label(__('order.status')),

                Tables\Columns\TextColumn::make('centers.name')
                    ->label(__('order.centers'))
                    ->searchable(),

                Tables\Columns\TextColumn::make('number_of_families')
                    ->label(__('order.number_of_families'))
                    ->searchable(),

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

            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label(__('order.order_type'))
                    ->options(collect(Order::getOrderTypes())->mapWithKeys(fn ($value, $key) => [$key => __($value)])),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    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 [
            AssociationRequirementsRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\AssociationListOrders::route('/'),
            'create' => Pages\AssociationCreateOrder::route('/create'),
            'view' => Pages\AssociationViewOrder::route('/{record}'),
            'edit' => Pages\AssociationEditOrder::route('/{record}/edit'),
        ];
    }

    /**
     * Get association-specific order status translations
     */
    public static function getAssociationOrderStatuses(): array
    {
        return [
            Order::STATUS_CREATED => 'تحت الدراسة',
            Order::STATUS_PENDING_RECOMMENDATION => 'تحت الدراسة',
            Order::STATUS_RECOMMENDED => 'تحت الدراسة',
            Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED => 'بانتظار استكمال المتطلبات',
            Order::STATUS_TECHNICAL_FINANCIAL_APPROVED => 'تحت الدراسة',
            Order::STATUS_PROJECT_MANAGER_APPROVED => 'تحت الدراسة',
            Order::STATUS_CEO_APPROVED => 'بانتظار توقيع الاتفاقية',
            Order::STATUS_CLASSIFICATION => 'تحت الدراسة',
            Order::STATUS_AGREEMENT => 'منفذ',
            Order::STATUS_LAUNCHED => 'طلب معتمد',
            Order::STATUS_ACCEPTED => 'طلب معتمد',
            Order::STATUS_REJECTED => 'مرفوض',
        ];
    }

    /**
     * Get the association-specific order information form fields (with custom status labels)
     */
    public static function getAssociationOrderInformationFields(): array
    {
        return [
            Forms\Components\Select::make('association_id')
                ->label(__('order.association'))
                ->relationship('association', 'name')
                ->required()
                ->searchable()
                ->preload(),

            Forms\Components\Select::make('type')
                ->required()
                ->options(collect(Order::getOrderTypes())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->default(Order::TYPE_STATION)
                ->label(__('order.order_type'))
                ->live()
                ->afterStateUpdated(function (Set $set, $state) {
                    // Clear files when type changes
                    $requirements = Order::getTypeFileRequirements()[$state] ?? [];
                    foreach ($requirements as $fileKey => $fileTitle) {
                        $set($fileKey, null);
                    }
                }),

            // status - using association-specific labels
            Forms\Components\Select::make('status')
                ->label(__('order.status'))
                ->options(static::getAssociationOrderStatuses())
                ->default(Order::STATUS_PENDING_RECOMMENDATION)
                ->required()
                ->searchable()
                ->preload(),

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

    public static function canAccess(): bool
    {
        $association = Auth::user()->association;
        if ($association->type !== AssociationType::ASSOCIATION) {
            return false;
        }

        return static::canViewAny();
    }
}
