<?php

namespace App\Filament\Imports;

use App\Enums\LicenseStatus;
use App\Models\Association;
use App\Models\Center;
use App\Models\City;
use App\Models\State;
use App\Models\WellLicense;
use EightyNine\ExcelImport\EnhancedDefaultImport;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;

class WellLicenseExcelImport extends EnhancedDefaultImport
{
    protected function beforeCollection(Collection $collection): void
    {
        // Validate required headers
        $requiredHeaders = [
            'association',
            'well_name',
            'state',
            'city',
            'center',
            'lat',
            'lng',
            'well_depth',
            'well_diameter',
            'pump_size',
            'withdrawal_amount',
        ];

        $this->validateHeaders($requiredHeaders, $collection);

        // Check if collection is not empty
        if ($collection->isEmpty()) {
            $this->stopImportWithError(__('well_license.import_no_data'));
        }
    }

    protected function beforeCreateRecord(array $data, $row): void
    {
        // Validate association exists
        if (isset($data['association'])) {
            $association = Association::where('name', $data['association'])->first();
            if (! $association) {
                $this->stopImportWithError(
                    __('well_license.import_association_not_found', ['name' => $data['association']])
                );
            }
        }

        // Validate state exists
        if (isset($data['state'])) {
            $state = State::where('name', $data['state'])->first();
            if (! $state) {
                $this->stopImportWithError(
                    __('well_license.import_state_not_found', ['name' => $data['state']])
                );
            }
        }

        // Validate city exists and belongs to state
        if (isset($data['city']) && isset($state)) {
            $city = City::where('name', $data['city'])
                ->where('state_id', $state->id)
                ->first();
            if (! $city) {
                $this->stopImportWithError(
                    __('well_license.import_city_not_found', ['name' => $data['city'], 'state' => $state->name])
                );
            }
        }

        // Validate center exists and belongs to city
        if (isset($data['center']) && isset($city)) {
            $center = Center::where('name', $data['center'])
                ->where('city_id', $city->id)
                ->first();
            if (! $center) {
                $this->stopImportWithError(
                    __('well_license.import_center_not_found', ['name' => $data['center'], 'city' => $city->name])
                );
            }
        }

        // Check for duplicate well name within the same association
        if (isset($data['well_name']) && isset($association)) {
            $exists = WellLicense::where('well_name', $data['well_name'])
                ->where('association_id', $association->id)
                ->exists();

            if ($exists) {
                $this->stopImportWithWarning(
                    __('well_license.import_duplicate_well', ['name' => $data['well_name'], 'association' => $association->name])
                );
            }
        }
    }

    public function collection(Collection $collection)
    {
        foreach ($collection as $row) {
            $data = $this->prepareRowData($row);

            $this->beforeCreateRecord($data, $row);

            // Resolve relationships
            $association = Association::where('name', $data['association'])->first();
            $state = State::where('name', $data['state'])->first();
            $city = City::where('name', $data['city'])->where('state_id', $state->id)->first();
            $center = Center::where('name', $data['center'])->where('city_id', $city->id)->first();

            // Create the well license
            $wellLicense = WellLicense::create([
                'association_id' => $association->id,
                'well_name' => $data['well_name'],
                'state_id' => $state->id,
                'city_id' => $city->id,
                'center_id' => $center->id,
                'lat' => $data['lat'],
                'lng' => $data['lng'],
                'well_depth' => $data['well_depth'],
                'well_diameter' => $data['well_diameter'] ?? null,
                'pump_size' => $data['pump_size'] ?? null,
                'withdrawal_amount' => $data['withdrawal_amount'] ?? null,
                'status' => LicenseStatus::PENDING_REQUIREMENTS,
                'created_by' => Auth::id(),
            ]);

            $this->afterCreateRecord($data, $row);
        }
    }

    protected function prepareRowData($row): array
    {
        return [
            'association' => $row['association'] ?? null,
            'well_name' => $row['well_name'] ?? null,
            'state' => $row['state'] ?? null,
            'city' => $row['city'] ?? null,
            'center' => $row['center'] ?? null,
            'lat' => $row['lat'] ?? null,
            'lng' => $row['lng'] ?? null,
            'well_depth' => $row['well_depth'] ?? null,
            'well_diameter' => $row['well_diameter'] ?? null,
            'pump_size' => $row['pump_size'] ?? null,
            'withdrawal_amount' => $row['withdrawal_amount'] ?? null,
        ];
    }

    protected function afterCollection(Collection $collection): void
    {
        $count = $collection->count();
        $this->stopImportWithSuccess(
            __('well_license.import_success', ['count' => $count])
        );
    }
}
