<?php

use App\Mail\TestEmail;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\Rule;
use Livewire\Volt\Component;

new class extends Component {
    public string $full_name = '';
    public string $email = '';
    public string $preferred_language = 'ar';

    /**
     * Mount the component.
     */
    public function mount(): void
    {
        $user = Auth::user();
        $this->full_name = $user->full_name;
        $this->email = $user->email;
        $this->preferred_language = $user->preferred_language ?? 'ar';
    }

    /**
     * Update the profile information for the currently authenticated user.
     */
    public function updateProfileInformation(): void
    {
        $user = Auth::user();

        $validated = $this->validate([
            'full_name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'lowercase',
                'email',
                'max:255',
                Rule::unique(User::class)->ignore($user->id),
            ],
            'preferred_language' => ['required', 'in:ar,en'],
        ]);

        $user->fill($validated);

        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();

        $this->dispatch('profile-updated', name: $user->full_name);
    }

    /**
     * Send an email verification notification to the current user.
     */
    public function resendVerificationNotification(): void
    {
        $user = Auth::user();

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

            return;
        }

        $user->sendEmailVerificationNotification();

        Session::flash('status', 'verification-link-sent');
    }

    /**
     * Send a test email to verify mail configuration (admin only).
     */
    public function sendTestEmail(): void
    {
        if (! Auth::user()->isAdmin()) {
            return;
        }

        try {
            $locale = Auth::user()->preferred_language ?? 'en';
            Mail::to(Auth::user())->send(new TestEmail($locale));
            Session::flash('test-email-sent', true);
        } catch (\Exception $e) {
            \Log::error('Test email failed: ' . $e->getMessage(), [
                'exception' => get_class($e),
                'trace' => $e->getTraceAsString(),
            ]);
            Session::flash('test-email-failed', true);
        }
    }
}; ?>

<section class="w-full">
    @include('partials.settings-heading')

    <x-settings.layout :heading="__('navigation.profile_heading')" :subheading="__('navigation.profile_subheading')">
        <form wire:submit="updateProfileInformation" class="my-6 w-full space-y-6">
            <flux:input wire:model="full_name" :label="__('Full Name')" type="text" required autofocus autocomplete="name" />

            <div>
                <flux:input wire:model="email" :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 !text-green-600">
                                {{ __('A new verification link has been sent to your email address.') }}
                            </flux:text>
                        @endif
                    </div>
                @endif
            </div>

            <flux:select wire:model="preferred_language" :label="__('Preferred Language')">
                <option value="ar">{{ __('Arabic') }}</option>
                <option value="en">{{ __('English') }}</option>
            </flux:select>

            <div class="flex items-center gap-4">
                <div class="flex items-center justify-end">
                    <flux:button variant="primary" type="submit" class="w-full" data-test="update-profile-button">
                        {{ __('Save') }}
                    </flux:button>
                </div>

                <x-action-message class="me-3" on="profile-updated">
                    {{ __('Saved.') }}
                </x-action-message>
            </div>
        </form>

        @if (auth()->user()->isAdmin())
            <flux:separator class="my-6" />

            <div>
                <flux:heading size="lg">{{ __('Email Configuration') }}</flux:heading>
                <flux:text class="mt-1 text-sm text-zinc-500">
                    {{ __('Verify your email configuration is working correctly.') }}
                </flux:text>

                @if (session('test-email-sent'))
                    <div class="mt-4">
                        <flux:callout variant="success" icon="check-circle">
                            {{ __('admin.test_email_sent') }}
                        </flux:callout>
                    </div>
                @endif

                @if (session('test-email-failed'))
                    <div class="mt-4">
                        <flux:callout variant="danger" icon="exclamation-triangle">
                            {{ __('admin.test_email_failed') }}
                        </flux:callout>
                    </div>
                @endif

                <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                    <div>
                        <flux:text class="text-sm font-medium text-zinc-600">
                            {{ __('admin.sender_name') }}
                        </flux:text>
                        <flux:text class="mt-1 font-medium text-zinc-900">
                            {{ config('mail.from.name') }}
                        </flux:text>
                    </div>
                    <div>
                        <flux:text class="text-sm font-medium text-zinc-600">
                            {{ __('admin.sender_email') }}
                        </flux:text>
                        <flux:text class="mt-1 font-medium text-zinc-900">
                            {{ config('mail.from.address') }}
                        </flux:text>
                    </div>
                </div>

                <div class="mt-4">
                    <flux:button wire:click="sendTestEmail" wire:loading.attr="disabled">
                        <span wire:loading.remove wire:target="sendTestEmail">
                            {{ __('admin.send_test_email') }}
                        </span>
                        <span wire:loading wire:target="sendTestEmail">
                            {{ __('admin.sending') }}
                        </span>
                    </flux:button>
                </div>
            </div>
        @endif

        <livewire:settings.delete-user-form />
    </x-settings.layout>
</section>
