<?php

namespace App\Filament\Admin\Resources\Associations\Forms;

use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Facades\Filament;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Builder;

class AssociationForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                Hidden::make('org_id')
                    ->default(fn () => Filament::getTenant()?->id),

                Section::make(__('association.association_information'))
                    ->description(__('association.association_information_description'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('logo')
                            ->label(__('association.logo'))
                            ->collection('logo')
                            ->acceptedFileTypes(['image/jpeg', 'image/png'])
                            ->maxSize(2048)
                            ->downloadable()
                            ->required(),

                        TextInput::make('name')
                            ->label(__('association.name'))
                            ->placeholder(__('association.name_placeholder'))
                            ->maxLength(255)
                            ->required(),

                        TextInput::make('license_number')
                            ->label(__('association.license_number'))
                            ->placeholder(__('association.license_number_placeholder'))
                            ->maxLength(255)
                            ->rules(['regex:/^[1-9][0-9]*$/'])
                            ->validationMessages([
                                'regex' => __('association.license_number_no_leading_zero'),
                            ])
                            ->required(),

                        DatePicker::make('license_expiration_date')
                            ->label(__('association.license_expiration_date'))
                            ->required()
                            ->after('today'),

                        Select::make('user_id')
                            ->label(__('association.representative'))
                            ->relationship('representative', 'name')
                            ->searchable()
                            ->preload()
                            ->required(),
                    ])
                    ->columns(2),

                Section::make(__('association.national_address'))
                    ->description(__('association.national_address_description'))
                    ->schema([
                        TextInput::make('city')
                            ->label(__('association.city'))
                            ->placeholder(__('association.city_placeholder')),

                        TextInput::make('postal_code')
                            ->label(__('association.postal_code'))
                            ->placeholder(__('association.postal_code_placeholder')),

                        TextInput::make('district')
                            ->label(__('association.neighborhood'))
                            ->placeholder(__('association.neighborhood_placeholder')),

                        TextInput::make('building_number')
                            ->label(__('association.building_number'))
                            ->placeholder(__('association.building_number_placeholder')),

                        TextInput::make('street')
                            ->label(__('association.street'))
                            ->placeholder(__('association.street_placeholder')),

                        TextInput::make('secondary_number')
                            ->label(__('association.branch_number'))
                            ->placeholder(__('association.branch_number_placeholder')),
                    ])
                    ->columns(2),

                Section::make(__('association.geographic_scope'))
                    ->description(__('association.geographic_scope_description'))
                    ->schema(static::getLocationInformationFields())
                    ->columns(2),

                Section::make(__('association.banking_details'))
                    ->description(__('association.banking_details_description'))
                    ->schema([
                        TextInput::make('iban')
                            ->label(__('association.iban'))
                            ->placeholder(__('association.iban_placeholder'))
                            ->maxLength(255),

                        TextInput::make('bank_name')
                            ->label(__('association.bank_name'))
                            ->placeholder(__('association.bank_name_placeholder'))
                            ->maxLength(255),

                        TextInput::make('account_holder_name')
                            ->label(__('association.account_holder_name'))
                            ->placeholder(__('association.account_holder_name_placeholder'))
                            ->maxLength(255),
                    ])
                    ->columns(2),

                Section::make(__('association.documents'))
                    ->description(__('association.documents_description'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('authorization_letter')
                            ->label(__('association.authorization_letter_upload'))
                            ->collection('authorization_letter')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable()
                            ->required(),

                        SpatieMediaLibraryFileUpload::make('license_certificate')
                            ->label(__('association.license_upload'))
                            ->collection('license_certificate')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable()
                            ->required(),

                        SpatieMediaLibraryFileUpload::make('iban_certificate')
                            ->label(__('association.iban_certificate'))
                            ->collection('iban_certificate')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable(),

                        SpatieMediaLibraryFileUpload::make('national_address_certificate')
                            ->label(__('association.national_address_certificate'))
                            ->collection('national_address_certificate')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable(),

                        SpatieMediaLibraryFileUpload::make('governance_certificate')
                            ->label(__('association.governance_certificate'))
                            ->collection('governance_certificate')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable(),

                        SpatieMediaLibraryFileUpload::make('financial_reports')
                            ->label(__('association.financial_reports'))
                            ->collection('financial_reports')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable(),

                        SpatieMediaLibraryFileUpload::make('basic_bylaws')
                            ->label(__('association.basic_bylaws'))
                            ->collection('basic_bylaws')
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(5120)
                            ->downloadable()
                            ->required(),
                    ])
                    ->columns(2),

                Section::make(__('association.verification_lock_section'))
                    ->description(__('association.verification_lock_section_description'))
                    ->schema([
                        Toggle::make('is_verified')
                            ->label(__('association.is_verified'))
                            ->helperText(__('association.is_verified_helper'))
                            ->default(false),

                        Toggle::make('is_locked')
                            ->label(__('association.is_locked'))
                            ->helperText(__('association.is_locked_helper'))
                            ->default(false),
                    ])
                    ->columns(2),
            ]);
    }

    /**
     * Get the location information form fields
     */
    public static function getLocationInformationFields(): array
    {
        return [
            Select::make('states')
                ->label(__('association.states'))
                ->relationship('states', 'name')
                ->multiple()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set) {
                    $set('cities', []);
                    $set('centers', []);
                }),

            Select::make('cities')
                ->label(__('association.cities'))
                ->relationship(
                    'cities',
                    'name',
                    fn (Builder $query, Get $get) => $query->whereIn('state_id', $get('states')),
                )
                ->multiple()
                ->searchable()
                ->preload()
                ->live()
                ->afterStateUpdated(function (Set $set) {
                    $set('centers', []);
                }),

            Select::make('centers')
                ->label(__('association.centers'))
                ->relationship(
                    'centers',
                    'name',
                    fn (Builder $query, Get $get) => $query->whereIn('city_id', $get('cities')),
                )
                ->multiple()
                ->searchable()
                ->preload()
                ->live(),

            Map::make('location')
                ->label(__('association.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)) {
                        $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,
                        ]);
                    }
                }),

            Hidden::make('lat'),
            Hidden::make('lng'),
        ];
    }
}
