<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PackingSlipResource\Pages;
use App\Models\Customer;
use App\Models\Order;
use App\Models\PackingSlip;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;

class PackingSlipResource extends Resource
{
    protected static ?string $model = PackingSlip::class;

    protected static ?string $navigationIcon = 'lucide-package';

    protected static ?string $navigationGroup = 'Management';

    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                DatePicker::make('date_received'),
                TextInput::make('amount'),
                Select::make('customer_id')
                    ->options(Customer::all()->pluck('company_name', 'id'))
                    ->reactive()
                    ->searchable(),
                Select::make('order_id')
                    ->options(fn ($get): array => Order::where('customer_id', $get('customer_id') ?? null)
                        ->get()
                        ->pluck('customer_po', 'id')
                        ->toArray())
                    ->searchable(),
                TextArea::make('contents'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('date_received')
                    ->sortable()
                    ->searchable(),
                TextColumn::make('order.customer_po')
                    ->weight('bold')
                    ->color('code')
                    ->sortable()
                    ->searchable(),
                TextColumn::make('contents'),
                TextColumn::make('amount'),
                TextColumn::make('order.customer.company_name')
                    ->sortable()
                    ->searchable(),
            ])
            ->defaultSort('date_received', 'desc')
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index'  => Pages\ListPackingSlips::route('/'),
            'create' => Pages\CreatePackingSlip::route('/create'),
            'edit'   => Pages\EditPackingSlip::route('/{record}/edit'),
        ];
    }
}
