<?php

namespace App\Filament\Exports;

use App\Models\AdoptionApplication;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;

class AdoptionApplicationExporter extends Exporter
{
    protected static ?string $model = AdoptionApplication::class;

    public static function getColumns(): array
    {
        return [
            // Application fields
            ExportColumn::make('id')
                ->label('Application ID'),
            ExportColumn::make('created_at')
                ->label('Submitted Date')
                ->formatStateUsing(fn ($state) => $state?->format('Y-m-d H:i:s')),
            ExportColumn::make('updated_at')
                ->label('Last Updated')
                ->formatStateUsing(fn ($state) => $state?->format('Y-m-d H:i:s')),
            ExportColumn::make('status')
                ->label('Status'),
            ExportColumn::make('cancellation_reason')
                ->label('Cancellation Reason')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),

            // User fields
            ExportColumn::make('user.name')
                ->label('User Name')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.email')
                ->label('User Email')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.phone')
                ->label('User Phone')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.full_address')
                ->label('User Address')
                ->formatStateUsing(fn ($state) => $state ?: 'N/A'),

            // First Pet fields
            ExportColumn::make('pet.name')
                ->label('Pet Name')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('pet.species.name')
                ->label('Pet Species')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('pet.breed.name')
                ->label('Pet Breed')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('pet.age_in_years')
                ->label('Pet Age')
                ->formatStateUsing(fn ($state) => $state ?? 'Unknown'),
            ExportColumn::make('pet.gender')
                ->label('Pet Gender')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('pet.status')
                ->label('Pet Status')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),

            // Second Pet fields (if exists)
            ExportColumn::make('secondPet.name')
                ->label('Second Pet Name')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('secondPet.species.name')
                ->label('Second Pet Species')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('secondPet.breed.name')
                ->label('Second Pet Breed')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('secondPet.age_in_years')
                ->label('Second Pet Age')
                ->formatStateUsing(fn ($state) => $state ?? 'Unknown'),
            ExportColumn::make('secondPet.gender')
                ->label('Second Pet Gender')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('secondPet.status')
                ->label('Second Pet Status')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),

            // Form answers as JSON
            ExportColumn::make('form_answers')
                ->label('Form Answers (JSON)')
                ->state(function (AdoptionApplication $record): string {
                    return $record->answers->map(function ($answer) {
                        return [
                            'question' => $answer->question_label,
                            'answer' => $answer->formatted_answer,
                        ];
                    })->toJson();
                }),
        ];
    }

    public static function modifyQuery(Builder $query): Builder
    {
        // Eager load relationships to prevent N+1 queries
        return $query->with([
            'user',
            'pet.species',
            'pet.breed',
            'secondPet.species',
            'secondPet.breed',
            'answers',
        ]);
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Your adoption application export has completed and '.Number::format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.';

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $body .= ' '.Number::format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.';
        }

        return $body;
    }
}
