<?php

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;

new class extends Component {
    public string $name = '';
    public string $email = '';

    public array $profile = [];

    public array $countries = [];
    public array $states = [];
    public array $currencies = [];

    public function mount()
    {
        $user = Auth::user();
        $profile = $user->profile;

        // User fields
        $this->name = $user->name;
        $this->email = $user->email;

        // Profile fields (editable subset)
        $this->profile = [
            'username' => $profile->username,
            'occupation' => $profile->occupation,
            'date_of_birth' => optional($profile->date_of_birth)->format('Y-m-d'),
            'gender' => $profile->gender,
            'phone' => $profile->phone,
            'dial_code' => $profile->dial_code,
            'country' => $profile->country,
            'state' => $profile->state,
            'city' => $profile->city,
            'zip_code' => $profile->zip_code,
            'address_1' => $profile->address_1,
            'address_2' => $profile->address_2,
        ];

        // Read-only system fields (for display only)
        $this->profile['client_id'] = $profile->client_id;
        $this->profile['currency'] = $profile->currency;

        // Load datasets
        $dialCodes = collect(json_decode(file_get_contents(resource_path('data/countries.json')), true));
        $statesData = collect(json_decode(file_get_contents(resource_path('data/countrystate.json')), true));
        $currencies = collect(json_decode(file_get_contents(resource_path('data/currencies.json')), true));

        // countries.json
        $this->countries = Cache::rememberForever('countries_json', function () {
            $countries = json_decode(file_get_contents(resource_path('data/countries.json')), true);
            $statesData = json_decode(file_get_contents(resource_path('data/countrystate.json')), true);

            return collect($countries)
                ->map(function ($country) use ($statesData) {
                    $match = collect($statesData)->firstWhere('code2', $country['code']);

                    return [
                        'name' => $country['name'],
                        'code' => $country['code'],
                        'emoji' => $country['emoji'] ?? '🏳️',
                        'dial_code' => $country['dial_code'],
                        'states' => $match['states'] ?? [],
                    ];
                })
                ->sortBy('name')
                ->values()
                ->toArray();
        });

        $this->currencies = Cache::rememberForever('currencies_json', function () {
            return collect(json_decode(file_get_contents(resource_path('data/currencies.json')), true))
                ->sortBy('name')
                ->values()
                ->toArray();
        });

        // Preload states if a country is already set
        if (!empty($this->profile['country'])) {
            $this->loadStates($this->profile['country']);
        }
    }

    /**
     * Called when the country is updated.
     */
    public function updatedProfileCountry($countryCode)
    {
        $this->loadStates($countryCode);
    }

    /**
     * Helper to load states and optionally set dial code.
     */
    private function loadStates(?string $countryCode)
    {
        if (!$countryCode) {
            $this->states = [];
            $this->profile['state'] = '';
            return;
        }

        $selected = collect($this->countries)->firstWhere('code', $countryCode);

        $this->states = $selected['states'] ?? [];

        // Only reset state if the current state is not in the new states list
        if (!in_array($this->profile['state'], array_column($this->states, 'name'))) {
            $this->profile['state'] = $this->states[0]['name'] ?? ''; // default to first state if available
        }

        // Auto-set dial code if not already set
        if (empty($this->profile['dial_code'])) {
            $this->profile['dial_code'] = $selected['dial_code'] ?? '';
        }
    }

    /**
     * Update user profile information.
     */
    public function updateProfileInformation()
    {
        $user = Auth::user();
        $user->update(['name' => $this->name]);

        $this->validate([
            'name' => 'required|string|max:255',
            'profile.username' => ['nullable', 'string', 'max:50', Rule::unique('profiles', 'username')->ignore($user->profile->id)],
            'profile.phone' => 'nullable|string',
            'profile.dial_code' => 'nullable|string',
            'profile.gender' => 'nullable|string',
            'profile.date_of_birth' => 'nullable|date',
            'profile.occupation' => 'nullable|string|max:255',
            'profile.country' => 'nullable|string',
            'profile.state' => 'nullable|string',
            'profile.city' => 'nullable|string|max:255',
            'profile.zip_code' => 'nullable|string|max:20',
            'profile.address_1' => 'nullable|string|max:255',
            'profile.address_2' => 'nullable|string|max:255',
        ]);

        $user->profile->update(
            collect($this->profile)
                ->only(['username', 'occupation', 'date_of_birth', 'gender', 'phone', 'dial_code', 'country', 'state', 'city', 'zip_code', 'address_1', 'address_2'])
                ->toArray(),
        );

        $this->dispatch('showToast', message: 'Profile Updated Successfully.', type: 'success');
    }

    public function resendVerificationNotification(): void
    {
        $user = Auth::user();

        if ($user->hasVerifiedEmail()) {
            $this->redirectIntended(default: route('user.dashboard', absolute: false));

            return;
        }

        $user->sendEmailVerificationNotification();
        Session::flash('status', 'verification-link-sent');
        $this->dispatch('showToast', message: 'verification-link-sent.', type: 'success');
    }
};
?>

<x-slot:title>
    {{ config('app.name') }} || Update Profile Information
</x-slot:title>
<section class="w-full py-5">
    <x-settings.layout :heading="__('Profile')" :subheading="__('Update your name and email address')">
        <form wire:submit="updateProfileInformation" class="my-6 w-full space-y-4">

            {{-- Basic Info --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <flux:input wire:model.defer="name" icon="user" label="Full Name" required />
                <div>
                    <flux:input wire:model="email" disabled :label="__('Email')" type="email" required
                        autocomplete="email" />

                    @if (auth()->user() instanceof \Illuminate\Contracts\Auth\MustVerifyEmail && !auth()->user()->hasVerifiedEmail())
                        <div>
                            <flux:text class="mt-4">
                                {{ __('Your email address is unverified.') }}

                                <flux:link class="text-sm cursor-pointer"
                                    wire:click.prevent="resendVerificationNotification">
                                    {{ __('Click here to re-send the verification email.') }}
                                </flux:link>
                            </flux:text>

                            @if (session('status') === 'verification-link-sent')
                                <flux:text class="mt-2 font-medium !dark:text-green-400 !text-green-600">
                                    {{ __('A new verification link has been sent to your email address.') }}
                                </flux:text>
                            @endif
                        </div>
                    @endif
                </div>
            </div>

            {{-- Profile Details --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <flux:input wire:model.defer="profile.username" icon="at-symbol" label="Username" />
                <flux:input wire:model.defer="profile.occupation" icon="briefcase" label="Occupation" />
                <flux:input wire:model.defer="profile.date_of_birth" icon="calendar-days" type="date"
                    label="Date of Birth" />

                <flux:select wire:model.defer="profile.gender" icon="user-group" label="Gender">
                    <flux:select.option value="">Select</flux:select.option>
                    <flux:select.option value="male">Male</flux:select.option>
                    <flux:select.option value="female">Female</flux:select.option>
                    <flux:select.option value="other">Other</flux:select.option>
                </flux:select>
            </div>

            {{-- Phone --}}
            <flux:input.group label="Phone Number">
                <flux:select wire:model.defer="profile.dial_code" class="max-w-fit">
                    <flux:select.option value="">Code</flux:select.option>
                    @foreach ($countries as $country)
                        <flux:select.option value="{{ $country['dial_code'] }}">
                            {{ $country['emoji'] }} {{ $country['dial_code'] }}
                        </flux:select.option>
                    @endforeach
                </flux:select>

                <flux:input wire:model.defer="profile.phone" icon="phone" placeholder="777-777-0000" />
            </flux:input.group>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                {{-- Country --}}
                <div>
                    <x-flux::select label="Country" placeholder="Select a country"
                        wire:model.live.debounce.500ms="profile.country">
                        @foreach ($countries as $c)
                            <flux:select.option value="{{ $c['code'] }}">
                                {{ $c['emoji'] }} {{ $c['name'] }}
                            </flux:select.option>
                        @endforeach
                    </x-flux::select>
                </div>

                {{-- State / Province --}}
                <div class="relative">
                    @if (!empty($states))
                        <x-flux::select label="State / Province" placeholder="Select a state"
                            wire:model.defer="profile.state" wire:loading.attr="disabled" wire:target="profile.country">
                            @foreach ($states as $s)
                                <flux:select.option value="{{ $s['name'] }}">
                                    {{ $s['name'] }}
                                </flux:select.option>
                            @endforeach
                        </x-flux::select>
                    @else
                        <x-flux::input label="State / Province" placeholder="Enter your state or province"
                            wire:model.defer="profile.state" wire:loading.attr="disabled"
                            wire:target="profile.country" />
                    @endif

                    <div wire:loading wire:target="profile.country" class="absolute top-1/2 right-3 -translate-y-1/2">
                        <svg class="animate-spin h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg"
                            fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z">
                            </path>
                        </svg>
                    </div>
                </div>
            </div>

            {{-- Address --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                {{-- City & Zip --}}
                <flux:input wire:model.defer="profile.city" icon="building-office" label="City" />
                <flux:input wire:model.defer="profile.zip_code" icon="map-pin" label="Zip Code" />
            </div>

            <flux:input wire:model.defer="profile.address_1" icon="home" label="Address Line 1" />
            <flux:input wire:model.defer="profile.address_2" icon="home-modern" label="Address Line 2" />

            {{-- Read-only system fields --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 opacity-70">
                <flux:input label="Client ID" icon="finger-print" :value="$profile['client_id'] ?? ''" disabled />
                <flux:input label="Currency" icon="currency-dollar" :value="$profile['currency'] ?? ''" disabled />
            </div>

            {{-- Save --}}
            <div class="pt-4">
                <x-button type="submit" icon="user" iconPosition="right" class="w-full">
                    {{ __('Update Profile') }}
                </x-button>

            </div>
        </form>


    </x-settings.layout>
</section>
