<?php

namespace App\Filament\Imports;

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

class StationLicenseImporter extends Importer
{
    protected static ?string $model = StationLicense::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('association')
                ->label(__('station_license.association'))
                ->exampleHeader(__('station_license.association'))
                ->requiredMapping()
                ->relationship(resolveUsing: 'name')
                ->rules(['required']),

            ImportColumn::make('station_name')
                ->label(__('station_license.station_name'))
                ->exampleHeader(__('station_license.station_name'))
                ->requiredMapping()
                ->rules(['required', 'max:255']),

            ImportColumn::make('state')
                ->label(__('station_license.state'))
                ->exampleHeader(__('station_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(__('station_license.city'))
                ->exampleHeader(__('station_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(__('station_license.center'))
                ->exampleHeader(__('station_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(__('station_license.lat'))
                ->exampleHeader(__('station_license.lat'))
                ->requiredMapping()
                ->numeric(decimalPlaces: 8)
                ->rules(['required', 'numeric', 'between:-90,90']),

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

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

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

            ImportColumn::make('operation_start_date')
                ->label(__('station_license.operation_start_date'))
                ->exampleHeader(__('station_license.operation_start_date'))
                ->requiredMapping()
                ->castStateUsing(function (?string $state): ?string {
                    if (blank($state)) {
                        return null;
                    }

                    try {
                        return \Carbon\Carbon::parse($state)->format('Y-m-d');
                    } catch (\Exception $e) {
                        return null;
                    }
                })
                ->rules(['required', 'date']),

            ImportColumn::make('has_environmental_permit')
                ->label(__('station_license.has_environmental_permit'))
                ->exampleHeader(__('station_license.has_environmental_permit'))
                ->boolean()
                ->rules(['nullable', 'boolean']),

            ImportColumn::make('has_evaporation_ponds')
                ->label(__('station_license.has_evaporation_ponds'))
                ->exampleHeader(__('station_license.has_evaporation_ponds'))
                ->boolean()
                ->rules(['nullable', 'boolean']),

            ImportColumn::make('evaporation_ponds_count')
                ->label(__('station_license.evaporation_ponds_count'))
                ->exampleHeader(__('station_license.evaporation_ponds_count'))
                ->numeric()
                ->rules(['nullable', 'integer', 'min:0']),

            ImportColumn::make('evaporation_ponds_area')
                ->label(__('station_license.evaporation_ponds_area'))
                ->exampleHeader(__('station_license.evaporation_ponds_area'))
                ->numeric(decimalPlaces: 2)
                ->rules(['nullable', 'numeric', 'min:0']),
        ];
    }

    public function resolveRecord(): ?StationLicense
    {
        // Check if updating existing records based on station_name
        // if ($this->options['updateExisting'] ?? false) {
        //     return StationLicense::query()
        //         ->where('station_name', $this->data['station_name'])
        //         ->where('association_id', $this->data['association'])
        //         ->firstOrNew();
        // }

        return new StationLicense;
    }

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

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

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

        return $body;
    }

    public static function getOptionsFormComponents(): array
    {
        return [
            // \Filament\Forms\Components\Checkbox::make('updateExisting')
            //     ->label(__('station_license.update_existing_records'))
            //     ->helperText(__('station_license.update_existing_records_helper')),
        ];
    }

    protected function beforeSave(): void
    {
        // 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();
        }
    }
}
