<?php

namespace App\Filament\AssociationAdmin\Imports;

use App\Enums\LicenseStatus;
use App\Models\WellLicense;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Illuminate\Support\Facades\Auth;

class AssociationWellLicenseImporter extends Importer
{
    protected static ?string $model = WellLicense::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('well_name')
                ->label(__('well_license.well_name'))
                ->exampleHeader(__('well_license.well_name'))
                ->requiredMapping()
                ->rules(['required', 'max:255']),

            ImportColumn::make('state')
                ->label(__('well_license.state'))
                ->exampleHeader(__('well_license.state'))
                ->requiredMapping()
                ->relationship(resolveUsing: function (string $state): ?\App\Models\State {
                    return \App\Models\State::query()
                        ->where('name', $state)
                        ->first();
                })
                ->rules(['required']),

            ImportColumn::make('city')
                ->label(__('well_license.city'))
                ->exampleHeader(__('well_license.city'))
                ->requiredMapping()
                ->relationship(resolveUsing: function (string $state): ?\App\Models\City {
                    return \App\Models\City::query()
                        ->where('name', $state)
                        ->first();
                })
                ->rules(['required']),

            ImportColumn::make('center')
                ->label(__('well_license.center'))
                ->exampleHeader(__('well_license.center'))
                ->requiredMapping()
                ->relationship(resolveUsing: function (string $state): ?\App\Models\Center {
                    return \App\Models\Center::query()
                        ->where('name', $state)
                        ->first();
                })
                ->rules(['required']),

            ImportColumn::make('lat')
                ->label(__('well_license.lat'))
                ->exampleHeader(__('well_license.lat'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 8)
                ->rules(['required', 'numeric', 'between:-90,90']),

            ImportColumn::make('lng')
                ->label(__('well_license.lng'))
                ->exampleHeader(__('well_license.lng'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 8)
                ->rules(['required', 'numeric', 'between:-180,180']),

            ImportColumn::make('well_depth')
                ->label(__('well_license.well_depth'))
                ->exampleHeader(__('well_license.well_depth'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 2)
                ->rules(['required', 'numeric', 'min:0']),

            ImportColumn::make('well_diameter')
                ->label(__('well_license.well_diameter'))
                ->exampleHeader(__('well_license.well_diameter'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 2)
                ->rules(['required', 'numeric', 'min:0']),

            ImportColumn::make('pump_size')
                ->label(__('well_license.pump_size'))
                ->exampleHeader(__('well_license.pump_size'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 2)
                ->rules(['required', 'numeric', 'min:0']),

            ImportColumn::make('withdrawal_amount')
                ->label(__('well_license.withdrawal_amount'))
                ->exampleHeader(__('well_license.withdrawal_amount'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 2)
                ->rules(['required', 'numeric', 'min:0']),
        ];
    }

    public function resolveRecord(): ?WellLicense
    {
        return new WellLicense;
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $successfulRows = $import->successful_rows;
        $rowWord = $successfulRows === 1 ? __('well_license.row') : __('well_license.rows');

        $body = __('well_license.import_completed', [
            'count' => number_format($successfulRows),
            'rows' => $rowWord,
        ]);

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $failedRowWord = $failedRowsCount === 1 ? __('well_license.row') : __('well_license.rows');
            $body .= ' '.__('well_license.import_failed_rows', [
                'count' => number_format($failedRowsCount),
                'rows' => $failedRowWord,
            ]);
        }

        return $body;
    }

    protected function beforeSave(): void
    {
        // Set association_id to current user's association
        if (Auth::check() && Auth::user()->association_id) {
            $this->record->association_id = Auth::user()->association_id;
        }

        // Set default status if not provided
        if (! isset($this->data['status']) || blank($this->data['status'])) {
            $this->data['status'] = LicenseStatus::INITIAL_APPROVAL;
        }

        // Set created_by to current user if creating new record
        if (! $this->record->exists && Auth::check()) {
            $this->record->created_by = Auth::id();
        }
    }
}
