<?php

namespace App\Filament\Resources;

use App\Filament\Resources\RfqTransporterBidResource\Pages;
use App\Filament\Resources\RfqTransporterBidResource\RelationManagers;
use App\Models\RfqTransporterBid;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;


class RfqTransporterBidResource extends Resource
{
    protected static ?string $model = RfqTransporterBid::class;

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

    protected static ?string $navigationGroup = 'Request For Quotation';


    public static function getEloquentQuery(): Builder
    {
        $user = Filament::auth()->user();

        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ])
            ->when(
                ! $user->hasAnyRole(['Super Admin', 'TransporterBidSupervisor']),
                fn (Builder $query) => $query
                    ->where('transporter_name', $user->name)
                    ->whereNotNull('request_quotation_id')
            );
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('request_quotation_id')
                    ->label('RFQ Number')
                    // ->relationship('requestQuotation', 'rfq_number')
                    ->relationship(
                        'requestQuotation',
                        'rfq_number',
                        function (Builder $query) {

                            $userName = Filament::auth()->user()?->name;

                            $masterIds = \App\Models\SpotRateTransportMaster::whereRaw(
                                    "user_name::jsonb @> ?",
                                    [json_encode([$userName])]
                                )
                                ->pluck('id')
                                ->unique()
                                ->toArray();

                            if (empty($masterIds)) {
                                $query->whereRaw('1 = 0');
                                return;
                            }

                            $query->whereIn('spot_rate_transport_master_id', $masterIds);
                        }
                    )
                    ->reactive()
                    // ->disabled(fn ($record) => !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor']))
                    ->disabled(fn ($record) =>
                        !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor'])
                        && $record
                    )
                    ->afterStateUpdated(function ($state, callable $set) {
                        $rfq = \App\Models\RequestQuotation::find($state);
                        if ($rfq) {
                            $set('pickup_address', $rfq->pickup_address);
                            $set('delivery_address', $rfq->delivery_address);
                            $set('type_of_vehicle', $rfq->type_of_vehicle);
                            $set('weight', $rfq->weight);
                            $set('volumetrice_size_inch', $rfq->volumetrice_size_inch);
                            $set('no_of_vehicle', $rfq->no_of_vehicle);
                            $set('product_name', $rfq->product_name);
                            $set('pick_and_delivery', $rfq->pick_and_delivery);
                            $set('payment_term', $rfq->payment_term);
                            $set('paid_topay', $rfq->paid_topay);
                            $set('loading_by', $rfq->loading_by);
                            $set('unloading_by', $rfq->unloading_by);
                            $set('special_type', $rfq->special_type);
                            $set('rfq_date_time', $rfq->rfq_date_time);
                            $set('require_date_time', $rfq->require_date_time);
                            $set('rfq_rec_on_or_before', $rfq->rfq_rec_on_or_before);
                        }
                    })
                    ->afterStateHydrated(function ($state, callable $set) {
                        $rfq = \App\Models\RequestQuotation::find($state);
                        if ($rfq) {
                            $set('pickup_address', $rfq->pickup_address);
                            $set('delivery_address', $rfq->delivery_address);
                            $set('type_of_vehicle', $rfq->type_of_vehicle);
                            $set('weight', $rfq->weight);
                            $set('volumetrice_size_inch', $rfq->volumetrice_size_inch);
                            $set('no_of_vehicle', $rfq->no_of_vehicle);
                            $set('product_name', $rfq->product_name);
                            $set('pick_and_delivery', $rfq->pick_and_delivery);
                            $set('payment_term', $rfq->payment_term);
                            $set('paid_topay', $rfq->paid_topay);
                            $set('loading_by', $rfq->loading_by);
                            $set('unloading_by', $rfq->unloading_by);
                            $set('special_type', $rfq->special_type);
                            $set('rfq_date_time', $rfq->rfq_date_time);
                            $set('require_date_time', $rfq->require_date_time);
                            $set('rfq_rec_on_or_before', $rfq->rfq_rec_on_or_before);
                        }
                    })
                    ->required(),
                Forms\Components\Section::make('RFQ Details')
                    ->visible(fn ($get) => $get('request_quotation_id') != null)
                    ->reactive()
                    ->schema([
                        TextInput::make('pickup_address')->label('Pickup Address')->disabled(),
                        TextInput::make('delivery_address')->label('Delivery Address')->disabled(),
                        TextInput::make('type_of_vehicle')->label('Vehicle Type')->disabled(),
                        TextInput::make('weight')->label('Weight')->disabled(),
                        TextInput::make('volumetrice_size_inch')->label('Volumetric Size')->disabled(),
                        TextInput::make('no_of_vehicle')->label('No. of Vehicle')->disabled(),
                        TextInput::make('product_name')->label('Product Name')->disabled(),
                        TextInput::make('pick_and_delivery')->label('Pick & Delivery')->disabled(),
                        TextInput::make('payment_term')->label('Payment Term')->disabled(),
                        TextInput::make('paid_topay')->label('Paid / To Pay')->disabled(),
                        TextInput::make('loading_by')->label('Loading By')->disabled(),
                        TextInput::make('unloading_by')->label('Unloading By')->disabled(),
                        TextInput::make('special_type')->label('Special Type')->disabled(),
                        TextInput::make('rfq_date_time')->label('RFQ Created On')->disabled(),
                        TextInput::make('require_date_time')->label('Required Date')->disabled(),
                        TextInput::make('rfq_rec_on_or_before')->label('RFQ Received On/Before')->disabled(),
                    ]),
                Forms\Components\TextInput::make('transporter_name')
                    ->label('Transporter Name')
                    ->readOnly()
                    ->default(Filament::auth()->user()?->name)
                    ->required()
                    ->rule(function (callable $get) {
                        return Rule::unique('rfq_transporter_bids', 'transporter_name')
                            ->where('request_quotation_id', $get('request_quotation_id'))
                            ->ignore($get('id'));
                    }),
                Forms\Components\TextInput::make('total_freight_charge')
                    ->label('Total Freight Charge')
                    ->required()
                    // ->disabled(fn ($record) => $record && $record->created_by != Filament::auth()->user()?->name)
                    // ->hidden(fn ($record) => !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor']) && $record->transporter_name != Filament::auth()->user()?->name),
                    ->hidden(fn ($record) =>
                        !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor'])
                        && ($record && $record->transporter_name != Filament::auth()->user()?->name) // Ensure $record is not null before checking transporter_name
                ),
                Forms\Components\TextInput::make('transit_day')
                    ->label('Transit Day')
                    ->required()
                    // ->disabled(fn ($record) => $record && $record->created_by != Filament::auth()->user()?->name),
                    // ->hidden(fn ($record) => !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor']) && $record->transporter_name != Filament::auth()->user()?->name),
                ->hidden(fn ($record) =>
                    !Filament::auth()->user()?->hasAnyRole(['Super Admin', 'TransporterBidSupervisor'])
                    && ($record && $record->transporter_name != Filament::auth()->user()?->name) // Ensure $record is not null before checking transporter_name
                ),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By')
                    ->default(Filament::auth()->user()?->name),
                ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->alignCenter()
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('requestQuotation.rfq_number')
                    ->label('RFQ Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.pickup_address')
                    ->label('PickUp Address')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.delivery_address')
                    ->label('Delivery Address')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.type_of_vehicle')
                    ->label('Type Of Vehicle')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.weight')
                    ->label('Weight')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.volumetrice_size_inch')
                    ->label('Volumetrice Size Inch')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.no_of_vehicle')
                    ->label('No Of Vehicle')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.product_name')
                    ->label('Product Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.pick_and_delivery')
                    ->label('Pick And Delivery')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.payment_term')
                    ->label('Payment Term')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.paid_topay')
                    ->label('Paid Today')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.loading_by')
                    ->label('Loading By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.unloading_by')
                    ->label('Unloading By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.special_type')
                    ->label('Special Type')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.rfq_date_time')
                    ->label('RFQ DateTime')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.require_date_time')
                    ->label('RFQ Require DateTime')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('requestQuotation.rfq_rec_on_or_before')
                    ->label('RFQ Rec On Or Before')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListRfqTransporterBids::route('/'),
            'create' => Pages\CreateRfqTransporterBid::route('/create'),
            'view' => Pages\ViewRfqTransporterBid::route('/{record}'),
            'edit' => Pages\EditRfqTransporterBid::route('/{record}/edit'),
        ];
    }

    // public static function getEloquentQuery(): Builder
    // {
    //     return parent::getEloquentQuery()
    //         ->withoutGlobalScopes([
    //             SoftDeletingScope::class,
    //         ]);
    // }
}
