<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ContractorResource\Pages;
use App\Models\Contractor;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Exports\ExcelExport;

class ContractorResource extends Resource
{
    protected static ?string $model = Contractor::class;

    protected static ?string $navigationIcon = 'heroicon-o-wrench-screwdriver';
    protected static ?string $navigationGroup = 'پیمانکاران';
    protected static ?string $navigationLabel = 'پیمانکاران';
    protected static ?string $modelLabel = 'پیمانکار';
    protected static ?string $pluralModelLabel = 'پیمانکاران';
    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\Section::make('اطلاعات پیمانکار')
                ->columns(2)
                ->schema([
                    Forms\Components\ToggleButtons::make('type')->label('نوع پیمانکار')
                        ->options(['individual' => 'حقیقی', 'legal' => 'حقوقی'])
                        ->default('individual')->inline()->required()
                        ->live()
                        ->columnSpanFull(),

                    Forms\Components\TextInput::make('first_name')->label('نام')
                        ->required()->maxLength(255),
                    Forms\Components\TextInput::make('last_name')->label('نام خانوادگی')
                        ->required()->maxLength(255),

                    Forms\Components\TextInput::make('company_name')->label('نام شرکت / مجموعه')
                        ->maxLength(255)
                        ->required(fn (Forms\Get $get) => $get('type') === 'legal')
                        ->visible(fn (Forms\Get $get) => $get('type') === 'legal'),

                    Forms\Components\TextInput::make('mobile')->label('شماره موبایل')
                        ->tel()->required()->maxLength(20)
                        ->helperText('اجباری'),
                    Forms\Components\TextInput::make('phone')->label('تلفن ثابت')
                        ->tel()->maxLength(20),

                    Forms\Components\TextInput::make('specialty')->label('تخصص / زمینه‌ی کاری')
                        ->placeholder('برق‌کاری، نقاشی، گچ‌کاری …')->maxLength(255),
                    Forms\Components\TextInput::make('email')->label('ایمیل')->email()->maxLength(255),
                ]),

            Forms\Components\Section::make('اطلاعات هویتی و حقوقی')
                ->columns(2)->collapsible()
                ->schema([
                    Forms\Components\TextInput::make('national_code')->label('کد ملی')
                        ->visible(fn (Forms\Get $get) => $get('type') === 'individual')->maxLength(20),
                    Forms\Components\TextInput::make('national_id')->label('شناسه ملی')
                        ->visible(fn (Forms\Get $get) => $get('type') === 'legal')->maxLength(20),
                    Forms\Components\TextInput::make('registration_number')->label('شماره ثبت')
                        ->visible(fn (Forms\Get $get) => $get('type') === 'legal')->maxLength(50),
                    Forms\Components\TextInput::make('economic_code')->label('کد اقتصادی')->maxLength(50),
                ]),

            Forms\Components\Section::make('آدرس و توضیحات')
                ->columns(2)->collapsible()
                ->schema([
                    Forms\Components\TextInput::make('province')->label('استان')->maxLength(100),
                    Forms\Components\TextInput::make('city')->label('شهر')->maxLength(100),
                    Forms\Components\TextInput::make('postal_code')->label('کد پستی')->maxLength(20),
                    Forms\Components\Textarea::make('address')->label('آدرس')->columnSpanFull(),
                    Forms\Components\Textarea::make('description')->label('توضیحات')->columnSpanFull(),
                    Forms\Components\Toggle::make('is_active')->label('فعال')->default(true),
                ]),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('display_name')->label('نام پیمانکار')
                    ->searchable(['first_name', 'last_name', 'company_name'])->sortable(),
                Tables\Columns\TextColumn::make('type')->label('نوع')->badge()
                    ->formatStateUsing(fn ($state) => ['individual' => 'حقیقی', 'legal' => 'حقوقی'][$state] ?? $state),
                Tables\Columns\TextColumn::make('mobile')->label('موبایل')->searchable()
                    ->formatStateUsing(fn ($state) => \App\Support\NumberToWords::digits($state)),
                Tables\Columns\TextColumn::make('specialty')->label('تخصص')->toggleable(),
                Tables\Columns\TextColumn::make('tasks_count')->label('تعداد کار')->counts('tasks')->badge()
                    ->formatStateUsing(fn ($state) => \App\Support\NumberToWords::digits($state)),
                Tables\Columns\IconColumn::make('is_active')->label('فعال')->boolean(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')->label('نوع')
                    ->options(['individual' => 'حقیقی', 'legal' => 'حقوقی']),
            ])
            ->actions([Tables\Actions\EditAction::make()])
            ->headerActions([
                ExportAction::make()->label('خروجی اکسل')->exports([ExcelExport::make()->fromTable()]),
            ]);
    }

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