<?php

namespace App\Filament\Resources;

use App\Filament\Resources\CurrencyResource\Pages;
use App\Filament\Resources\CurrencyResource\RelationManagers;
use App\Models\Currency;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Support\Enums\FontWeight;
use Filament\Notifications\Notification;

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

class CurrencyResource extends Resource
{
    protected static ?string $model = Currency::class;

    protected static ?string $modelLabel = 'Para Birimi';
    protected static ?string $pluralModelLabel = 'Para Birimleri';

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(self::$modelLabel.' Bilgileri')
                    ->columns(3)
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('Başlık')
                            ->placeholder('Türk Lirası')
                            ->required()
                            ->maxLength(100),

                        Forms\Components\TextInput::make('code')
                            ->label('Kısa Kod')
                            ->placeholder('TRY')
                            ->required()
                            ->length(10),

                        Forms\Components\TextInput::make('symbol')
                            ->label('Sembol')
                            ->placeholder('₺')
                            ->required()
                            ->maxLength(10),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Para Birimi')
                    ->description(fn ($record) => $record->code)
                    ->weight(FontWeight::Medium)
                    ->searchable(),

                Tables\Columns\TextColumn::make('buying')
                    ->label('Alış')
                    ->prefix('₺')
                    ->color('success')
                    ->weight(FontWeight::Medium),

                Tables\Columns\TextColumn::make('selling')
                    ->label('Satış')
                    ->prefix('₺')
                    ->color('success')
                    ->weight(FontWeight::Medium),

                Tables\Columns\TextColumn::make('symbol')
                    ->label('Sembol')
                    ->badge(),

                Tables\Columns\ToggleColumn::make('is_active')
                    ->label('Aktif/Pasif')
                    ->beforeStateUpdated(function ($record, $state) {
                        if ($record->is_default) {
                            Notification::make()
                                ->title($record->name)
                                ->body('Varsayılan olarak işaretli para biriminin durumunu pasif olarak işaretleyemezsiniz.')
                                ->warning()
                                ->send();

                            throw \Illuminate\Validation\ValidationException::withMessages([]);
                        }
                    })
                    ->alignCenter(),

                Tables\Columns\ToggleColumn::make('is_default')
                    ->label('Varsayılan')
                    ->beforeStateUpdated(function ($record, $state) {
                        if (!$record->is_active) {
                            Notification::make()
                                ->title($record->name)
                                ->body('Aktif olmayan bir para birimi, varsayılan olarak ayarlanamaz.')
                                ->warning()
                                ->send();

                            throw \Illuminate\Validation\ValidationException::withMessages([]);
                        } elseif ($record->is_default) {
                            Notification::make()
                                ->title($record->name)
                                ->body('İşlem yapmak istediğiniz para birimi, zaten varsayılan olarak işaretli.')
                                ->info()
                                ->send();

                            throw \Illuminate\Validation\ValidationException::withMessages([]);
                        } elseif ($state) {
                            $record
                                ->where('id', '!=', $record->id)
                                ->update(['is_default' => false]);

                            Notification::make()
                                ->title('Başarılı bir şekilde güncellendi.')
                                ->body("Varsayılan para birimi {$record->name} olarak değiştirildi.")
                                ->success()
                                ->send();
                        }
                    })
                    ->alignCenter(),

                Tables\Columns\ToggleColumn::make('is_featured')
                    ->label('Öne Çıkar')
                    ->alignCenter(),

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

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Güncelleme')
                    ->dateTime(),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\EditAction::make(),
                    // Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->bulkActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make(),
                // ]),
            ]);
    }

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

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