<?php

namespace App\Filament\Office\Resources;

use Filament\Forms;
use Filament\Tables;
use App\Models\Company;
use Filament\Forms\Form;
use Filament\Tables\Table;
use App\Enums\CompanyTypes;
use Filament\Infolists\Infolist;
use Filament\Resources\Resource;
use Filament\Support\Enums\Alignment;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Database\Eloquent\Model;
use Filament\Infolists\Components\Split;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\Layout\Grid;
use Filament\Tables\Columns\Layout\Stack;
use Illuminate\Database\Eloquent\Builder;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ImageEntry;
use App\Filament\Office\Resources\CompanyResource\Pages;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Filament\Office\Resources\CompanyResource\CompanyForms;
use App\Filament\Office\Resources\CompanyResource\RelationManagers;

class CompanyResource extends Resource
{
    protected static ?string $model = Company::class;

    protected static ?string $slug = 'companies/customers';

    protected static ?string $navigationGroup = 'Companies';
    protected static ?string $navigationLabel = 'Customer\'s Companies';
    protected static ?string $navigationIcon = 'heroicon-o-briefcase';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                CompanyForms::getAddForm()
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Grid::make([
                    'lg' => 2,
                    '2xl' => 5,
                ])
                ->schema([
                    TextColumn::make('name')
                        ->formatStateUsing(fn(?Model $record): string => $record->name . ' (' . $record->code . ')')
                        ->searchable()
                        ->sortable()
                        ->grow(false)
                        ->weight(FontWeight::Bold),
                    TextColumn::make('type')->badge()
                        // ->formatStateUsing(fn (string $state): string => strtoupper($state))
                        // ->color(fn (string $state): string => match ($state) {
                        //     CompanyTypes::CNF->value => 'gray',
                        //     CompanyTypes::BRANCH->value => 'warning',
                        //     CompanyTypes::CUSTOMER->value => 'success',
                        //     CompanyTypes::BANK->value => 'danger',
                        //     CompanyTypes::AGENT->value => 'agent',
                        // })
                        ->alignment(Alignment::End),
                    TextColumn::make('address')
                        ->description(function(Company $record):string {
                            $desc = '';
                            if ($record->city != null) {
                                $desc .= $record->city->name;
                            }
                            
                            if ($record->state != null) {
                                if ($record->city != null) {
                                    $desc .= ' ⋅ ';
                                }
                                $desc .= $record->state->name;
                            }
                            
                            if ($record->country != null) {
                                if ($record->state != null) {
                                    $desc .= ' ⋅ ';
                                }
                                if ($record->city != null && $record->state == null) {
                                    $desc .= ' ⋅ ';
                                }
                                $desc .= $record->country->name;
                            }
                            return $desc;
                        })
                        ->formatStateUsing(fn (Company $record): string => $record->address . (($record->post_code != null)?' ⋅ ' . $record->post_code:''))
                        ->searchable()
                        ->columnSpan('full'),
                    Stack::make([
                        // TextColumn::make('name')->weight(FontWeight::Bold),
                        // TextColumn::make('address')
                        //     ->description(function(Company $record):string {
                        //         $desc = '';
                        //         if ($record->city != null) {
                        //             $desc .= $record->city->name;
                        //         }
                                
                        //         if ($record->state != null) {
                        //             if ($record->city != null) {
                        //                 $desc .= ' ⋅ ';
                        //             }
                        //             $desc .= $record->state->name;
                        //         }
                                
                        //         if ($record->country != null) {
                        //             if ($record->state != null) {
                        //                 $desc .= ' ⋅ ';
                        //             }
                        //             if ($record->city != null && $record->state == null) {
                        //                 $desc .= ' ⋅ ';
                        //             }
                        //             $desc .= $record->country->name;
                        //         }
                        //         return $desc;
                        //     })
                        //     // (($record->city != null)?$record->city->name:'') . ($record->state != null)?(($record->city != null)?' ⋅ ':'').$record->state->name . ($record->country != null)?(($record->state != null)?' ⋅ ':($record->city != null && $record->state == null)?' ⋅ ':'').$record->country->name . $record->city->name . ' ⋅ ' . $record->state->name . ' ⋅ ' . $record->country->name
                        //     ->formatStateUsing(fn (Company $record): string => $record->address . (($record->post_code != null)?' ⋅ ' . $record->post_code:''))
                        //     ->searchable(),
                        TextColumn::make('mobile')
                            ->icon('heroicon-o-device-phone-mobile'),
                        TextColumn::make('tel')
                            ->icon('heroicon-o-phone'),
                        TextColumn::make('primary_email')
                            ->icon('heroicon-o-envelope'),
                        TextColumn::make('website')
                            ->icon('heroicon-o-globe-alt'),
                    ])->columnSpan([
                        'lg' => 'full',
                        '2xl' => 2,
                    ])
                    ->collapsible(),
                    Stack::make([
                        // TextColumn::make('contacts')
                        //     ->formatStateUsing(fn($state)=>dd($state))
                        //     ->listWithLineBreaks()
                        //     ->bulleted(),

                        ImageColumn::make('contacts.pic')
                            ->circular()
                            ->stacked()
                            ->limit(3)
                            ->limitedRemainingText(isSeparate: true),
                    ])
                    ->collapsible(),
                ]),
                // Tables\Columns\TextColumn::make('city_id')
                //     ->numeric()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('state_id')
                //     ->numeric()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('country_id')
                //     ->numeric()
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('name')
                //     ->description(function(Company $record):string {
                //         $desc = '';
                //         if ($record->city != null) {
                //             $desc .= $record->city->name;
                //         }
                        
                //         if ($record->state != null) {
                //             if ($record->city != null) {
                //                 $desc .= ' ⋅ ';
                //             }
                //             $desc .= $record->state->name;
                //         }
                        
                //         if ($record->country != null) {
                //             if ($record->state != null) {
                //                 $desc .= ' ⋅ ';
                //             }
                //             if ($record->city != null && $record->state == null) {
                //                 $desc .= ' ⋅ ';
                //             }
                //             $desc .= $record->country->name;
                //         }
                //         return $desc;
                //     })
                //     // (($record->city != null)?$record->city->name:'') . ($record->state != null)?(($record->city != null)?' ⋅ ':'').$record->state->name . ($record->country != null)?(($record->state != null)?' ⋅ ':($record->city != null && $record->state == null)?' ⋅ ':'').$record->country->name . $record->city->name . ' ⋅ ' . $record->state->name . ' ⋅ ' . $record->country->name
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('address')
                //     ->grow(false)
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('post_code')
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('website')
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('primary_email')
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('tel')
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('mobile')
                //     ->searchable(),
                // Tables\Columns\TextColumn::make('admin.name')
                //     ->sortable(),
                // Tables\Columns\TextColumn::make('created_at')
                //     ->dateTime()
                //     ->sortable()
                //     ->toggleable(isToggledHiddenByDefault: true),
                // Tables\Columns\TextColumn::make('updated_at')
                //     ->dateTime()
                //     ->sortable()
                //     ->toggleable(isToggledHiddenByDefault: true),
                // Tables\Columns\TextColumn::make('deleted_at')
                //     ->dateTime()
                //     ->sortable()
                //     ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\ViewAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->emptyStateActions([
                Tables\Actions\CreateAction::make(),
            ])
            ->contentGrid([
                'md' => 2,
                'xl' => 3,
            ])
            ->paginated([15, 25, 50, 100, 'all']);
    }

    public static function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Section::make('Company Logo')
                    ->columns([
                        'sm' => 1,
                        'xl' => 2,
                    ])
                    ->schema([
                        ImageEntry::make('logo'),
                        ImageEntry::make('dark_logo'),
                    ]),
                Section::make('Company Intro')
                    ->columns([
                        'sm' => 1,
                        'xl' => 2,
                        '2xl' => 3,
                    ])
                    ->schema([
                        TextEntry::make('name')
                            ->columnSpan([
                                'sm' => 1,
                                'xl' => 2,
                                '2xl' => 3,
                            ])
                            ->formatStateUsing(fn(?Model $record): string => $record->name . ' (' . $record->code . ')')
                            ->weight(FontWeight::Bold),
                        TextEntry::make('address')
                            ->formatStateUsing(fn(?Model $record): string => $record->address . ', ' . $record->state->name . ', ' . $record->city->name . ' - ' . $record->post_code . ', ' . $record->country->name)
                            ->columnSpan([
                                'sm' => 1,
                                'xl' => 2,
                                '2xl' => 3,
                            ])
                            ->html(),
                        TextEntry::make('mobile')
                            ->label('Mobile Number')
                            ->icon('heroicon-o-device-phone-mobile'),
                        TextEntry::make('tel')
                            ->label('Telephone Number')
                            ->icon('heroicon-o-phone'),
                        TextEntry::make('primary_email')
                            ->url((fn(string $state):string => 'mailto:'.$state), shouldOpenInNewTab: true)
                            ->icon('heroicon-o-envelope'),
                        TextEntry::make('website')
                            ->url((fn(string $state):string => str_starts_with($state, 'http')?$state:'http://'.$state), shouldOpenInNewTab: true)
                            ->icon('heroicon-o-globe-alt'),
                    ])->grow(),
                Section::make('Others Info')
                    ->columns([
                        'sm' => 1,
                        'xl' => 2,
                        '2xl' => 3,
                    ])
                    ->schema([
                        TextEntry::make('type')
                            ->badge()
                            ->label('Type'),
                        // TextEntry::make('admin.name')
                        //     ->label('Company Admin')
                        //     ->icon('heroicon-o-user'),
                        TextEntry::make('note')
                            ->icon('heroicon-o-document')
                            ->columnSpan([
                                'sm' => 1,
                                'xl' => 2,
                                '2xl' => 3,
                            ])
                            ->html(),
                    ]),
            ]);
    }
    
    public static function getRelations(): array
    {
        return [
            // RelationManagers\ContactsRelationManager::class,
            RelationManagers\BlRelationManager::class,
        ];
    }
    
    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCompanies::route('/'),
            'create' => Pages\CreateCompany::route('/create'),
            'edit' => Pages\EditCompany::route('/{record}/edit'),
            'view' => Pages\ViewCompany::route('/{record}/view'),
        ];
    }    
    
    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
                'organization'
            ]);
    }
}
