<?php

namespace App\Filament\Resources;

use App\Filament\Resources\BookingResource\Pages;
use App\Models\Booking;
use App\Models\Consultant;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\SelectColumn;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\FileUpload;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class BookingResource extends Resource
{
    protected static ?string $model = Booking::class;
    protected static ?string $navigationIcon = 'heroicon-o-calendar-days';

    /**
     * SECURITY & MULTI-TENANCY
     * Filters the list so consultants only see their own clients.
     */
    public static function getEloquentQuery(): Builder
    {
        $user = Auth::user();
        $query = parent::getEloquentQuery();

        // 1. Super Admin sees everything
        if ($user->hasRole('super_admin')) {
            return $query;
        }

        // 2. Consultant logic
        if ($user->consultant) {
            return $query->where('consultant_id', $user->consultant->id);
        }

        // 3. Fallback: If you want the Admin Prabhu (ID 1) to see everything
        // even without a consultant profile, add this:
        if ($user->id === 1) {
            return $query;
        }

        return $query->whereRaw('1 = 0');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')
                    ->relationship('user', 'name')
                    ->preload()
                    ->searchable()
                    ->required(),

                Forms\Components\Select::make('consultant_id')
                    ->label('Consultant')
                    ->options(function () {
                        return Consultant::with('user')->get()->mapWithKeys(function ($consultant) {
                            return [$consultant->id => $consultant->user->name . ' - ' . $consultant->specialization];
                        });
                    })
                    ->default(fn() => Auth::user()->consultant?->id)
                    // CHANGED: Check for 'consultant' role instead of 'panel_user'
                    ->disabled(fn() => !Auth::user()->hasRole('super_admin'))
                    ->dehydrated()
                    ->required(),

                Forms\Components\Select::make('service_id')
                    ->relationship('service', 'name')
                    ->required(),

                Forms\Components\DateTimePicker::make('scheduled_at')
                    ->required(),

                Forms\Components\Select::make('status')
                    ->options([
                        'pending' => 'Pending',
                        'confirmed' => 'Confirmed',
                        'completed' => 'Completed',
                        'cancelled' => 'Cancelled',
                    ])->default('pending'),

                Section::make('Payment Verification')
                    ->description('Review the payment proof before confirming.')
                    ->schema([
                        FileUpload::make('payment_proof')
                            ->image()
                            ->disk('public')
                            ->disabled()
                            ->dehydrated(false)
                            ->columnSpanFull(),
                    ])
                    ->collapsible(),

                Forms\Components\TextInput::make('meeting_link')
                    ->url()
                    ->placeholder('https://meet.google.com/...'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('user.name')
                    ->label('Client')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('service.name')
                    ->sortable(),

                TextColumn::make('scheduled_at')
                    ->dateTime()
                    ->sortable(),

                // Status Column - Selectable for quick updates
                SelectColumn::make('status')
                    ->options([
                        'pending' => 'Pending',
                        'confirmed' => 'Confirmed',
                        'completed' => 'Completed',
                        'cancelled' => 'Cancelled',
                    ]),

                ImageColumn::make('payment_proof')
                    ->label('Proof')
                    ->disk('public')
                    ->square(),
            ])
            ->filters([
                // Add filters here if needed
            ])
            ->actions([
                Tables\Actions\EditAction::make(),

                // ADDED: Quick "Confirm" Action Button
                Tables\Actions\Action::make('confirm')
                    ->label('Confirm')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(fn(Booking $record) => $record->update(['status' => 'confirmed']))
                    ->visible(fn(Booking $record) => $record->status === 'pending'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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