<?php

use App\Models\User;
use Illuminate\Validation\Rules\Password;
use Livewire\Features\SupportRedirects\Redirector;
use Illuminate\Support\Facades\{Auth, Hash};
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Title;
use Livewire\Component;
use Mary\Traits\Toast;

new #[Title('Profil')]
class extends Component {
    use Toast;

    public User $user;
    public string $firstname = '';
    public string $name = '';
    public string $email = '';
    public bool $newsletter = false;
    public string $password = '';
    public string $password_confirmation = '';
    public bool $rgpd = false;

    public function mount(): void
    {
        $this->user = Auth::user();
        $this->firstname = $this->user->firstname ?? '';
        $this->name = $this->user->name ?? '';
        $this->email = $this->user->email ?? '';
        $this->newsletter = (bool) ($this->user->newsletter ?? false);
    }

    public function generatePassword(): void
    {
        $generated = Str::password(14);
        $this->password = $generated;
        $this->password_confirmation = $generated;

        $this->info(__('Nouveau mot de passe généré.'), position: 'toast-bottom');
    }

    public function save(): void
    {
        $data = $this->validate([
            'firstname'  => ['required', 'string', 'max:255'],
            'name'       => ['required', 'string', 'max:255'],
            'email'      => ['required', 'email', Rule::unique('users')->ignore($this->user->id)],
            'newsletter' => ['boolean'],
            'rgpd'       => ['accepted'],
            'password' => [
                'nullable',
                'confirmed',
                Password::min(8)
                    ->mixedCase()   // Majuscules & Minuscules
                    ->numbers()     // Chiffres
                    ->symbols()     // Caractères spéciaux
                    ->uncompromised(), // Vérifie via "Have I Been Pwned" si le mot de passe a fuité sur le web !
            ],
        ], [
            'rgpd.accepted' => __('Vous devez accepter la politique de confidentialité pour enregistrer.')
        ]);

        if (empty($data['password'])) {
            unset($data['password']);
        } else {
            $data['password'] = Hash::make($data['password']);
        }

        unset($data['rgpd']);

        $this->user->update($data);

        $this->success(__('Profil mis à jour avec succès !'), redirectTo: route('home'));
    }

    public function cancel(): Redirector
    {
        return redirect()->route('home');
    }
}; ?>

<div class="min-h-screen py-8 bg-base-200/50">
    <div class="max-w-3xl mx-auto px-4">

        {{-- En-tête --}}
        <div class="text-center mb-8">
            <h1 class="text-3xl font-extrabold tracking-tight">@lang('Mon profil')</h1>
            <p class="text-sm text-base-content/70 mt-1">@lang('Gérez vos informations personnelles et vos préférences')</p>
        </div>

        {{-- Formulaire Carte --}}
        <x-card class="shadow-xl bg-base-100 border border-base-300">
            <x-form wire:submit="save" class="space-y-6">

                {{-- Section : Informations personnelles --}}
                <div class="space-y-4">
                    <div class="flex items-center gap-2 text-lg font-semibold border-b border-base-200 pb-2">
                        <x-icon name="o-user" class="w-5 h-5 text-primary" />
                        <span>@lang('Informations personnelles')</span>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <x-input
                            label="{{ __('Prénom') }}"
                            wire:model="firstname"
                            icon="o-user"
                            required
                        />
                        <x-input
                            label="{{ __('Nom') }}"
                            wire:model="name"
                            icon="o-user"
                            required
                        />
                    </div>

                    <x-input
                        label="{{ __('Email') }}"
                        wire:model="email"
                        icon="o-envelope"
                        type="email"
                        required
                    />
                </div>

                {{-- Section : Mot de passe --}}
                <div class="space-y-4 pt-4">
                    <div class="flex items-center gap-2 text-lg font-semibold border-b border-base-200 pb-2">
                        <x-icon name="o-lock-closed" class="w-5 h-5 text-primary" />
                        <span>@lang('Sécurité')</span>
                    </div>

                    <p class="text-xs text-base-content/60">
                        @lang('Laissez vide si vous ne souhaitez pas modifier votre mot de passe.')
                    </p>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <x-input
                            label="{{ __('Nouveau mot de passe') }}"
                            wire:model="password"
                            icon="o-key"
                            type="password"
                        />
                        <x-input
                            label="{{ __('Confirmer le mot de passe') }}"
                            wire:model="password_confirmation"
                            icon="o-key"
                            type="password"
                        />
                    </div>

                    <div class="flex items-center gap-3">
                        <x-button
                            label="{{ __('Générer un mot de passe sécurisé') }}"
                            wire:click="generatePassword"
                            icon="o-arrow-path"
                            class="btn-outline btn-sm btn-secondary"
                            type="button"
                        />
                    </div>

                    {{-- Affichage temporaire du MDP généré --}}
                    @if($password)
                        <div x-data="{ showPass: false }" class="p-3 bg-warning/10 border border-warning/30 rounded-lg space-y-2">
                            <div class="flex items-center justify-between">
                                <span class="font-mono text-sm font-semibold">
                                    <span x-show="!showPass">••••••••••••</span>
                                    <span x-show="showPass" x-cloak>{{ $password }}</span>
                                </span>
                                <div class="flex items-center gap-2">
                                    <button type="button" @click="showPass = !showPass" class="btn btn-ghost btn-xs">
                                        <x-icon name="o-eye" class="w-4 h-4" />
                                    </button>
                                    <button type="button" onclick="navigator.clipboard.writeText('{{ $password }}')" class="btn btn-warning btn-xs">
                                        <x-icon name="o-clipboard-document" class="w-4 h-4" />
                                        @lang('Copier')
                                    </button>
                                </div>
                            </div>
                            <p class="text-xs text-base-content/70">
                                @lang('Pensez à copier le mot de passe généré avant d\'enregistrer.')
                            </p>
                        </div>
                    @endif
                </div>

                {{-- Section : Préférences & RGPD --}}
                <div class="space-y-4 pt-4">
                    <div class="flex items-center gap-2 text-lg font-semibold border-b border-base-200 pb-2">
                        <x-icon name="o-cog-6-tooth" class="w-5 h-5 text-primary" />
                        <span>@lang('Préférences et confidentialité')</span>
                    </div>

                    <div class="space-y-3 bg-base-200/50 p-4 rounded-lg">
                        <x-checkbox
                            label="{{ __('Je souhaite recevoir la newsletter') }}"
                            wire:model="newsletter"
                        />
                        <x-checkbox
                            wire:model="rgpd"
                        >
                            <x-slot:label>
                                @lang('J\'accepte la')
                                <a href="{{ route('pages', ['page' => 'politique-de-confidentialite']) }}" target="_blank" class="link link-primary">
                                    @lang('politique de confidentialité')
                                </a>
                            </x-slot:label>
                        </x-checkbox>
                    </div>
                </div>

                {{-- Actions --}}
                <div class="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-between gap-3 pt-6 border-t border-base-200">
                    <x-button
                        label="{{ __('Annuler') }}"
                        wire:click="cancel"
                        class="btn-ghost"
                        type="button"
                    />

                    <x-button
                        label="{{ __('Enregistrer les modifications') }}"
                        icon="o-check"
                        spinner="save"
                        type="submit"
                        class="btn-primary"
                        ::disabled="!$wire.rgpd"
                    />
                </div>

            </x-form>
        </x-card>
    </div>
</div>
