<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationOrderResource\Pages;

use App\Filament\AssociationAdmin\Resources\AssociationOrderResource;
use App\Models\Order;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class AssociationCreateOrder extends CreateRecord
{
    use CreateRecord\Concerns\HasWizard;

    protected static string $resource = AssociationOrderResource::class;

    public function getTitle(): string
    {
        return __('order.create_order');
    }

    protected function getCreateFormAction(): Action
    {
        return Action::make('create')
            ->label(__('order.create_order'))
            ->submit('create')
            ->keyBindings(['mod+s']);
    }

    protected function getSteps(): array
    {
        return [
            Forms\Components\Wizard\Step::make(__('order.order_information'))
                ->schema([
                    ...$this::getOrderInformationFields(),
                    ...$this::getLocationInformationFields(),
                    ...$this::getWaterSourceInformationFields(),
                ])
                ->columns(2),

            Forms\Components\Wizard\Step::make(__('order.project_details'))
                ->schema($this::getProjectDetailsFields())
                ->columns(1),

            Forms\Components\Wizard\Step::make(__('order.required_files'))
                ->schema(function (Get $get) {
                    return $this::getRequiredFilesFields($get);
                }),
        ];
    }

    /**
     * Get the order information form fields
     */
    public static function getOrderInformationFields(): array
    {
        return [

            Forms\Components\Hidden::make('association_id')
                ->default(fn () => Auth::user()->association_id),

            Forms\Components\Select::make('type')
                ->required()
                ->options(collect(Order::getOrderTypes())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->default(Order::TYPE_STATION)
                ->label(__('order.order_type'))
                ->live()
                ->afterStateUpdated(function (Set $set, $state) {
                    // Clear files when type changes
                    $requirements = Order::getTypeFileRequirements()[$state] ?? [];
                    foreach ($requirements as $fileKey => $fileTitle) {
                        $set($fileKey, null);
                    }
                }),

            Forms\Components\Hidden::make('status')
                ->default(fn () => Order::STATUS_PENDING_RECOMMENDATION),

            Forms\Components\Hidden::make('created_by')
                ->default(fn () => Auth::id()),
        ];
    }

    /**
     * Get the location information form fields
     */
    public static function getLocationInformationFields(): array
    {
        return [
            Forms\Components\Select::make('state_id')
                ->label(__('order.state'))
                ->relationship(
                    'state',
                    'name',
                    fn (Builder $query) => $query
                        ->whereHas('associations', fn ($q) => $q->where('associations.id', Auth::user()->association_id))
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set) {
                    $set('city_id', null);
                    $set('centers', []);
                }),

            Forms\Components\Select::make('city_id')
                ->label(__('order.city'))
                ->relationship(
                    'city',
                    'name',
                    fn (Builder $query, Get $get) => $query
                        ->where('state_id', $get('state_id'))
                        ->whereHas('associations', fn ($q) => $q->where('associations.id', Auth::user()->association_id))
                        ->orderByName()
                )
                ->required()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set, $state, Get $get) {
                    $set('centers', []);

                    // Auto-update map location when city is selected
                    if ($state) {
                        $locationService = app(\App\Services\LocationCoordinatesService::class);
                        $coordinates = $locationService->getCityCoordinates($state);

                        if ($coordinates) {
                            $set('location', $coordinates);
                            $set('lat', $coordinates['lat']);
                            $set('lng', $coordinates['lng']);
                        }
                    }
                }),

            Forms\Components\Select::make('centers')
                ->label(__('order.centers'))
                ->relationship('centers', 'name')
                ->required()
                ->multiple()
                ->searchable()
                ->getSearchResultsUsing(
                    fn (string $search, Get $get): array => \App\Models\Center::where('city_id', $get('city_id'))
                        ->where('name', 'like', "%{$search}%")
                        ->whereHas('associations', fn ($q) => $q->where('associations.id', Auth::user()->association_id))
                        ->pluck('name', 'id')
                        ->toArray()
                )
                ->preload()
                ->live()
                ->options(function (Get $get) {
                    $cityId = $get('city_id');
                    if (! $cityId) {
                        return [];
                    }

                    return \App\Models\Center::where('city_id', $cityId)
                        ->whereHas('associations', fn ($q) => $q->where('associations.id', Auth::user()->association_id))
                        ->pluck('name', 'id');
                }),

            Map::make('location')
                ->label(__('order.location'))
                ->mapControls([
                    'mapTypeControl' => true,
                    'scaleControl' => true,
                    'streetViewControl' => true,
                    'rotateControl' => true,
                    'fullscreenControl' => true,
                    'searchBoxControl' => false,
                    'zoomControl' => true,
                ])
                ->height(fn () => '400px')
                ->defaultZoom(8)
                // default location to riyadh
                ->defaultLocation([24.7136, 46.6753])
                ->autocomplete('address')
                ->clickable(true)
                ->reactive()
                ->afterStateUpdated(function (Set $set, $state) {
                    if (is_array($state) && isset($state['lat']) && isset($state['lng'])) {
                        $set('lat', $state['lat']);
                        $set('lng', $state['lng']);
                    }
                })
                ->afterStateHydrated(function (Set $set, $state, $record) {
                    if ($record && $record->lat && $record->lng) {
                        $set('location', [
                            'lat' => (float) $record->lat,
                            'lng' => (float) $record->lng,
                        ]);
                    }
                })
                ->columnSpanFull(),

            Forms\Components\Hidden::make('lat'),
            Forms\Components\Hidden::make('lng'),

            Forms\Components\TextInput::make('number_of_families')
                ->label(__('order.number_of_families'))
                ->required()
                ->numeric()
                ->minValue(1),
        ];
    }

    /**
     * Get the water source information form fields
     */
    public static function getWaterSourceInformationFields(): array
    {
        return [
            Forms\Components\Select::make('water_source')
                ->label(__('order.water_source'))
                ->required()
                ->multiple()
                ->options(collect(Order::getWaterSources())->mapWithKeys(fn ($value, $key) => [$key => __($value)]))
                ->helperText(__('order.water_source_helper')),

            Forms\Components\TextInput::make('water_distance')
                ->label(__('order.water_distance'))
                ->required()
                ->numeric()
                ->step(0.01)
                ->minValue(0)
                ->suffix(__('order.km_suffix')),
        ];
    }

    /**
     * Get the project details form fields
     */
    public static function getProjectDetailsFields(): array
    {
        return [
            Forms\Components\Select::make('development_impacts')
                ->label(__('order.development_impacts'))
                ->multiple()
                ->relationship(
                    'developmentImpacts',
                    'name',
                    fn (Builder $query) => $query->where('type', \App\Models\SekayaValue::TYPE_ORDER_IMPACT_REASONS)
                )
                ->preload()
                ->searchable()
                ->required(),

            Forms\Components\Textarea::make('order_justifications')
                ->label(__('order.order_justifications'))
                ->required()
                ->rows(3)
                ->maxLength(1000),

            Forms\Components\Textarea::make('order_description')
                ->label(__('order.order_description'))
                ->required()
                ->rows(3)
                ->maxLength(1000)
                ->helperText(__('order.order_description_helper')),
        ];
    }

    /**
     * Get the required files form fields
     */
    public static function getRequiredFilesFields(Get $get): array
    {
        $type = $get('type');
        if (! $type) {
            return [
                Forms\Components\Placeholder::make('select_type_first')
                    ->label('')
                    ->content(__('order.select_type_first')),
            ];
        }

        $requirements = Order::getTypeFileRequirements()[$type] ?? [];

        if (empty($requirements)) {
            return [
                Forms\Components\Placeholder::make('no_files_required')
                    ->label('')
                    ->content(__('order.no_files_required')),
            ];
        }

        $fields = [];

        if ($type === ORDER::TYPE_STATION) {
            // show a guidance link for station type with specific URL
            $fields[] = Forms\Components\Placeholder::make('station_guide_file_helper')
                ->label(__('order.station_guide_file_helper'))
                ->content(new \Illuminate\Support\HtmlString(
                    ' <a href="'.'https://sekaya-prod-api.fra1.digitaloceanspaces.com/sekaya-templates/%D8%A7%D9%84%D8%A7%D8%B4%D8%AA%D8%B1%D8%A7%D8%B7%D8%A7%D8%AA%20%D9%88%20%D8%A7%D9%84%D9%85%D9%88%D8%A7%D8%B5%D9%81%D8%A7%D8%AA%20%D9%84%D8%AA%D9%82%D8%AF%D9%8A%D9%85%20%20%D9%85%D8%B4%D8%B1%D9%88%D8%B9%20%D9%85%D8%AD%D8%B7%D8%A9%20%D8%AA%D9%86%D9%82%D9%8A%D8%A9%20%D9%85%D9%8A%D8%A7%D9%87%202025.pdf'.'" target="_blank" class="text-primary-600 hover:text-primary-500 underline">'.__('common.click_to_download').'</a>'
                )
                );
        }

        foreach ($requirements as $fileKey => $fileData) {
            $field = SpatieMediaLibraryFileUpload::make($fileKey)
                ->label(__($fileData['label']))
                ->visibility('private')
                ->required()
                ->directory('orders')
                ->collection('order_files')
                ->acceptedFileTypes([
                    'application/pdf',
                    'image/jpeg',
                    'image/png',
                    'image/jpg',
                ])
                ->customProperties([
                    'file_title' => __($fileData['label']),
                ])
                ->downloadable()
                ->maxSize(10240); // 10MB

            // Add guidance link if file_url is provided
            if (! empty($fileData['file_url'])) {
                $field->helperText(
                    new \Illuminate\Support\HtmlString(
                        __('order.file_guidance_available').' <a href="'.$fileData['file_url'].'" target="_blank" class="text-primary-600 hover:text-primary-500 underline">'.__('order.download_guidance').'</a>'
                    )
                );
            }

            $fields[] = $field;
        }

        return $fields;
    }
}
