<?php

namespace App\Filament\Resources\Pets\Tables;

use App\Filament\Resources\Pets\PetResource;
use App\Models\AdoptionApplication;
use App\Models\Pet;
use App\Models\Setting;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ReplicateAction;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class PetsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                ImageColumn::make('images')
                    ->label('Image')
                    ->circular()
                    ->defaultImageUrl(url('/images/placeholder-pet.png'))
                    ->state(fn ($record) => $record->images[0] ?? null),
                TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('species.name')
                    ->searchable()
                    ->sortable()
                    ->badge()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('breed.name')
                    ->searchable()
                    ->sortable()
                    ->toggleable()
                    ->limit(30),
                TextColumn::make('age_in_years')
                    ->label('Age')
                    ->default('Unknown')
                    ->sortable(query: function ($query, string $direction) {
                        return $query->orderBy('date_of_birth', $direction === 'asc' ? 'desc' : 'asc');
                    })
                    ->toggleable(),
                TextColumn::make('color')
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->placeholder('N/A'),
                TextColumn::make('gender')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'male' => 'info',
                        'female' => 'warning',
                        default => 'gray',
                    })
                    ->toggleable(),
                TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'available' => 'Available',
                        'pending' => 'Pending',
                        'adopted' => 'Adopted',
                        'coming_soon' => 'Not Available',
                        default => $state,
                    })
                    ->color(fn (string $state): string => match ($state) {
                        'available' => 'success',
                        'pending' => 'warning',
                        'adopted' => 'gray',
                        'coming_soon' => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),
                ToggleColumn::make('is_visible')
                    ->label('Visible'),
                TextColumn::make('intake_date')
                    ->date()
                    ->sortable()
                    ->toggleable()
                    ->placeholder('N/A'),
                TextColumn::make('adoption_date')
                    ->label('Approval date')
                    ->timezone(auth()->user()->timezone)
                    ->date()
                    ->sortable()
                    ->toggleable()
                    ->placeholder('N/A'),
                TextColumn::make('created_at')
                    ->timezone(auth()->user()->timezone)
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('species_id')
                    ->label('Species')
                    ->relationship('species', 'name')
                    ->preload(),
                SelectFilter::make('gender')
                    ->options([
                        'male' => 'Male',
                        'female' => 'Female',
                        'unknown' => 'Unknown',
                    ]),
                SelectFilter::make('size')
                    ->options([
                        'small' => 'Small',
                        'medium' => 'Medium',
                        'large' => 'Large',
                        'extra_large' => 'Extra Large',
                    ]),
                SelectFilter::make('vaccination_status')
                    ->label('Vaccinated')
                    ->options([
                        true => 'Yes',
                        false => 'No',
                    ]),
                SelectFilter::make('special_needs')
                    ->label('Special Needs')
                    ->options([
                        true => 'Yes',
                        false => 'No',
                    ]),
                SelectFilter::make('is_spayed_neutered')
                    ->label('Spayed/Neutered')
                    ->options([
                        true => 'Yes',
                        false => 'No',
                    ]),
            ])
            ->recordActions([
                EditAction::make(),
                ReplicateAction::make('replicate')
                    ->label('Copy & Edit')
                    ->icon(Heroicon::OutlinedSquare2Stack)
                    ->color('gray')
                    ->requiresConfirmation()
                    ->modalHeading(fn (Pet $record) => "Copy {$record->name}?")
                    ->modalDescription(fn (Pet $record) => "Creates a hidden copy named \"Copy of {$record->name}\" with the status reset to Available and no photos, then opens it for editing.")
                    ->excludeAttributes(['adoption_date', 'images'])
                    ->beforeReplicaSaved(function (Pet $replica): void {
                        $replica->name = 'Copy of '.$replica->name;
                        $replica->slug = Pet::generateUniqueSlug($replica->name);
                        $replica->status = 'available';
                        $replica->is_visible = false;
                        $replica->adoption_date = null;
                    })
                    ->successRedirectUrl(fn (Pet $replica) => PetResource::getUrl('edit', ['record' => $replica])),
                Action::make('backfillApplication')
                    ->label('Backfill Application')
                    ->icon(Heroicon::OutlinedDocumentPlus)
                    ->color('warning')
                    ->url(fn (?Pet $record) => $record ? PetResource::getUrl('backfill', ['record' => $record]) : null)
                    ->visible(function (?Pet $record) {
                        if (! $record) {
                            return false;
                        }
                        if (! Setting::get('require_application_for_manual_adoption', false)) {
                            return false;
                        }

                        if ($record->status !== 'adopted') {
                            return false;
                        }

                        return ! AdoptionApplication::query()
                            ->where(function (Builder $query) use ($record) {
                                $query->where('pet_id', $record->id)
                                    ->orWhere('second_pet_id', $record->id);
                            })
                            ->whereNotIn('status', ['cancelled', 'rejected', 'archived'])
                            ->exists();
                    }),
                Action::make('print_bio')
                    ->label('Print Bio')
                    ->icon(Heroicon::OutlinedPrinter)
                    ->color('gray')
                    ->url(fn (?Pet $record) => $record ? route('pets.print', $record) : null)
                    ->openUrlInNewTab(),
                Action::make('markAsAdopted')
                    ->label('Mark as Adopted')
                    ->icon(Heroicon::OutlinedHeart)
                    ->color('gray')
                    ->visible(fn (Pet $record) => in_array($record->status, ['available', 'pending', 'coming_soon']))
                    ->requiresConfirmation()
                    ->modalHeading('Mark as Adopted')
                    ->modalDescription(fn (Pet $record) => "Mark {$record->name} as adopted? No application will be created.")
                    ->modalSubmitActionLabel('Yes, mark as adopted')
                    ->action(fn (Pet $record) => $record->update([
                        'status' => 'adopted',
                        'adoption_date' => now(),
                    ])),
            ])
            ->toolbarActions([
                // BulkActionGroup::make([
                //     DeleteBulkAction::make(),
                // ]),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
