<?php

namespace App\Filament\Resources;

use App\Filament\Resources\EmployeeResource\Pages;
use App\Filament\Resources\EmployeeResource\RelationManagers;

use App\Models\Employee;
use App\Models\Country;
use App\Models\Department;
use App\Models\Carrier;

use App\Enums\BloodGroup;
use App\Enums\EducationLevel;
use App\Enums\MilitaryServiceStatus;
use App\Enums\EmployeeCertificateType;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Support\Enums\FontWeight;
use Filament\Forms\Components\Actions\Action;
use Filament\Resources\Pages\Page;
use Filament\Pages\SubNavigationPosition;
use Filament\Support\Enums\MaxWidth;

use Filament\Infolists;
use Filament\Infolists\Infolist;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Carbon;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;

class EmployeeResource extends Resource
{
    protected static ?string $model = Employee::class;

    protected static ?string $recordTitleAttribute = 'firstname';

    protected static ?string $modelLabel = 'Personel';
    protected static ?string $pluralModelLabel = 'Personeller';

    // protected static ?string $navigationIcon = 'heroicon-o-user-group';
    protected static ?string $navigationLabel = 'Personeller';
    protected static ?string $navigationGroup = 'Uygulama';

    protected static ?int $navigationSort = 3;

    protected static int $globalSearchResultsLimit = 5;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    public static function getRecordTitleAttribute(): ?string
    {
        return 'fullname';
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Kişisel Bilgiler')
                    ->columns([
                        'lg' => 2,
                        'xl' => 4,
                    ])
                    ->icon('heroicon-m-user-circle')
                    ->schema([
                        Forms\Components\TextInput::make('firstname')
                            ->label('Ad')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\TextInput::make('lastname')
                            ->label('Soyad')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\Select::make('country_id')
                            ->label('Uyruk')
                            ->options(Country::all()->pluck('name', 'id'))
                            ->searchable(),

                        Forms\Components\TextInput::make('identity_number')
                            ->label('Kimlik Numarası')
                            ->maxLength(11)
                            ->default(null),

                        Forms\Components\Select::make('gender')
                            ->label('Cinsiyet')
                            ->options([
                                'Erkek' => 'Erkek',
                                'Kadın' => 'Kadın',
                            ])
                            ->native(false),

                        Forms\Components\Select::make('marital_status')
                            ->label('Medeni Hal')
                            ->options([
                                'Bekar' => 'Bekar',
                                'Evli'  => 'Evli',
                                'Dul'   => 'Dul',
                            ])
                            ->native(false),

                        Forms\Components\Select::make('blood_group_id')
                            ->label('Kan Grubu')
                            ->options(BloodGroup::class)
                            ->searchable(),

                        Forms\Components\TextInput::make('ssn')
                            ->label('Sosyal Güvenlik Numarası')
                            ->maxLength(26)
                            ->default(null),

                        Forms\Components\DatePicker::make('birth_date')
                            ->label('Doğum Tarihi'),

                        Forms\Components\TextInput::make('birth_place')
                            ->label('Doğum Yeri')
                            ->maxLength(255)
                            ->default(null),

                        Forms\Components\TextInput::make('registered_city')
                            ->label('Nüfusa Kayıtlı Olduğu İl')
                            ->maxLength(255)
                            ->default(null),

                        Forms\Components\TextInput::make('registered_district')
                            ->label('Nüfusa Kayıtlı Olduğu İlçe')
                            ->maxLength(255)
                            ->default(null),

                        Forms\Components\Select::make('education_level_id')
                            ->label('Eğitim Durumu')
                            ->options(EducationLevel::class)
                            ->searchable(),

                        Forms\Components\Select::make('military_status_id')
                            ->label('Askerlik Durumu')
                            ->options(MilitaryServiceStatus::class)
                            ->searchable(),

                        Forms\Components\Select::make('department_id')
                            ->label('Departman')
                            ->options(Department::all()->pluck('name', 'id'))
                            ->searchable()
                            ->required(),

                        Forms\Components\Select::make('carrier_id')
                            ->label('Tedarikçi')
                            ->relationship(name: 'carrier', titleAttribute: 'name')
                            ->createOptionForm([
                                Forms\Components\TextInput::make('name')
                                    ->label('Tedarikçi Adı')
                                    ->maxLength(255)
                                    ->required(),

                                Forms\Components\TextInput::make('tax_number')
                                    ->label('Vergi Numarası')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('tax_office')
                                    ->label('Vergi Dairesi')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('address')
                                    ->label('Adres')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('telefon')
                                    ->label('Telefon')
                                    ->maxLength(255),

                                Forms\Components\TextInput::make('email')
                                    ->label('E-posta Adresi')
                                    ->maxLength(150),

                                Forms\Components\TextInput::make('website')
                                    ->label('Website')
                                    ->prefix('https://')
                                    ->maxLength(255),
                            ])
                            ->createOptionAction(function (Action $action) {
                                return $action
                                    ->modalHeading('Tedarikçi Oluştur')
                                    ->modalWidth(MaxWidth::Large)
                                    ->slideOver();
                            })
                            ->searchable()
                            ->required(),
                    ]),

                Forms\Components\Section::make('Belgeler & Serifikalar')
                    ->visible(fn ($operation) => $operation === 'create')
                    ->columns([
                        'lg' => 1,
                    ])
                    ->icon('heroicon-s-document-text')
                    ->schema([
                        Forms\Components\Repeater::make('certificates')
                            ->label('')
                            ->relationship('certificates')
                            ->schema([
                                Forms\Components\Select::make('certificate_type_id')
                                    ->label('Belge Türü')
                                    ->options(EmployeeCertificateType::class)
                                    ->required()
                                    ->searchable()
                                    ->native(false)
                                    ->live()
                                    ->afterStateUpdated(function (Forms\Components\Select $component) {
                                        $component
                                            ->getContainer()
                                            ->getComponent('dynamicCertificateFields')
                                            ->getChildComponentContainer()
                                            ->fill();
                                    }),

                                Forms\Components\DatePicker::make('started_at')
                                    ->label('Başlangıç Tarihi')
                                    ->required(),

                                Forms\Components\DatePicker::make('ended_at')
                                    ->label('Bitiş Tarihi')
                                    ->required(),

                                Forms\Components\Grid::make(3)
                                    ->schema(fn (Get $get): array => self::getCertificateFields($get('certificate_type_id')))
                                    ->key('dynamicCertificateFields'),
                            ])
                            ->itemLabel(function (array $state): ?string {
                                return !empty($state['certificate_type_id'])
                                    ? EmployeeCertificateType::from($state['certificate_type_id'])->getLabel()
                                    : null;
                            })
                            ->addActionLabel('Yeni Belge & Sertifika Ekle')
                            ->collapsible()
                            ->deleteAction(fn (Forms\Components\Actions\Action $action) => $action->requiresConfirmation())
                            ->defaultItems(0)
                            ->columns(3),
                    ]),

                Forms\Components\Section::make('Pasaport Bilgileri')
                    ->columns([
                        'lg' => 2,
                        'xl' => 4,
                    ])
                    ->icon('heroicon-m-identification')
                    ->schema([
                        Forms\Components\TextInput::make('passport_number')
                            ->label('Pasaport Numarası')
                            ->maxLength(255)
                            ->default(null),

                        Forms\Components\Select::make('passport_issue_country')
                            ->label('Verildiği Ülke')
                            ->options(Country::all()->pluck('name', 'id'))
                            ->searchable(),

                        Forms\Components\DatePicker::make('passport_issue_date')
                            ->label('Verildiği Tarih')
                            ->default(null),

                        Forms\Components\DatePicker::make('passport_expiry_date')
                            ->label('Son Kullanma Tarihi')
                            ->default(null),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('id', 'desc')
            ->modifyQueryUsing(fn (Builder $query) => $query->with([
                'certificates',
                'phones',
                'addresses',
                'emergencyContacts',
                'bankAccounts',
                'department',
                'carrier',
            ]))
            ->columns([
                Tables\Columns\TextColumn::make('firstname')
                    ->label('Personel')
                    ->formatStateUsing(fn ($record): View => view(
                        'vendor.filament.components.user-info-column',
                        ['record' => $record],
                    ))
                    ->searchable(['firstname', 'lastname', 'identity_number'])
                    ->grow(true),

                Tables\Columns\TextColumn::make('phones.phone_number')
                    ->label('Telefon')
                    ->icon('heroicon-s-phone')
                    ->searchable()
                    ->formatStateUsing(function ($record): string {
                        if (!optional($record->phones->where('is_primary', true)->first())->name) {
                            return '';
                        }

                        return '<div style="margin-left: 0.25rem;">
                                    <div class="text-xs text-gray-500">'.optional($record->phones->where('is_primary', true)->first())->name.':</div>
                                    <div>'.optional($record->phones->where('is_primary', true)->first())->phone_number.'</div>
                                </div>';
                    })
                    ->html(),

                Tables\Columns\IconColumn::make('passport_expiry_date')
                    ->label('Pasaport')
                    ->getStateUsing(function ($record) {
                        return (bool) ! Carbon::parse($record->passport_expiry_date)->isPast();
                    })
                    ->icon(function ($record): string {
                        $expiryDate = Carbon::parse($record->passport_expiry_date);
                        return $expiryDate->isPast()
                            ? ($record->passport_expiry_date ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $expiryDate = Carbon::parse($record->passport_expiry_date);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($record->passport_expiry_date ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Pasaport bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $expiryDate = Carbon::parse($record->passport_expiry_date);
                        return $expiryDate->isPast()
                            ? ($record->passport_expiry_date ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter(),

                Tables\Columns\IconColumn::make('adr_driver_training')
                    ->label('SRC-5 Belgesi')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'SRC-5 bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 1)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter(),

                Tables\Columns\IconColumn::make('travel_health_insurance')
                    ->label('Sağlık Sigortası')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Seyahat sağlık sigortası bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 2)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter(),

                Tables\Columns\IconColumn::make('tachograph_driver_card')
                    ->label('Sürücü Kartı')
                    ->getStateUsing(function ($record) {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        return (bool) ! Carbon::parse($state)->isPast();
                    })
                    ->icon(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-x-circle')
                            : 'heroicon-o-check-circle';
                    })
                    ->tooltip(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        $today = Carbon::today();

                        return $expiryDate->isPast()
                            ? ($state ? $expiryDate->isoFormat('LL').' tarihinde süresi doldu.' : 'Sürücü kartı bilgisi bulunamadı.')
                            : $expiryDate->isoFormat('LL').' tarihine kadar geçerlidir. Geçerlilik süresinin dolmasına '.$today->diff($expiryDate).' kaldı.';
                    })
                    ->color(function ($record): string {
                        $state = $record->certificates->where('certificate_type_id', 3)->sortByDesc('ended_at')->first()?->ended_at;
                        $expiryDate = Carbon::parse($state);
                        return $expiryDate->isPast()
                            ? ($state ? 'warning' : 'danger')
                            : 'success';
                    })
                    ->alignCenter(),

                Tables\Columns\TextColumn::make('department.name')
                    ->label('Departman')
                    ->badge()
                    ->color(fn ($record) => \Filament\Support\Colors\Color::hex($record->department->color)),

                Tables\Columns\TextColumn::make('completion_percentage')
                    ->label('Doluluk')
                    ->getStateUsing(fn ($record): View => view(
                        'vendor.filament.components.progress-bar',
                        ['percentage' => $record->getCompletionPercentage()],
                    )),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('Oluşturma')
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Güncelleme')
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('department')
                    ->label('Deparmant')
                    ->relationship('department', 'name')
                    ->searchable()
                    ->preload(),

                Tables\Filters\SelectFilter::make('passport_expiry_date')
                    ->label('Pasaport')
                    ->options([
                        'expired'   => 'Süresi Dolanlar',
                        'valid'     => 'Pasaportu Geçerli Olanlar',
                        'has_not'   => 'Pasaportu Olmayanlar',
                    ])
                    ->query(function (Builder $query, array $data) {
                        match ($data['value']) {
                            'expired'   => $query->where('passport_expiry_date', '<', now()),
                            'valid'     => $query->where('passport_expiry_date', '>', now()),
                            'has_not'   => $query->whereNull('passport_expiry_date'),
                            default     => null,
                        };
                    })
                    ->native(false),

                // Tables\Filters\SelectFilter::make('src5_expiry_date')
                //     ->label('SRC-5 Belgesi')
                //     ->options([
                //         'expired'   => 'Süresi Dolanlar',
                //         'valid'     => 'SRC-5 Belgesi Geçerli Olanlar',
                //         'has_not'   => 'SRC-5 Belgesi Olmayanlar',
                //     ])
                //     ->query(function (Builder $query, array $data) {
                //         match ($data['value']) {
                //             'expired'   => $query->where('src5_expiry_date', '<', now()),
                //             'valid'     => $query->where('src5_expiry_date', '>', now()),
                //             'has_not'   => $query->whereNull('src5_expiry_date'),
                //             default     => null,
                //         };
                //     })
                //     ->native(false),

            ], layout: FiltersLayout::Modal)
            ->filtersTriggerAction(
                fn (\Filament\Tables\Actions\Action $action) => $action->slideOver()
            )
            // ->recordUrl(null)
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    // public static function infolist(Infolist $infolist): Infolist
    // {
    //     return $infolist
    //         ->schema([
    //             Infolists\Components\Tabs::make('Tabs')
    //                 ->tabs([
    //                     Infolists\Components\Tabs\Tab::make('Personel Bilgileri')
    //                         ->schema([
    //                             Infolists\Components\TextEntry::make('firstname')
    //                                 ->label('Personel Adı:')
    //                                 ->inlineLabel(),

    //                             //
    //                         ]),

    //                     Infolists\Components\Tabs\Tab::make('Telefon Numaraları')
    //                         ->schema([
    //                             //
    //                         ]),

    //                     Infolists\Components\Tabs\Tab::make('Adres Bilgileri')
    //                         ->schema([
    //                             //
    //                         ]),

    //                     Infolists\Components\Tabs\Tab::make('Hesap Numaraları')
    //                         ->schema([
    //                             //
    //                         ]),

    //                     Infolists\Components\Tabs\Tab::make('Bağlantılar')
    //                         ->schema([
    //                             //
    //                         ]),
    //                 ])
    //                 ->contained(true),
    //         ])
    //         ->columns(1);
    // }

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

    public static function getRecordSubNavigation(Page $page): array
    {
        return $page->generateNavigationItems([
            Pages\EditEmployee::class,
            Pages\ManageCertificates::class,
            Pages\ManagePhones::class,
            Pages\ManageAddresses::class,
            Pages\ManageBankAccounts::class,
            // Pages\ManageAttachments::class,
            Pages\ManageEmergencyContact::class,
        ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListEmployees::route('/'),
            'create' => Pages\CreateEmployee::route('/create'),
            'view' => Pages\ViewEmployee::route('/{record}'),
            'edit' => Pages\EditEmployee::route('/{record}/edit'),
            'certificates' => Pages\ManageCertificates::route('/{record}/certificates'),
            'phones' => Pages\ManagePhones::route('/{record}/phones'),
            'addresses' => Pages\ManageAddresses::route('/{record}/addresses'),
            'bank-accounts' => Pages\ManageBankAccounts::route('/{record}/bank-accounts'),
            'attachments' => Pages\ManageAttachments::route('/{record}/attachments'),
            'emergency-contacts' => Pages\ManageEmergencyContact::route('/{record}/emergency-contacts'),

        ];
    }

    // public static function getEloquentQuery(): Builder
    // {
    //     return parent::getEloquentQuery()->with([
    //         'latestCertificates',
    //         'phones',
    //         'addresses',
    //         'emergencyContacts',
    //         'bankAccounts',
    //         'department',
    //     ]);
    // }

    public static function getGloballySearchableAttributes(): array
    {
        return ['firstname', 'lastname', 'identity_number', 'phones.phone_number'];
    }

    public static function getGlobalSearchResultTitle(Model $record): string | Htmlable
    {
        return $record->firstname.' '.$record->lastname;
    }

    public static function getCertificateFields($typeId = null)
    {
       return match ((string) $typeId) {
            '1' => [
                // SRC-5 Belgesi (ADR)
            ],
            '2' => [
                // Seyahat Sağlık Sigortası
            ],
            '3' => [
                // Sürücü Kartı
            ],
            default => [
                //
            ],
       };
    }
}
