<?php

namespace App\Filament\Resources;

use App\Filament\Resources\InsuranceCompanyResource\Pages;
use App\Filament\Resources\InsuranceCompanyResource\RelationManagers;
use App\Models\InsuranceCompany;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Resources\Pages\Page;
use Filament\Pages\SubNavigationPosition;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Enums\IconPosition;
use Filament\Notifications\Notification;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class InsuranceCompanyResource extends Resource
{
    protected static ?string $model = InsuranceCompany::class;

    protected static ?string $modelLabel = 'Sigorta Şirketi';
    protected static ?string $pluralModelLabel = 'Sigorta Şirketleri';

    // protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationLabel = 'Sigorta Şirketleri';
    protected static ?string $navigationGroup = 'Yapılandırma';

    protected static int $globalSearchResultsLimit = 5;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('İşletme Bilgileri')
                    ->columns([
                        'lg' => 2,
                    ])
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('İşletme Adı')
                            ->required()
                            ->maxLength(255),

                        Forms\Components\TextInput::make('website')
                            ->label('Website')
                            ->prefix('https://')
                            ->maxLength(255),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('İşletme Adı')
                    ->weight(FontWeight::Medium)
                    ->searchable(),

                Tables\Columns\TextColumn::make('website')
                    ->label('Website')
                    ->icon('heroicon-c-arrow-top-right-on-square')
                    ->iconPosition(IconPosition::After)
                    ->url(fn ($state): string => 'https://'.$state)
                    ->openUrlInNewTab(),

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

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Güncelleme')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make()
                    ->action(function (InsuranceCompany $record) {
                        return static::handleDelete($record);
                    }),
                ]),
            ])
            ->bulkActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make()
                //     ->action(function (Collection $records) {
                //         return static::handleBulkDelete($records);
                //     }),
                // ]),
            ]);
    }

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

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

    protected static function handleDelete(Model $record)
    {
        try {
            $record->delete();
            Notification::make()
                ->title('Saved successfully')
                ->success()
                ->send();
        } catch (\Illuminate\Database\QueryException $e) {
            Notification::make()
                ->title('Kullanılıyor, silemezsin.')
                ->danger()
                ->send();
        }
    }

    protected static function handleBulkDelete(Collection $records)
    {
        $successCount = 0;
        $failCount = 0;
        $failRecords = [];

        foreach ($records as $record) {
            try {
                $record->delete();
                $successCount++;
            } catch (\Illuminate\Database\QueryException $e) {
                $failCount++;
                $failRecords[] = $record->name;
            }
        }

        if ($successCount > 0) {
            Notification::make()
                ->title("$successCount kayıt başarılı bir şekilde silindi.")
                ->success()
                ->send();
        }

        if ($failCount > 0) {
            $failedRecordsList = implode(', ', $failRecords);
            Notification::make()
                ->title("$failCount kayıt silinemedi: $failedRecordsList")
                ->danger()
                ->send();
        }
    }

}
