<?php

namespace App\Filament\Admin\Resources\Properties;

use App\Filament\Admin\Resources\Properties\Pages\CreateProperty;
use App\Filament\Admin\Resources\Properties\Pages\EditProperty;
use App\Filament\Admin\Resources\Properties\Pages\ListProperties;
use App\Filament\Admin\Resources\Properties\Pages\ViewProperty;
use App\Filament\Admin\Resources\Properties\Schemas\PropertyForm;
use App\Filament\Admin\Resources\Properties\Schemas\PropertyInfolist;
use App\Filament\Admin\Resources\Properties\Tables\PropertiesTable;
use App\Models\Property;
use BackedEnum;
use UnitEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Illuminate\Database\Eloquent\Builder;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Forms\Components\RichEditor;

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

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice2;

    protected static string|UnitEnum|null $navigationGroup  = 'Inmuebles';
    protected static ?int    $navigationSort  = 7;

    public static function getPluralLabel(): string
    {
        return 'Inmuebles';
    }

    public static function getLabel(): string
    {
        return 'Inmueble';
    }

    protected static ?string $recordTitleAttribute = 'code';

    public static function form(Schema $schema): Schema
    {
        //return PropertyForm::configure($schema);
        return $schema
            ->schema([
            Section::make('Información Básica')
                    ->description('Datos principales del inmueble')
                    ->columnSpanFull()
                    ->columns(2)
                    ->icon('heroicon-m-home')
                    ->schema([
                        TextInput::make('code')
                            ->label('Código')
                            ->required()
                            ->maxLength(255),                
                        Select::make('state')
                            ->label('Estado')
                            ->options([
                                'Activo'   => 'Activo',
                                'Inactivo' => 'Inactivo',
                            ])
                            ->default(fn ($record) => $record->state ?? 'Activo')
                            ->required(),
                        Select::make('property_status_id')
                            ->label('Estado del Inmueble')
                            ->relationship('propertyStatus', 'name')
                            ->required(),
                        Select::make('offer_id')
                            ->label('Oferta')
                            ->relationship('offer', 'name')
                            ->required(),   
                        Select::make('type_property_id')
                            ->label('Tipo de Inmueble')
                            ->options(fn () => \App\Models\TypeProperty::pluck('name', 'id'))
                            ->searchable()
                            ->required(),  
                        Select::make('agent_id')
                            ->label('Agente')
                            ->relationship('agent', 'name')
                            ->required(),  
                        Select::make('owner_id')
                            ->label('Propietario')
                            ->relationship('owner', 'name')
                            ->required(),  
                        TextInput::make('video_url')
                            ->label('URL del Video')
                            ->url()
                            ->placeholder('https://www.youtube.com/watch?v=example')
                            ->helperText('Ingresa la URL del video del inmueble (YouTube, Vimeo, etc.)')
                            ->maxLength(255),      
                    ]),
            Section::make('Detalles del Inmueble')
                    ->description('Características y descripción del inmueble')
                    ->icon('heroicon-m-information-circle')
                    ->columnSpanFull()
                    ->columns(2)
                    ->schema([
                        TextInput::make('price')
                            ->label('Precio')
                            ->numeric()
                            ->prefix('$')
                            ->suffix('COP')
                            ->required(),
                        TextInput::make('administration')
                            ->label('Administración')
                            ->numeric()
                            ->prefix('$')
                            ->suffix('COP'),
                        TextInput::make('rooms')
                            ->label('Habitaciones')
                            ->numeric(),
                        TextInput::make('bathrooms')
                            ->label('Baños')
                            ->numeric(),
                        TextInput::make('parking')
                            ->label('Parqueaderos')
                            ->numeric(),
                        TextInput::make('area')
                            ->label('Área (m²)')
                            ->numeric()
                            ->required(),
                        Select::make('city_id')
                            ->label('Ciudad')
                            ->relationship('city', 'name')
                            ->options(fn () => \App\Models\City::pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function ($state, Set $set) {
                                // Limpiar barrio cuando cambia la ciudad
                                $set('neighborhood_id', null);
                            })
                            ->required(),
                        Select::make('neighborhood_id')
                            ->label('Barrio')
                            ->relationship(
                                name: 'neighborhood',
                                titleAttribute: 'name',
                                modifyQueryUsing: function (Builder $query, Get $get) {
                                    // Filtrar barrios por la ciudad seleccionada
                                    $cityId = $get('city_id');
                                    
                                    if ($cityId) {
                                        $query->where('city_id', $cityId);
                                    } else {
                                        // Si no hay ciudad, no mostrar barrios
                                        $query->whereNull('id');
                                    }
                                },
                            )
                            ->options(function (Get $get): array {
                                $cityId = $get('city_id');
                                
                                if (!$cityId) {
                                    return [];
                                }
                                
                                return \App\Models\Neighborhood::where('city_id', $cityId)
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->searchable()
                            ->preload()
                            ->disabled(function (Get $get) {
                                    $cityId = $get('city_id');
                                    
                                    if (!$cityId) {
                                        return true;
                                    }
                                    
                                    $neighborhoodsCount = \App\Models\Neighborhood::where('city_id', $cityId)
                                        ->count();
                                    
                                    return $neighborhoodsCount === 0;
                                })
                            ->placeholder(function (Get $get) {
                                $cityId = $get('city_id');
                                
                                if (!$cityId) {
                                    return 'Primero selecciona una ciudad';
                                }
                                
                                $hasNeighborhoods = \App\Models\Neighborhood::where('city_id', $cityId)
                                    ->exists();
                                
                                return $hasNeighborhoods 
                                    ? 'Selecciona un barrio' 
                                    : 'No hay barrios disponibles para esta ciudad';
                            })
                            ->helperText(function (Get $get) {
                                $cityId = $get('city_id');
                                
                                if (!$cityId) {
                                    return 'Primero selecciona una ciudad';
                                }
                                
                                $hasNeighborhoods = \App\Models\Neighborhood::where('city_id', $cityId)
                                    ->exists();
                                
                                if (!$hasNeighborhoods) {
                                    return '⚠️ No hay barrios registrados para esta ciudad. Por favor, agrega barrios primero.';
                                }
                                
                                return 'Selecciona un barrio de la ciudad elegida';
                            })
                            ->required(function (Get $get) {
                                $cityId = $get('city_id');
                                
                                if (!$cityId) {
                                    return false;
                                }
                                
                                // Solo requerido si hay barrios disponibles
                                return \App\Models\Neighborhood::where('city_id', $cityId)
                                    ->exists();
                            }),
                        RichEditor::make('description')
                            ->label('Descripción')
                            ->placeholder('Escribe una descripción detallada del inmueble...')
                            ->toolbarButtons([
                                'attachFiles',
                                'blockquote',
                                'bold',
                                'bulletList',
                                'codeBlock',
                                'h2',
                                'h3',
                                'italic',
                                'link',
                                'orderedList',
                                'redo',
                                'strike',
                                'underline',
                                'undo',
                            ])
                            ->fileAttachmentsDisk('public')
                            ->fileAttachmentsDirectory('property-descriptions')
                            ->fileAttachmentsVisibility('public')
                            ->extraAttributes([
                                    'style' => 'height: 500px; min-height: 500px;',
                                ])
                            ->columnSpanFull(),
                            ]),
            Section::make('Ubicación')
                    ->description('Datos de la ubicación del inmueble')
                    ->icon('heroicon-m-map')
                    ->columnSpanFull()
                    ->columns(2)
                    ->schema([                        
                        TextInput::make('address')
                            ->label('Dirección')
                            ->required()
                            ->maxLength(255),
                        TextInput::make('address_extra')
                            ->label('Dirección Extra')
                            ->maxLength(255),
                        Map::make('location')
                            ->mapControls([
                                'mapTypeControl'    => true,
                                'scaleControl'      => true,
                                'streetViewControl' => true,
                                'rotateControl'     => true,
                                'fullscreenControl' => true,
                                'searchBoxControl'  => true,
                                'zoomControl'       => true,
                            ])
                            ->height('500px')
                            ->defaultZoom(15)
                            ->autocomplete('address')
                            ->autocompleteReverse(true)
                            ->defaultLocation(fn ($record) => [
                                        $record?->latitude ?? 7.115143,
                                        $record?->longitude ?? -73.125769,
                                        ]) 
                            ->draggable()
                            ->clickable(true)
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                $set('latitude', $state['lat'] ?? null);
                                $set('longitude', $state['lng'] ?? null);
                            })
                            ->columnSpanFull(),

                        TextInput::make('latitude')
                            ->label('Latitud')
                            ->numeric()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                $set('location', [
                                    'lat' => floatval($state),
                                    'lng' => floatval($get('longitude') ?? 0),
                                ]);
                            }),

                        TextInput::make('longitude')
                            ->label('Longitud')
                            ->numeric()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                $set('location', [
                                    'lat' => floatval($get('latitude') ?? 0),
                                    'lng' => floatval($state),
                                ]);
                            }),
                    ])

            ]);   
    }

    public static function infolist(Schema $schema): Schema
    {
        return PropertyInfolist::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return PropertiesTable::configure($table);
       
    }

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

    public static function getPages(): array
    {
        return [
            'index' => ListProperties::route('/'),
            'create' => CreateProperty::route('/create'),
            'view' => ViewProperty::route('/{record}'),
            'edit' => EditProperty::route('/{record}/edit'),
        ];
    }
}
