<?php

namespace App\Filament\Office\Resources\BillofladingResource\RelationManagers;

use Filament\Forms;
use Filament\Tables;
use App\Models\Tracking;
use Filament\Forms\Form;
use Filament\Tables\Table;
use Illuminate\Support\Str;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Group;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\RichEditor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Resources\RelationManagers\RelationManager;

class TrackingRelationManager extends RelationManager
{
    protected static string $relationship = 'trackings';

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Group::make()
                    ->schema([
                        Section::make('Status')
                            ->schema([
                                DatePicker::make('date')->required(),
                                Select::make('status')->options([
                                        'port_arrived' => 'Arrived at port', 
                                        'port_ready_to_ship' => 'In port (Ready to ship)', 
                                        'port_way_to' => 'In port (On the way to Warehouse)', 
                                        'port_transshipment' => 'Transshipment port', 
                                        'on_board' => 'On Board', 
                                        'warehouse_inside' => 'Inside Warehouse', 
                                        'warehouse_loading' => 'Loading at Warehouse', 
                                        'warehouse_unloading' => 'Unloading at Warehouse'
                                    ])->default('warehouse_inside')->searchable()->required(),
                                TextInput::make('status_details')
                                    ->maxLength(255)
                                    ->columnSpanFull(),
                                RichEditor::make('description')
                                    ->columnSpanFull(),
                            ])->columns(['lg' => 2]),
                    ])
                    ->columnSpan(['lg' => 2]),
                Group::make()
                    ->schema([
                        Section::make('Relation')
                            ->schema([
                                Select::make('bl_id')->label('BL Number')
                                    // ->options(\App\Models\Company::all()->pluck('name', 'id'))
                                    ->relationship('bl', 'bl_no', fn (Builder $query) => $query->withTrashed())
                                    ->required()
                                    ->searchable()
                                    ->reactive()
                                    ->preload()
                                    ->createOptionForm([
                                        // Self::getCustomerAddForm()
                                    ]),

                                Select::make('port_id')
                                    // ->options(\App\Models\Port::all()->pluck('name', 'id'))
                                    ->relationship('port', 'name', fn (Builder $query) => $query->withTrashed())
                                    ->searchable()
                                    ->reactive()
                                    ->createOptionForm([
                                        Self::getPortAddForm()
                                    ]),
                                
                                Select::make('vessel_id')->label('Vessel')
                                    // ->options(\App\Models\Vessel::all()->pluck('name', 'id'))
                                    ->relationship('vessel', 'name', fn (Builder $query) => $query->withTrashed())
                                    ->searchable()
                                    ->reactive()
                                    ->createOptionForm([
                                        Self::getVesselAddForm()
                                    ]),
                            ]),
                    ])
                    ->columnSpan(['lg' => 1]),
            ])
            ->columns(3);
    }

    static protected function getPortAddForm() : Grid {
        return Grid::make('Add New Port')->schema([
            TextInput::make('name')
                ->helperText('Enter full name of port here (no iso or country code).')
                ->required()
                ->minLength(2)
                ->maxLength(100),
            Select::make('country_id')
                ->relationship('country', 'name')
                ->searchable()
                ->required(),
            TextInput::make('latitude')->numeric(),
            TextInput::make('longitude')->numeric(),
            TextInput::make('iso')->label('ISO')
                ->helperText('ISO is the unique identifier for a port.')
                ->minLength(2)
                ->maxLength(3)
                ->required(),
            Select::make('type')
                ->options([
                    'inland' => 'Inland',
                    'dry' => 'Dry',
                    'fishing' => 'Fishing',
                    'warm-water' => 'Warm Water',
                    'seaports' => 'Seaports',
                ]),
        ])->columns(2);
    }

    static protected function getVesselAddForm() : Grid {
        return Grid::make('Add New Delivery Agent')->schema([
            TextInput::make('name')
                ->unique(ignorable: fn ($record) => $record)
                ->helperText('Write new vessel name here')
                ->minLength(3)
                ->maxLength(100),
            TextInput::make('capacity')
                ->helperText('Capacity with tues')
                ->minLength(1),
            Select::make('route_start')
                ->label('Starting Port')
                ->relationship('port_start', 'name')
                ->searchable(),
            Select::make('route_end')
                ->label('Destination Port')
                ->relationship('port_end', 'name')
                ->searchable(),
        ])->columns(2);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('bl_no')
            ->columns([
                Tables\Columns\TextColumn::make('bl.bl_no')
                    ->label('BL Number')
                    ->description(fn (Tracking $record): string => \Carbon\Carbon::parse($record->date)->since())
                    ->sortable()
                    ->searchable(),
                // Tables\Columns\TextColumn::make('port.name')
                //     ->numeric()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('vessel.name')
                //     ->numeric()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('date')
                //     ->date()
                //     ->since()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->description(fn (Tracking $record): string => ($record->port != null)?$record->port->name . (($record->vessel != null)?' ⋅ ' . $record->vessel->name:''):'')
                    ->formatStateUsing(fn (Tracking $record): string => Str::headline($record->status))
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'port_arrived' => 'success', 
                        'port_ready_to_ship' => 'primary', 
                        'port_way_to' => 'indigo', 
                        'port_transshipment' => 'danger', 

                        'on_board' => 'warning', 

                        'warehouse_inside' => 'indigo', 
                        'warehouse_loading' => 'info', 
                        'warehouse_unloading' => 'primary'
                    })
                    ->html()
                    ->searchable(),
                Tables\Columns\TextColumn::make('status_details')
                    ->searchable()
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_at')->label('Added')
                    ->dateTime()
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')->label('Updated')
                    ->dateTime()
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')->label('Deleted')
                    ->dateTime()
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->emptyStateActions([
                Tables\Actions\CreateAction::make(),
            ]);
    }
}
