<?php

namespace App\Filament\Resources;

use App\Filament\Resources\InspectionResource\Pages;
use App\Models\Inspection;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class InspectionResource extends Resource
{
    protected static ?string $model = Inspection::class;
    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-check';
    protected static ?string $navigationLabel = 'بازدیدها';
    protected static ?string $modelLabel = 'بازدید';
    protected static ?string $pluralModelLabel = 'بازدیدها';
    protected static ?string $navigationGroup = 'مدیریت';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('user_id')
                    ->relationship('user', 'name')
                    ->required()
                    ->searchable(),
                Forms\Components\Select::make('ad_id')
                    ->relationship('ad', 'title')
                    ->nullable()
                    ->searchable(),
                Forms\Components\Select::make('inspection_type')
                    ->options([
                        'buy' => 'خرید',
                        'sell' => 'فروش',
                    ])
                    ->required(),
                Forms\Components\Select::make('status')
                    ->options([
                        'in_progress' => 'در حال انجام',
                        'completed' => 'تکمیل شده',
                        'cancelled' => 'لغو شده',
                    ])
                    ->required(),
                Forms\Components\TextInput::make('risk_score')
                    ->numeric()
                    ->minValue(0)
                    ->maxValue(100)
                    ->label('امتیاز ریسک'),
                Forms\Components\Select::make('risk_level')
                    ->options([
                        'low' => 'پایین',
                        'medium' => 'متوسط',
                        'high' => 'بالا',
                    ])
                    ->label('سطح ریسک'),
                Forms\Components\Textarea::make('recommendations')
                    ->rows(3)
                    ->label('توصیه‌ها'),
                Forms\Components\Textarea::make('answers')
                    ->rows(3)
                    ->label('پاسخ‌ها'),
                Forms\Components\TextInput::make('current_question')
                    ->numeric()
                    ->label('سوال فعلی'),
                Forms\Components\DateTimePicker::make('completed_at')
                    ->label('تاریخ تکمیل'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('user.name')
                    ->label('کاربر')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('ad.title')
                    ->label('آگهی')
                    ->searchable()
                    ->limit(30),
                Tables\Columns\TextColumn::make('inspection_type')
                    ->label('نوع')
                    ->formatStateUsing(fn (string $state): string => match($state) {
                        'buy' => 'خرید',
                        'sell' => 'فروش',
                    })
                    ->badge()
                    ->color(fn (string $state): string => match($state) {
                        'buy' => 'success',
                        'sell' => 'info',
                    }),
                Tables\Columns\TextColumn::make('status')
                    ->label('وضعیت')
                    ->formatStateUsing(fn (string $state): string => match($state) {
                        'in_progress' => 'در حال انجام',
                        'completed' => 'تکمیل شده',
                        'cancelled' => 'لغو شده',
                    })
                    ->badge()
                    ->color(fn (string $state): string => match($state) {
                        'in_progress' => 'warning',
                        'completed' => 'success',
                        'cancelled' => 'danger',
                    }),
                Tables\Columns\TextColumn::make('risk_score')
                    ->label('امتیاز ریسک')
                    ->sortable()
                    ->formatStateUsing(fn (?int $state): string => $state ? "{$state}/100" : '-'),
                Tables\Columns\TextColumn::make('risk_level')
                    ->label('سطح ریسک')
                    ->formatStateUsing(fn (?string $state): string => match($state) {
                        'low' => '🟢 پایین',
                        'medium' => '🟡 متوسط',
                        'high' => '🔴 بالا',
                        default => '-'
                    })
                    ->badge()
                    ->color(fn (?string $state): string => match($state) {
                        'low' => 'success',
                        'medium' => 'warning',
                        'high' => 'danger',
                        default => 'gray'
                    }),
                Tables\Columns\TextColumn::make('current_question')
                    ->label('پیشرفت')
                    ->formatStateUsing(function (Inspection $record): string {
                        $total = $record->inspection_type === 'buy' ? 7 : 7;
                        return "{$record->current_question}/{$total}";
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاریخ ایجاد')
                    ->dateTime('j F Y H:i')
                    ->sortable(),
                Tables\Columns\TextColumn::make('completed_at')
                    ->label('تاریخ تکمیل')
                    ->dateTime('j F Y H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('inspection_type')
                    ->options([
                        'buy' => 'خرید',
                        'sell' => 'فروش',
                    ])
                    ->label('نوع بازدید'),
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'in_progress' => 'در حال انجام',
                        'completed' => 'تکمیل شده',
                        'cancelled' => 'لغو شده',
                    ])
                    ->label('وضعیت'),
                Tables\Filters\SelectFilter::make('risk_level')
                    ->options([
                        'low' => 'پایین',
                        'medium' => 'متوسط',
                        'high' => 'بالا',
                    ])
                    ->label('سطح ریسک'),
                Tables\Filters\Filter::make('completed')
                    ->query(fn ($query) => $query->where('status', 'completed'))
                    ->label('تکمیل شده'),
                Tables\Filters\Filter::make('high_risk')
                    ->query(fn ($query) => $query->where('risk_level', 'high'))
                    ->label('ریسک بالا'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListInspections::route('/'),
            'create' => Pages\CreateInspection::route('/create'),
            'view' => Pages\ViewInspection::route('/{record}'),
            'edit' => Pages\EditInspection::route('/{record}/edit'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('status', 'in_progress')->count();
    }

    public static function getNavigationBadgeColor(): ?string
    {
        return 'warning';
    }
}
