<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ClientResource\Pages;
use App\Filament\Resources\ClientResource\RelationManagers;
use App\Models\Client;
use App\Models\Country;

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\Support\Enums\MaxWidth;

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

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

use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Actions\Tables\ExportBulkAction;

class ClientResource extends Resource
{
    protected static ?string $model = Client::class;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $modelLabel = 'Müşteri';
    protected static ?string $pluralModelLabel = 'Müşteriler';

    // protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationLabel = 'Müşteriler';
    protected static ?string $navigationGroup = 'Uygulama';

    protected static ?int $navigationSort = 1;

    protected static int $globalSearchResultsLimit = 2;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Müşteri Bilgileri')
                    ->columns([
                        'lg' => 3,
                    ])
                    ->icon('heroicon-m-user-circle')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('İşletme Adı')
                            ->required()
                            ->maxLength(255)
                            ->columnSpanFull(),

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

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

                        Forms\Components\Select::make('country_id')
                            ->label('Ülke')
                            ->options(Country::active()->pluck('name', 'id'))
                            ->searchable()
                            ->default(222)
                            ->required(),

                        Forms\Components\TextInput::make('maturity_period')
                            ->label('Vade Süresi')
                            ->maxLength(255),

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

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

                Forms\Components\Section::make()
                    ->columns([
                        'lg' => 1,
                    ])
                    ->schema([
                        Forms\Components\Select::make('serviceCountries')
                            ->label('Çalıştığı Ülkeler')
                            ->relationship('serviceCountries', 'name')
                            ->searchable()
                            ->preload()
                            ->multiple(),
                    ]),

                Forms\Components\Section::make('İşletme Bağlantıları')
                    ->columns([
                        'lg' => 1,
                    ])
                    ->icon('heroicon-m-users')
                    ->schema([
                        Forms\Components\Repeater::make('contacts')
                            ->label('')
                            ->relationship()
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Kişi')
                                    ->required()
                                    ->maxLength(100),

                                Forms\Components\TextInput::make('phone_number')
                                    ->label('Telefon')
                                    ->maxLength(100),

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

                                Forms\Components\Textarea::make('notes')
                                    ->label('Notlar')
                                    ->autosize()
                                    ->columnSpanFull(),
                            ])
                            ->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
                            ->addActionLabel('Yeni Kişi Ekle')
                            ->orderColumn('sort_order')
                            ->reorderable(true)
                            ->reorderableWithButtons()
                            ->collapsible()
                            ->collapsed()
                            ->deleteAction(fn (Forms\Components\Actions\Action $action) => $action->requiresConfirmation())
                            ->defaultItems(0)
                            ->columns(3),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('id', 'desc')
            ->heading(static::$pluralModelLabel.' Listesi')
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('İşletme')
                    ->weight(FontWeight::Medium)
                    ->description(fn ($record) => $record?->website)
                    ->searchable(),

                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\TextColumn::make('tax_number')
                    ->label('Vergi Numarası'),

                Tables\Columns\TextColumn::make('tax_office')
                    ->label('Vergi Dairesi'),

                Tables\Columns\TextColumn::make('country.name')
                    ->label('Ülke')
                    ->badge(),

                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([
                //
            ])
            // ->recordAction(Tables\Actions\ViewAction::class)
            ->recordUrl(null)
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),
                    Tables\Actions\EditAction::make(),
                    Tables\Actions\DeleteAction::make(),
                ]),
            ])
            ->headerActions([
                ExportAction::make()->exports([
                    \App\Filament\Exports\ClientExporter::make(),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),

                    ExportBulkAction::make()->exports([
                        \App\Filament\Exports\ClientExporter::make(),
                    ]),
                ]),
            ]);
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Tabs::make('Tabs')
                    ->tabs([
                        Infolists\Components\Tabs\Tab::make('Müşteri Bilgileri')
                            ->schema([
                                Infolists\Components\TextEntry::make('name')
                                    ->label('İşletme Adı:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('tax_number')
                                    ->label('Vergi Numarası:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('tax_office')
                                    ->label('Vergi Dairesi:')
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('phones.name')
                                    ->label('Telefon:')
                                    ->formatStateUsing(function ($record): string {
                                        $primaryPhone = optional($record->phones->where('is_primary', true)->first());

                                        if (!$primaryPhone->name) {
                                            return '-';
                                        }

                                        return $primaryPhone->phone_number;
                                    })
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('email')
                                    ->label('E-posta Adresi:')
                                    ->icon('heroicon-c-envelope')
                                    ->iconPosition(IconPosition::After)
                                    ->hidden(fn ($state): bool => !$state)
                                    ->url(fn ($state): string => 'mailto:'.$state)
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('addresses.name')
                                    ->label('Adres:')
                                    ->formatStateUsing(function ($record): string {
                                        $primaryAddress = optional($record->addresses->where('is_primary', true)->first());

                                        if (!$primaryAddress->name) {
                                            return '-';
                                        }

                                        $fullAddress = $primaryAddress->address;

                                        if ($primaryAddress->district && $primaryAddress->city) {
                                            $fullAddress .=  '<br />'.$primaryAddress->district .'/'. $primaryAddress->city;
                                        }

                                        if ($primaryAddress->postal_code) {
                                            $fullAddress .= ', '. $primaryAddress->postal_code;
                                        }

                                        $encodedAddress = urlencode(str_replace('<br />', ' ', $fullAddress));

                                        $fullAddress .= '
                                            <div class="">
                                                <a href="'.'https://www.google.com/maps/search/'.$encodedAddress.'" target="_blank" class="text-xs text-primary-500">
                                                    Google Maps\'te görüntülemek için tıklayın.
                                                </a>
                                            </div>';

                                        return $fullAddress;
                                    })
                                    ->html()
                                    ->inlineLabel(),

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

                                Infolists\Components\TextEntry::make('maturity_period')
                                    ->label('Vade Süresi:')
                                    ->badge()
                                    ->inlineLabel(),

                                Infolists\Components\TextEntry::make('serviceCountries.name')
                                    ->label('Çalıştığı Ülkeler:')
                                    ->listWithLineBreaks()
                                    ->bulleted()
                                    ->inlineLabel(),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Telefon Numaraları')
                            ->schema([
                                //
                                Infolists\Components\RepeatableEntry::make('phones')
                                    ->label('')
                                    ->schema([
                                        Infolists\Components\TextEntry::make('name')
                                            ->label('Başlık:')
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('phone_number')
                                            ->label('Telefon Numarası:')
                                            ->inlineLabel(),
                                    ]),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Adres Bilgileri')
                            ->schema([
                                Infolists\Components\RepeatableEntry::make('addresses')
                                    ->label('')
                                    ->schema([
                                        Infolists\Components\TextEntry::make('name')
                                            ->label('')
                                            ->weight(FontWeight::Medium),

                                        Infolists\Components\TextEntry::make('address')
                                            ->label(''),

                                        Infolists\Components\TextEntry::make('city')
                                            ->label('')
                                            ->formatStateUsing(fn ($record) => $record->district.'/'.$record->city.', '.$record->postal_code),
                                    ]),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Hesap Numaraları')
                            ->schema([
                                Infolists\Components\RepeatableEntry::make('bankAccounts')
                                    ->label('')
                                    ->schema([
                                        Infolists\Components\TextEntry::make('name')
                                            ->label('Banka:')
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('recipient')
                                            ->label('Alıcı:')
                                            ->inlineLabel()
                                            ->default('-'),

                                        Infolists\Components\TextEntry::make('iban')
                                            ->label('IBAN:')
                                            ->icon('heroicon-o-document-duplicate')
                                            ->iconPosition(IconPosition::After)
                                            ->copyable()
                                            ->copyMessageDuration(1100)
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('account_number')
                                            ->label('Hesap Numarası:')
                                            ->inlineLabel()
                                            ->default('-'),

                                        Infolists\Components\TextEntry::make('branch_name')
                                            ->label('Şube:')
                                            ->inlineLabel()
                                            ->default('-'),
                                    ]),
                            ]),

                        Infolists\Components\Tabs\Tab::make('Bağlantılar')
                            ->schema([
                                Infolists\Components\RepeatableEntry::make('contacts')
                                    ->label('')
                                    ->schema([
                                        Infolists\Components\TextEntry::make('name')
                                            ->label('Kişi:')
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('phone_number')
                                            ->label('Telefon:')
                                            ->hidden(fn ($state): bool => !$state)
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('email')
                                            ->label('E-posta Adresi:')
                                            ->icon('heroicon-c-envelope')
                                            ->iconPosition(IconPosition::After)
                                            ->hidden(fn ($state): bool => !$state)
                                            ->url(fn ($state): string => 'mailto:'.$state)
                                            ->inlineLabel(),

                                        Infolists\Components\TextEntry::make('notes')
                                            ->label('Notlar:')
                                            ->hidden(fn ($state): bool => !$state)
                                            ->inlineLabel(),
                                    ]),
                            ]),
                    ])
                    ->contained(true),
            ])
            ->columns(1);
    }

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

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListClients::route('/'),
            'create' => Pages\CreateClient::route('/create'),
            // 'view' => Pages\ViewClient::route('/{record}'),
            'edit' => Pages\EditClient::route('/{record}/edit'),
            'phones' => Pages\ManagePhones::route('/{record}/phones'),
            'addresses' => Pages\ManageAddresses::route('/{record}/addresses'),
            'bank_accounts' => Pages\ManageBankAccounts::route('/{record}/bank-accounts'),
        ];
    }
}
