<?php

namespace App\Filament\Resources;

use App\Enums\BookingItemStatus;
use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Filament\Resources\BookingItemResource\Pages;
use App\Filament\Resources\BookingItemResource\RelationManagers;
use App\Models\BookingItem;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class BookingItemResource extends Resource
{
    protected static ?int $navigationSort = 5;
    protected static ?string $model = BookingItem::class;

    public static function getNavigationGroup(): ?string
    {
        return __('Content Management');
    }

    protected static ?string $navigationIcon = 'heroicon-o-calendar-days';

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }

    public static function getLabel(): ?string
    {
        return __('Booking Item');
    }

    public static function getPluralLabel(): ?string
    {
        return __('Booking Items');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('booking_id')
                    ->label(__('Booking ID'))
                    ->relationship('booking', 'id')
                    ->disabled(),
                Forms\Components\Select::make('product_id')
                    ->label(__('Product'))
                    ->relationship('product', 'name_' . app()->getLocale())
                    ->disabled(),
                Forms\Components\TextInput::make('price')
                    ->label(__('Price'))
                    ->disabled()
                    ->numeric()
                    ->prefix('SAR'),
                Forms\Components\DatePicker::make('service_date')
                    ->label(__('Service Date'))
                    ->required(),
                Forms\Components\Select::make('service_provider_id')
                    ->label(__('Service Provider'))
                    ->relationship('serviceProvider', 'name')
                    ->disabled(),
                Forms\Components\Select::make('user_id')
                    ->label(__('User'))
                    ->relationship('user', 'first_name')
                    ->disabled(),
                Forms\Components\Textarea::make('notes')
                    ->label(__('Notes'))
                    ->columnSpanFull(),
                Forms\Components\TextInput::make('commission')
                    ->label(__('Commission'))
                    ->disabled()
                    ->numeric(),
                Forms\Components\TextInput::make('net_price')
                    ->label(__('Net Price'))
                    ->disabled()
                    ->numeric(),
                Forms\Components\Select::make('status')
                    ->label(__('Status'))
                    ->options(BookingItemStatus::options())
                    ->required(),
                Forms\Components\Toggle::make('is_transfered')
                    ->label(__('Is Transfered')),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->numeric()
                    ->label(__("ID")),
                Tables\Columns\TextColumn::make('booking_id')
                    ->label(__('Booking ID'))
                    ->url(fn($record) => BookingResource::getUrl('view', ['record' => $record->booking_id]))
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('product.name_' . app()->getLocale())
                    ->label(__('Product'))
                    ->url(
                        fn($record) =>
                        // dd($record->product->type)
                        $record->product->type == "service" ?
                            ServiceResource::getUrl('index', ['tableFilters[id][id]' => $record->product_id])
                            :
                            PackageResource::getUrl('index', ['tableFilters[id][id]' => $record->product_id])
                    )
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('price')
                    ->label(__('Price'))
                    ->money("SAR")
                    ->sortable(),
                Tables\Columns\TextColumn::make('service_date')
                    ->label(__('Service Date'))
                    ->date('Y-m-d')
                    ->sortable(),
                Tables\Columns\TextColumn::make('serviceProvider.name')
                    ->label(__('Service Provider'))
                    ->url(fn($record) => ServiceProviderResource::getUrl('edit', ['record' => $record->service_provider_id]))
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.first_name')
                    ->label(__('User'))
                    ->url(
                        fn($record) =>
                        UserResource::getUrl('view', ['record' => $record->user_id])
                    )
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('commission')
                    ->label(__('Commission'))
                    ->money("SAR")
                    ->sortable(),
                Tables\Columns\TextColumn::make('net_price')
                    ->label(__('Net Price'))
                    ->money("SAR")
                    ->sortable(),
                Tables\Columns\IconColumn::make('is_transfered')
                    ->label(__('Is Transfered'))
                    ->boolean(),
                Tables\Columns\TextColumn::make('status')
                    ->label(__('Status'))
                    ->formatStateUsing(fn($record) => $record->status->label())
                    ->searchable(),
                Tables\Columns\TextColumn::make('booking.payment_status')
                    ->label(__('Booking Payment Status'))
                    ->formatStateUsing(fn($record) => $record->booking->payment_status->label())
                    ->searchable(),
                Tables\Columns\TextColumn::make('booking.status')
                    ->label(__('Booking Status'))
                    ->formatStateUsing(fn($record) => $record->booking->status->label())
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('Created At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label(__('Updated At'))
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('booking_id')
                    ->label(__('Booking ID'))
                    ->relationship('booking', 'id')
                    ->multiple()
                    ->searchable()
                    ->preload(),
                SelectFilter::make('product_id')
                    ->label(__('Product'))
                    ->relationship('product', 'name_' . app()->getLocale())
                    ->multiple()
                    ->searchable()
                    ->preload(),
                SelectFilter::make('service_provider_id')
                    ->label(__('Service Provider'))
                    ->multiple()
                    ->relationship('serviceProvider', 'name')
                    ->searchable()
                    ->preload(),
                SelectFilter::make('user_id')
                    ->label(__('User'))
                    ->relationship('user', 'first_name')
                    ->multiple()
                    ->searchable()
                    ->preload(),
                SelectFilter::make('status')
                    ->multiple()
                    ->label(__('Status'))
                    ->options(BookingItemStatus::options()),
                SelectFilter::make('is_transfered')
                    ->label(__('Is Transfered'))
                    ->options([
                        true => __('Yes'),
                        false => __('No'),
                    ]),
                SelectFilter::make('payment_status')
                    ->label(__('Payment Status'))
                    ->options(PaymentStatus::options())
                    ->query(
                        fn(Builder $query, array $data) => $query->when(
                            $data['value'],
                            fn($query, $data) =>
                            $query->whereHas(
                                'booking',
                                fn($q) =>
                                $q->where('payment_status', $data)
                            )
                        )
                    ),
                SelectFilter::make('booking.status')
                    ->label(__('Booking Status'))
                    ->options(BookingStatus::options())
                    ->query(
                        fn(Builder $query, array $data) => $query->when(
                            $data['value'],
                            fn($query, $data) =>
                            $query->whereHas(
                                'booking',
                                fn($q) =>
                                $q->where('status', $data)
                            )
                        )
                    ),
                Filter::make('service_date')
                    ->form([
                        Forms\Components\DatePicker::make('created_from')->label(__('Service Date From')),
                        Forms\Components\DatePicker::make('created_until')->label(__('Service Date To')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn(Builder $query, $date): Builder => $query->whereDate('service_date', '>=', $date),
                            )
                            ->when(
                                $data['created_until'],
                                fn(Builder $query, $date): Builder => $query->whereDate('service_date', '<=', $date),
                            );
                    })
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                //
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\ActivitiesRelationManager::class,
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListBookingItems::route('/'),
            'view' => Pages\ViewBookingItem::route('/{record}'),
            'edit' => Pages\EditBookingItem::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['booking', 'product']);
    }
}
