<?php

namespace App\Filament\AssociationAdmin\Widgets;

use App\Models\Association;
use App\Services\OtpService;
use Cheesegrits\FilamentGoogleMaps\Fields\Map;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Notifications\Notification;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Ysfkaya\FilamentPhoneInput\Forms\PhoneInput;
use Ysfkaya\FilamentPhoneInput\PhoneInputNumberType;

class AssociationMultipleForms extends Widget implements HasForms
{
    use InteractsWithForms;

    protected static string $view = 'filament.association-admin.widgets.association-multiple-forms';

    protected int|string|array $columnSpan = 6;

    public $activeForm = 'associationInfo';

    protected $listeners = ['checkUnsavedChanges' => 'handleSectionChange', 'verificationSuccess' => 'handleVerificationSuccess'];

    public ?Association $association = null;

    public array $data = [];

    public bool $isFormDirty = false;

    public ?string $pendingSection = null;

    public ?string $originalEmail = null;

    public ?string $originalPhone = null;

    public function updateSection(string $section): void
    {
        $this->activeForm = $section;
        $this->isFormDirty = false;
        $this->pendingSection = null;
        $this->reloadFormData();
    }

    public function handleSectionChange(string $section): void
    {
        // If form has unsaved changes, show confirmation modal
        if ($this->isFormDirty) {
            $this->pendingSection = $section;
            $this->dispatch('open-modal', id: 'confirm-discard-changes');
        } else {
            // No unsaved changes, switch directly
            $this->updateSection($section);
            $this->dispatch('sectionChanged', $section);
        }
    }

    public function confirmDiscardChanges(): void
    {
        if ($this->pendingSection) {
            $section = $this->pendingSection;
            $this->updateSection($section);
            $this->dispatch('sectionChanged', $section);
        }
        $this->dispatch('close-modal', id: 'confirm-discard-changes');
    }

    public function cancelDiscardChanges(): void
    {
        $this->pendingSection = null;
        $this->dispatch('close-modal', id: 'confirm-discard-changes');
    }

    public function handleVerificationSuccess(string $type): void
    {
        // Refresh association data
        if ($this->association) {
            $this->association->refresh();

            // Update original values
            if ($type === 'email') {
                $this->originalEmail = $this->association->email;
            } else {
                $this->originalPhone = $this->association->phone_number;
            }
        }
    }

    public function reloadFormData(): void
    {
        // Refresh the association data from database
        if ($this->association) {
            $this->association->refresh();

            // Prepare data with relationships
            $associationData = $this->association->toArray();

            // Add relationship data for the form
            $associationData['states'] = $this->association->states()->pluck('states.id')->toArray();
            $associationData['cities'] = $this->association->cities()->pluck('cities.id')->toArray();
            $associationData['centers'] = $this->association->centers()->pluck('centers.id')->toArray();
            $associationData['residentialGatherings'] = $this->association->residentialGatherings()->pluck('residential_gatherings.id')->toArray();

            $associationData['location'] = [
                'lat' => (float) $this->association->lat,
                'lng' => (float) $this->association->lng,
            ];

            // print a log of location fields
            Log::info("Association location fields, lat: {$associationData['location']['lat']}, lng: {$associationData['location']['lng']}");

            // Refill the form with fresh data
            $this->form->fill($associationData);
        }
    }

    public function mount(): void
    {
        $user = Auth::user();
        $this->association = $user ? $user->association : null;

        // Fill form with existing data
        if ($this->association) {
            // Store original values for comparison
            $this->originalEmail = $this->association->email;
            $this->originalPhone = $this->association->phone_number;

            // Load the basic association data plus relationship IDs
            $associationData = $this->association->toArray();

            // Add relationship data for the form
            $associationData['states'] = $this->association->states()->pluck('states.id')->toArray();
            $associationData['cities'] = $this->association->cities()->pluck('cities.id')->toArray();
            $associationData['centers'] = $this->association->centers()->pluck('centers.id')->toArray();
            $associationData['residentialGatherings'] = $this->association->residentialGatherings()->pluck('residential_gatherings.id')->toArray();

            // print a log of location fields
            // Log::info("Association location fields, lat: {$associationData['location']['lat']}, lng: {$associationData['location']['lng']}");
            $associationData['location'] = [
                'lat' => (float) $this->association->lat,
                'lng' => (float) $this->association->lng,
            ];
            $this->form->fill($associationData);
        }
    }

    public function form(Form $form): Form
    {
        return $form
            ->model($this->association)
            ->schema($this->getFormSchema())
            ->statePath('data');
    }

    /**
     * Track any changes to the form data
     */
    public function updated($propertyName): void
    {
        // If any data property is updated, mark form as dirty
        if (str_starts_with($propertyName, 'data.')) {
            $this->isFormDirty = true;
        }
    }

    public function getFormSchema(): array
    {
        $isLocked = $this->association?->is_locked ?? false;

        return match ($this->activeForm) {
            'associationInfo' => [
                SpatieMediaLibraryFileUpload::make('logo')
                    ->label(__('association.logo'))
                    ->collection('logo')
                    ->acceptedFileTypes(['image/jpeg', 'image/png'])
                    ->maxSize(2048)
                    ->downloadable()
                    ->disabled($isLocked),

                TextInput::make('name')
                    ->label(__('association.name'))
                    ->placeholder(__('association.name_placeholder'))
                    ->disabled($isLocked),

                Grid::make()->columns(2)->schema([
                    TextInput::make('license_number')
                        ->label(__('association.license_number'))
                        ->placeholder(__('association.license_number_placeholder'))
                        ->rules(['regex:/^[1-9][0-9]*$/'])
                        ->validationMessages([
                            'regex' => __('association.license_number_no_leading_zero'),
                        ])
                        ->disabled($isLocked),

                    DatePicker::make('license_expiration_date')
                        ->label(__('association.license_expiration_date'))
                        ->placeholder(__('association.license_expiration_date'))
                        ->disabled($isLocked),
                ]),

                TextInput::make('representative_full_name')
                    ->label(__('association.representative'))
                    ->placeholder(__('association.representative_placeholder'))
                    ->disabled($isLocked),

                TextInput::make('representative_position')
                    ->label(__('association.position'))
                    ->placeholder(__('association.position_placeholder'))
                    ->disabled($isLocked),
            ],
            'contactInfo' => [
                PhoneInput::make('phone_number')
                    ->label(__('association.phone_number'))
                    ->defaultCountry('SA')
                    ->onlyCountries(['sa'])
                    ->validateFor('SA')
                    ->displayNumberFormat(PhoneInputNumberType::NATIONAL)
                    ->inputNumberFormat(PhoneInputNumberType::E164)
                    ->separateDialCode(true)
                    ->formatAsYouType()
                    ->disallowDropdown()
                    ->extraAttributes([
                        'dir' => 'ltr',
                        'style' => 'direction: ltr; text-align: left;',
                    ])
                    ->unique(ignoreRecord: true)
                    ->disabled($isLocked)
                    ->live(onBlur: true)
                    ->afterStateUpdated(function ($state) {
                        // Mark as unverified if phone changed
                        if ($state !== $this->originalPhone && $this->association) {
                            $this->association->update([
                                'phone_verified' => false,
                                'phone_verified_at' => null,
                            ]);
                            $this->association->refresh();
                        }
                    })
                    ->suffixAction(
                        Action::make('verify_phone')
                            ->label(fn () => $this->association?->phone_verified
                                ? __('association.verified')
                                : __('association.verify'))
                            ->icon(fn () => $this->association?->phone_verified
                                ? 'heroicon-o-check-circle'
                                : 'heroicon-o-shield-check')
                            ->color(fn () => $this->association?->phone_verified ? 'success' : 'warning')
                            ->disabled(fn () => $this->association?->phone_verified || $isLocked)
                            ->action(function ($state) {
                                if (! $state) {
                                    Notification::make()
                                        ->title(__('association.phone_required'))
                                        ->warning()
                                        ->send();

                                    return;
                                }

                                // Send OTP
                                $otpService = app(OtpService::class);
                                try {
                                    $normalizedPhone = (new \Propaganistas\LaravelPhone\PhoneNumber($state, 'SA'))->formatE164();
                                    $otpService->sendOtp(['phone' => $normalizedPhone]);

                                    // Open verification modal
                                    $this->dispatch('openVerificationModal', identifier: $state, type: 'phone');

                                    Notification::make()
                                        ->title(__('association.otp_sent'))
                                        ->success()
                                        ->send();
                                } catch (\Exception $e) {
                                    Notification::make()
                                        ->title(__('association.otp_send_failed'))
                                        ->danger()
                                        ->send();
                                }
                            })
                    ),

                Placeholder::make('phone_verification_status')
                    ->label('')
                    ->content(function () {
                        if (! $this->association) {
                            return '';
                        }

                        if ($this->association->phone_verified) {
                            return view('filament.components.verification-badge', [
                                'verified' => true,
                                'message' => __('association.phone_verified_at', [
                                    'date' => $this->association->phone_verified_at?->diffForHumans(),
                                ]),
                            ]);
                        }

                        return view('filament.components.verification-badge', [
                            'verified' => false,
                            'message' => __('association.phone_not_verified'),
                        ]);
                    })
                    ->visible(fn () => ! $isLocked),

                TextInput::make('email')
                    ->label(__('association.email'))
                    ->placeholder(__('association.email_placeholder'))
                    ->email()
                    ->suffixIcon('heroicon-m-envelope')
                    ->disabled($isLocked)
                    ->live(onBlur: true)
                    ->afterStateUpdated(function ($state) {
                        // Mark as unverified if email changed
                        if ($state !== $this->originalEmail && $this->association) {
                            $this->association->update([
                                'email_verified' => false,
                                'email_verified_at' => null,
                            ]);
                            $this->association->refresh();
                        }
                    })
                    ->suffixAction(
                        Action::make('verify_email')
                            ->label(fn () => $this->association?->email_verified
                                ? __('association.verified')
                                : __('association.verify'))
                            ->icon(fn () => $this->association?->email_verified
                                ? 'heroicon-o-check-circle'
                                : 'heroicon-o-shield-check')
                            ->color(fn () => $this->association?->email_verified ? 'success' : 'warning')
                            ->disabled(fn () => $this->association?->email_verified || $isLocked)
                            ->action(function ($state) {
                                if (! $state) {
                                    Notification::make()
                                        ->title(__('association.email_required'))
                                        ->warning()
                                        ->send();

                                    return;
                                }

                                // Send OTP
                                $otpService = app(OtpService::class);
                                try {
                                    $otpService->sendOtp(['email' => $state]);

                                    // Open verification modal
                                    $this->dispatch('openVerificationModal', identifier: $state, type: 'email');

                                    Notification::make()
                                        ->title(__('association.otp_sent'))
                                        ->success()
                                        ->send();
                                } catch (\Exception $e) {
                                    Notification::make()
                                        ->title(__('association.otp_send_failed'))
                                        ->danger()
                                        ->send();
                                }
                            })
                    ),

                Placeholder::make('email_verification_status')
                    ->label('')
                    ->content(function () {
                        if (! $this->association) {
                            return '';
                        }

                        if ($this->association->email_verified) {
                            return view('filament.components.verification-badge', [
                                'verified' => true,
                                'message' => __('association.email_verified_at', [
                                    'date' => $this->association->email_verified_at?->diffForHumans(),
                                ]),
                            ]);
                        }

                        return view('filament.components.verification-badge', [
                            'verified' => false,
                            'message' => __('association.email_not_verified'),
                        ]);
                    })
                    ->visible(fn () => ! $isLocked),
            ],
            'nationalAddress' => [
                Grid::make(1)->schema([
                    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])
                        ->clickable(true)
                        ->autocomplete('address')
                        ->reactive()
                        ->disabled($isLocked)
                        ->afterStateUpdated(function (Set $set, $state) {
                            Log::info('Map afterStateUpdated called with state: '.json_encode($state));
                            if (is_array($state) && isset($state['lat']) && isset($state['lng'])) {
                                $set('lat', $state['lat']);
                                $set('lng', $state['lng']);
                                Log::info("Map updated - Lat: {$state['lat']}, Lng: {$state['lng']}");
                            }
                        }),

                    TextInput::make('lat')
                        ->numeric()
                        ->reactive()
                        ->hidden()
                        ->afterStateUpdated(function ($state, Get $get, Set $set) {
                            Log::info('Lat field updated to: '.($state ?? 'null'));
                            $lng = $get('lng');
                            if ($state && $lng) {
                                $set('location', [
                                    'lat' => (float) $state,
                                    'lng' => (float) $lng,
                                ]);
                                Log::info("Location updated from lat field - Lat: {$state}, Lng: {$lng}");
                            }
                        }),

                    TextInput::make('lng')
                        ->numeric()
                        ->reactive()
                        ->hidden()
                        ->afterStateUpdated(function ($state, Get $get, Set $set) {
                            Log::info('Lng field updated to: '.($state ?? 'null'));
                            $lat = $get('lat');
                            if ($state && $lat) {
                                $set('location', [
                                    'lat' => (float) $lat,
                                    'lng' => (float) $state,
                                ]);
                                Log::info("Location updated from lng field - Lat: {$lat}, Lng: {$state}");
                            }
                        }),

                    Grid::make(2)->schema([
                        TextInput::make('city')
                            ->label(__('association.city'))
                            ->placeholder(__('association.city_placeholder'))
                            ->disabled($isLocked),

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

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

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

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

                        TextInput::make('branch_number')
                            ->label(__('association.branch_number'))
                            ->placeholder(__('association.branch_number_placeholder'))
                            ->disabled($isLocked),
                    ]),
                ]),
            ],
            'geographicScope' => [
                Select::make('states')
                    ->label(__('association.states'))
                    ->relationship('states', 'name')
                    ->multiple()
                    ->searchable()
                    ->preload()
                    ->live()
                    ->disabled($isLocked)
                    ->afterStateUpdated(function (Set $set) {
                        $set('cities', []);
                        $set('centers', []);
                    })
                    ->options(function (Get $get) {
                        return \App\Models\State::pluck('name', 'id');
                    }),

                Select::make('cities')
                    ->label(__('association.cities'))
                    ->relationship('cities', 'name')
                    ->multiple()
                    ->searchable()
                    ->getSearchResultsUsing(
                        fn (string $search, Get $get): array => \App\Models\City::whereIn('state_id', $get('states'))
                            ->where('name', 'like', "%{$search}%")
                            ->pluck('name', 'id')
                            ->toArray()
                    )
                    ->preload()
                    ->live()
                    ->disabled($isLocked)
                    ->afterStateUpdated(function (Set $set, $state, Get $get) {
                        $set('centers', []);

                        // Auto-update map location when cities are selected
                        if ($state && ! empty($state)) {
                            $locationService = app(\App\Services\LocationCoordinatesService::class);
                            $coordinates = $locationService->getCenterCoordinatesForCities($state);

                            if ($coordinates) {
                                $set('location', $coordinates);
                                $set('lat', $coordinates['lat']);
                                $set('lng', $coordinates['lng']);
                            }
                        }
                    })
                    ->options(function (Get $get) {
                        $stateIds = $get('states');
                        if (! $stateIds || empty($stateIds)) {
                            return [];
                        }

                        return \App\Models\City::whereIn('state_id', $stateIds)
                            ->pluck('name', 'id');
                    }),

                Select::make('centers')
                    ->label(__('association.centers'))
                    ->relationship('centers', 'name')
                    ->multiple()
                    ->searchable()
                    ->getSearchResultsUsing(
                        fn (string $search, Get $get): array => \App\Models\Center::whereIn('city_id', $get('cities'))
                            ->where('name', 'like', "%{$search}%")
                            ->pluck('name', 'id')
                            ->toArray()
                    )
                    ->preload()
                    ->live()
                    ->disabled($isLocked)
                    ->options(function (Get $get) {
                        $cityIds = $get('cities');
                        if (! $cityIds || empty($cityIds)) {
                            return [];
                        }

                        return \App\Models\Center::whereIn('city_id', $cityIds)
                            ->pluck('name', 'id');
                    })
                    ->afterStateUpdated(function (Set $set, $state, Get $get) {
                        // Auto-populate residential gatherings based on selected centers
                        if (is_array($state) && ! empty($state)) {
                            $residentialGatherings = \App\Models\ResidentialGathering::whereIn('center_id', $state)
                                ->pluck('id')
                                ->toArray();
                            $set('residentialGatherings', $residentialGatherings);
                        } else {
                            $set('residentialGatherings', []);
                        }
                    }),

                Select::make('residentialGatherings')
                    ->label(__('order.residential_gatherings'))
                    ->relationship('residentialGatherings', 'name')
                    ->multiple()
                    ->searchable()
                    ->disabled()
                    ->dehydrated()
                    ->getSearchResultsUsing(function (string $search, Get $get): array {
                        $centerIds = $get('centers');
                        if (empty($centerIds)) {
                            return [];
                        }

                        return \App\Models\ResidentialGathering::whereIn('center_id', $centerIds)
                            ->where('name', 'like', "%{$search}%")
                            ->with('center')
                            ->get()
                            ->mapWithKeys(function ($rg) {
                                return [$rg->id => $rg->name.' ('.$rg->center->name.')'];
                            })
                            ->toArray();
                    })
                    ->getOptionLabelFromRecordUsing(fn ($record) => $record->name.' ('.$record->center->name.')')
                    ->preload()
                    ->options(function (Get $get) {
                        $centerIds = $get('centers');
                        if (empty($centerIds)) {
                            return [];
                        }

                        return \App\Models\ResidentialGathering::whereIn('center_id', $centerIds)
                            ->with('center')
                            ->get()
                            ->mapWithKeys(function ($rg) {
                                return [$rg->id => $rg->name.' ('.$rg->center->name.')'];
                            })
                            ->toArray();
                    }),
            ],
            'bankDetails' => [
                TextInput::make('iban')
                    ->label(__('association.iban'))
                    ->placeholder(__('association.iban_placeholder'))
                    ->disabled($isLocked),

                TextInput::make('bank_name')
                    ->label(__('association.bank_name'))
                    ->placeholder(__('association.bank_name_placeholder'))
                    ->disabled($isLocked),

                TextInput::make('account_holder_name')
                    ->label(__('association.account_holder_name'))
                    ->placeholder(__('association.account_holder_name_placeholder'))
                    ->disabled($isLocked),

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

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

                SpatieMediaLibraryFileUpload::make('iban_certificate')
                    ->label(__('association.iban_certificate'))
                    ->collection('iban_certificate')
                    ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                    ->maxSize(5120)
                    ->downloadable()
                    ->disabled($isLocked)
                    ->visible($this->association?->type === \App\Enums\AssociationType::ASSOCIATION),

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

                SpatieMediaLibraryFileUpload::make('governance_certificate')
                    ->label(__('association.governance_certificate'))
                    ->collection('governance_certificate')
                    ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                    ->maxSize(5120)
                    ->downloadable()
                    ->disabled($isLocked)
                    ->visible($this->association?->type === \App\Enums\AssociationType::ASSOCIATION),

                SpatieMediaLibraryFileUpload::make('financial_reports')
                    ->label(__('association.financial_reports'))
                    ->collection('financial_reports')
                    ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                    ->maxSize(5120)
                    ->downloadable()
                    ->disabled($isLocked)
                    ->visible($this->association?->type === \App\Enums\AssociationType::ASSOCIATION),

                SpatieMediaLibraryFileUpload::make('basic_bylaws')
                    ->label(__('association.basic_bylaws'))
                    ->collection('basic_bylaws')
                    ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                    ->maxSize(5120)
                    ->downloadable()
                    ->disabled($isLocked)
                    ->visible($this->association?->type === \App\Enums\AssociationType::ASSOCIATION),
            ],

            default => [],
        };
    }

    protected function getFormStatePath(): string
    {
        return 'data';
    }

    public function submit(): void
    {
        // Prevent submission if association is locked
        if ($this->association?->is_locked) {
            Notification::make()
                ->title(__('association.profile_locked_title'))
                ->body(__('association.profile_locked_message'))
                ->warning()
                ->send();

            return;
        }

        $data = $this->form->getState();

        if ($this->activeForm === 'associationInfo') {
            $this->association->update([
                'name' => $data['name'],
                'license_number' => $data['license_number'],
                'license_expiration_date' => $data['license_expiration_date'],
                'representative_full_name' => $data['representative_full_name'],
                'representative_position' => $data['representative_position'],
            ]);
        } elseif ($this->activeForm === 'contactInfo') {
            $this->association->update([
                'phone_number' => $data['phone_number'],
                'email' => $data['email'],
            ]);

            // Update original values after save
            $this->originalEmail = $data['email'];
            $this->originalPhone = $data['phone_number'];
        } elseif ($this->activeForm === 'nationalAddress') {
            Log::info('Submit nationalAddress - Full data: '.json_encode($data));
            Log::info('Submit nationalAddress - Lat: '.($data['location']['lat'] ?? 'null').', Lng: '.($data['location']['lng'] ?? 'null'));

            $this->association->update([
                'lat' => $data['location']['lat'] ?? null,
                'lng' => $data['location']['lng'] ?? null,
                'city' => $data['city'],
                'postal_code' => $data['postal_code'],
                'neighborhood' => $data['neighborhood'],
                'building_number' => $data['building_number'],
                'street' => $data['street'],
                'branch_number' => $data['branch_number'],
            ]);

            Log::info('After update - Association lat: '.$this->association->lat.', lng: '.$this->association->lng);
        } elseif ($this->activeForm === 'geographicScope') {
            // Sync the many-to-many relationships
            if (isset($data['states'])) {
                $this->association->states()->sync($data['states']);
            }
            if (isset($data['cities'])) {
                $this->association->cities()->sync($data['cities']);
            }
            if (isset($data['centers'])) {
                $this->association->centers()->sync($data['centers']);
            }
            if (isset($data['residentialGatherings'])) {
                $this->association->residentialGatherings()->sync($data['residentialGatherings']);
            }
        } elseif ($this->activeForm === 'bankDetails') {
            $this->association->update([
                'iban' => $data['iban'],
                'bank_name' => $data['bank_name'],
                'account_holder_name' => $data['account_holder_name'],
            ]);
            // File uploads are handled automatically by SpatieMediaLibraryFileUpload
        } elseif ($this->activeForm === 'documents') {
            // File uploads are handled automatically by SpatieMediaLibraryFileUpload
            // No database updates needed for file fields
        }

        // Refresh form data after saving to reflect any changes
        $this->reloadFormData();

        // Reset dirty flag after successful save
        $this->isFormDirty = false;

        // Show success notification
        Notification::make()
            ->title('تم الحفظ بنجاح')
            ->success()
            ->send();
    }
}
