<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PropertyResource\Pages;
use App\Filament\Resources\PropertyResource\RelationManagers;
use App\Models\Property;
use App\Models\PropertyAmenity;
use App\Models\PropertyCategory;
use App\Models\PropertyType;
use Filament\Forms;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Section;
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\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Str;

class PropertyResource extends Resource
{
    protected static ?string $model = Property::class;

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

     protected static ?string $navigationGroup = 'Property Management';

    protected static ?int $navigationSort = 5;


    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make("Property Details")
                    ->schema([
                        Select::make('property_type_id')
                            ->label('Property Type')
                            ->options(PropertyType::where('status',1)->pluck('name','id')->toArray())
                           // ->relationship('propertyType','name')
                            ->reactive()
                            ->preload()
                            ->native(false)
                            ->required(),
                        Select::make('property_category_id')
                            ->label('Property Category')
                            ->options(function (callable $get){
                                $propertyType = PropertyType::find($get('property_type_id'));
                                if(!$propertyType){
                                    return PropertyCategory::where('status',1)->pluck('name','id');
                                }
                                return $propertyType->propertyCategories->pluck('name','id');
                            })
                            ->reactive()
                            ->preload()
                            ->native(false)->required(),
                       Select::make('property_amenity_id')
                            ->label('Property Amenities')
                            ->relationship('propertyAmenities','name')
                           ->options(function (callable $get){
                                $propertyCategory = PropertyCategory::find($get('property_category_id'));
                                if(!$propertyCategory){
                                    return PropertyAmenity::where('status',1)->pluck('name','id');
                                }
                                return $propertyCategory->propertyAmenities->pluck('name','id');
                            })

                           // ->relationship('propertyAmenities','name')
                            ->multiple()
                            ->searchable()
                            ->preload()
                           ->required()
                            ->native(false),
                        Select::make('property_location_id')
                            ->label('Property Location')
                            ->relationship('propertyLocation','name')
                            ->searchable()
                            ->preload()
                            ->native(false)->required()



                    ])->columns(2),
                Section::make()
                    ->schema([
                        TextInput::make('name')
                            ->live(debounce: 5000)
                            ->required()->minLength(1)->maxLength(200)
                            ->afterStateUpdated(function (string $operation, $state, Forms\Set $set) {
                                if ($operation === 'edit') {
                                    return;
                                }

                                $set('slug', Str::slug($state));
                            })->columnSpanFull(),
                        ]),
                            Section::make()  ->schema([
                            TextInput::make('slug')->label('Slug URL: Automatically updates')->required()->readOnly()->minLength(1)->unique(ignoreRecord: true)->maxLength(200),
                        Select::make('status')
                            ->options([
                                '1' => 'Published',
                                '0' => 'Draft'
                            ])->native(false)->required(),
                            Select::make('featured')->label('Show as Deal on homepage')
                            ->options([
                                '1' => 'Featured',
                                '0' => 'Normal Listing'
                            ])->native(false)->required(),

                        RichEditor::make('description')
                            ->required()
                            ->label("Short Description")
                        ->columnSpanFull(),
                    ])->columns(3),
                Section::make('Property Price Sizes')
                    ->schema([
                        TextInput::make('price')->numeric()->label('Price In Ksh.')->required(),
                        TextInput::make('offer_price')->numeric()->label('Offer Price In Ksh.'),
                        DatePicker::make('offer_end_dates')->label('Offer End Dates'),
                        Select::make('bathroom')
                            ->options([
                                '0' => '0',
                                '1' => '1',
                                '2' => '2',
                                '3' => '3',
                                '4' => '4',
                                '5' => '5+',
                            ])->native(false)->required(),
                        Select::make('bedrooms')
                            ->options([
                                '0' => '0',
                                '1' => '1',
                                '2' => '2',
                                '3' => '3',
                                '4' => '4',
                                '5' => '5+',
                            ])->native(false)->required(),
                        Select::make('garage')
                            ->options([
                                '0' => '0',
                                '1' => '1',
                                '2' => '2',
                                '3' => '3',
                                '4' => '4',
                                '5' => '5+',
                            ])->native(false)->required(),

                        ])->columns(3),



                Section::make('Cover Image and Gallery')
                    ->schema([
                        FileUpload::make('image')->label("Image Cover")
                           ->required()
                            ->directory('properties'),
                        FileUpload::make('gallery')->label("Image Gallery")
                             ->multiple()
                            ->directory('properties'),
                            //->image(),
                        ])->columns(2),
                Section::make()
                    ->schema([
                        Textarea::make('meta_description')->nullable()->label('SEO Meta Description'),
                        Textarea::make('keywords')->nullable()->label('SEO Keywords'),


                    ])

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')->label(" Name"),
                ImageColumn::make('image')->label(" Image"),
                TextColumn::make('propertyType.name')->label(" Property Type"),
                TextColumn::make('propertyCategory.name')->label(" Property Category"),
                TextColumn::make('propertyLocation.name')->label(" Property Location"),
                TextColumn::make('price')
                    ->label(" Property Price")
                    ->numeric(
                        decimalPlaces: 0,
                    decimalSeparator: '.',
                    thousandsSeparator: ','
                    ),
                ToggleColumn::make('status')->label("Status"),
            ])
            ->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\ListProperties::route('/'),
            'create' => Pages\CreateProperty::route('/create'),
            'edit' => Pages\EditProperty::route('/{record}/edit'),
        ];
    }
}
