<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Kyc;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

new class extends Component {
    use WithFileUploads;
    public $id_type = '';
    public $id_images = [];
    public $temp_id_images = [];

    public $unreadCount = 0;

    #[On('profile-updated')]
    public function refreshAvatar()
    {
        $this->profilePhotoUrl = Storage::disk('public')->url(Auth::user()->profile->profile_photo);
    }

    public function mount()
    {
        $this->refreshUnreadCount();
    }

    #[On('notification-sent')]
    #[On('notifications-read')]
    public function refreshUnreadCount()
    {
        $this->unreadCount = auth()->user()->unreadNotifications()->count();
    }

    public function markAsRead($id)
    {
        auth()->user()->unreadNotifications()->where('id', $id)->first()?->markAsRead();

        $this->refreshUnreadCount();
    }
    public function clearError($field)
    {
        $this->resetErrorBag($field);
    }

    public array $kyc_docs = [['value' => 'passport', 'label' => 'Passport'], ['value' => 'national_id', 'label' => 'National ID Card'], ['value' => 'driver_license', 'label' => 'Driver\'s License'], ['value' => 'voter_id', 'label' => 'Voter ID Card'], ['value' => 'residence_permit', 'label' => 'Residence Permit'], ['value' => 'others', 'label' => 'Others']];

    protected $rules = [
        'id_type' => 'required|string',
        'id_images' => 'required|array|min:1|max:3',
        'id_images.*' => 'required|image|max:10240|mimes:jpg,jpeg,png,webp',
    ];

    protected function messages()
    {
        return [
            // id_images general
            'id_images.required' => 'Please upload at least one ID image.',
            'id_images.array' => 'The ID images must be an array.',
            'id_images.min' => 'Please upload at least one ID image.',
            'id_images.max' => 'You can upload up to 3 ID images only.',

            // each individual id image
            'id_images.*.required' => 'Each ID image file is required.',
            'id_images.*.image' => 'Each file must be a valid image only jpeg, jpg, png, webp are allowed.',
            'id_images.*.max' => 'Each image must not exceed 2MB.',
            'id_images.*.mimes' => 'Only JPG and PNG images are allowed for ID images.',
        ];
    }

    public function removeImage($model, $index = null)
    {
        if (is_array($this->$model) || $this->$model instanceof \Illuminate\Support\Collection) {
            $files = collect($this->$model)->forget($index)->values()->all();
            $this->$model = $files;

            // Also sync to id_images if it's temp_id_images
            if ($model === 'temp_id_images') {
                $this->id_images = $files;
            }
        } else {
            $this->$model = null;
        }
    }

    public function updatedIdImages($newImages)
    {
        // Merge new images with old ones stored in temp_id_images
        $merged = collect($this->temp_id_images)
            ->merge($newImages)
            ->unique(function ($file) {
                return $file->getFilename();
            })
            ->values()
            ->all();

        $this->temp_id_images = $merged;
        $this->id_images = $merged;
    }

    public function submit()
    {
        $validated = $this->validate();

        $user = auth()->user();
        $storedIdImages = [];

        DB::beginTransaction();

        try {
            // 1) Store uploaded files first
            foreach ($this->id_images as $file) {
                $storedIdImages[] = $file->store('kyc-documents', 'public');
            }

            // 2) Lock user's KYC rows (prevents double submit race conditions)
            Kyc::where('user_id', $user->id)->lockForUpdate()->get();

            // 3) Mark previous latest as not latest
            Kyc::where('user_id', $user->id)
                ->where('is_latest', true)
                ->update(['is_latest' => false]);

            // 4) Determine latest version safely
            $latestVersion = Kyc::where('user_id', $user->id)->max('version') ?? 0;

            // 5) Create new latest KYC
            Kyc::create([
                'user_id' => $user->id,
                'id_type' => $this->id_type,
                'id_document_paths' => $storedIdImages,
                'status' => Kyc::STATUS_PENDING,
                'is_latest' => true,
                'version' => $latestVersion + 1,
            ]);

            DB::commit();

            // Reset form
            $this->reset(['id_type', 'id_images', 'temp_id_images']);

            $this->dispatch('showToast', message: 'KYC documents uploaded successfully!', type: 'success');
            $this->dispatch('kyc-uploaded');
        } catch (\Exception $e) {
            DB::rollBack();

            // Delete uploaded files if DB failed
            foreach ($storedIdImages as $path) {
                if (Storage::disk('public')->exists($path)) {
                    Storage::disk('public')->delete($path);
                }
            }

            Log::error('KYC submission failed', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }
};

?>
<div
    class="px-6 py-4 bg-white dark:bg-zinc-900 shadow-sm border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between">

    @php
        $page = currentPageInfo($authUser);
    @endphp
    <div wire:ignore class="flex items-center gap-2">

        <!-- Mobile hamburger -->
        <div class="lg:hidden z-50">
            <button @click="opensidebar = !opensidebar"
                class="relative w-8 h-8 flex flex-col justify-center items-center gap-1.5 p-2 bg-white dark:bg-gray-800 text-rose-600 dark:text-white rounded-md shadow-md focus:outline-none focus:ring-2 focus:ring-rose-500">

                @foreach (['', '', ''] as $i)
                    <span
                        :class="opensidebar
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        ? ['first:rotate-45 absolute', 'second:opacity-0', 'third:-rotate-45 absolute'][$loop->index] 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        : ''"
                        class="block w-6 h-0.5 bg-current transition-transform duration-500 ease-[cubic-bezier(0.68,-0.55,0.27,1.55)]
                           transition-opacity duration-500 scale-80"></span>
                @endforeach
            </button>
        </div>

        <!-- Title & Welcome -->
        <div class="hidden sm:block">
            <h2 class="text-base md:text-lg font-semibold text-gray-900 dark:text-white">{{ $page['title'] }}</h2>
            @if ($page['showWelcome'])
                <p class="text-sm text-gray-500 dark:text-gray-400">{{ $page['welcome'] }}</p>
            @endif
        </div>

    </div>

    @inject('impersonation', \App\Services\ImpersonationService::class)

    @if ($impersonation->isImpersonating())
        <div class="bg-yellow-400 text-black text-center py-2 text-sm">
            You are logged in as a user
            <form method="POST" action="{{ route('admin.impersonation.leave') }}" class="inline">
                @csrf
                <button class="underline ml-2 font-semibold">
                    Return to Admin
                </button>
            </form>
        </div>
    @endif


    <!-- RIGHT: Notifications + Account -->
    <div class="flex items-center gap-4" x-data="{ openDropdown: null }" @click.outside="openDropdown = null">
        <div class="flex items-center gap-3 relative">
            @php
                $kyc = Kyc::latestForUser(auth()->id())->first();
            @endphp
            <!-- Buttons -->
            @if (!$kyc)
                <!-- No KYC submitted -->
                <flux:button type="button" @click="$dispatch('open-kyc-modal')" class="bg-sky-500">
                    Verify KYC
                </flux:button>
            @elseif($kyc->status === 'pending')
                <!-- KYC submitted, pending -->
                <div class="p-2 bg-yellow-100 text-yellow-800 rounded-md text-sm text-center cursor-help"
                    title="Your KYC verification is pending. Please wait for approval.">
                    Pending KYC
                </div>
            @elseif($kyc->status === 'rejected')
                <!-- KYC rejected, allow re-upload -->
                <flux:button type="button" @click="$dispatch('open-kyc-modal')" class="bg-red-500 hover:bg-red-900">
                    Re-upload KYC
                </flux:button>
            @endif

            <!-- Single reusable modal -->
            <x-modal x-on:kyc-uploaded.window="close()" @open-kyc-modal.window="openModal()"
                @close-open-kyc-modal.window="close()">
                @include('partials.kyc')
            </x-modal>

        </div>
        <!-- Dark Mode Toggle with animation -->
        <button @click="darkMode = !darkMode; localStorage.setItem('darkMode', darkMode)"
            class="relative p-3 rounded-2xl bg-linear-to-br from-gray-50 to-gray-100 
               dark:from-gray-800 dark:to-gray-700 text-gray-600 dark:text-gray-300 
               hover:from-primary-50 hover:to-primary-100 
               dark:hover:from-primary-900/30 dark:hover:to-primary-800/30 
               transition-all duration-300 shadow-lg hover:shadow-xl 
               hover:-translate-y-0.5 group">
            <x-flux::icon.sun variant="solid" x-show="!darkMode" x-cloak
                class="w-5 h-5 group-hover:rotate-180 transition-transform duration-500" />

            <x-flux::icon.moon variant="solid" x-cloak x-show="darkMode"
                class="w-5 h-5 group-hover:rotate-12 transition-transform duration-300" />
        </button>

        <!-- Notifications -->
        <div class="relative">
            <button @click="openDropdown = (openDropdown === 'notifications' ? null : 'notifications')"
                class="relative p-2 rounded-full hover:bg-sky-100 dark:hover:bg-sky-900 focus:outline-none transition">
                <flux:icon.bell
                    class="w-6 h-6 {{ $unreadCount > 0 ? 'text-sky-500 animate-pulse' : 'text-gray-500 dark:text-gray-300' }}" />

                {{-- Badge --}}
                @if ($unreadCount > 0)
                    <span
                        class="absolute -top-1 -right-1 bg-sky-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-[10px] font-semibold shadow">
                        {{ $unreadCount }}
                    </span>
                @endif
            </button>

            {{-- Dropdown --}}
            <div x-show="openDropdown === 'notifications'" x-collapse x-cloak
                class="absolute right-0 w-96 max-h-96 overflow-y-auto bg-white dark:bg-zinc-900 shadow-2xl rounded-xl border border-gray-200 dark:border-zinc-700 mt-2 z-50">

                <div class="py-2 px-3 border-b border-gray-200 dark:border-zinc-700">
                    <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-200">Notifications</h4>
                </div>

                <div class="divide-y divide-gray-100 dark:divide-zinc-800">
                    @forelse(auth()->user()->notifications()->latest()->take(10)->get() as $notification)
                        @php
                            $link = $notification->data['link'] ?? null;
                        @endphp

                        @if ($link)
                            <a href="{{ $link }}" class="block">
                        @endif

                        <div class="flex items-start gap-3 p-3 hover:bg-sky-50 dark:hover:bg-sky-900 rounded-lg transition cursor-pointer"
                            @if (!$link) @click="$wire.markAsRead('{{ $notification->id }}')" @endif>

                            <div class="shrink-0">
                                <flux:icon.bell-alert class="w-5 h-5 text-sky-500 mt-1" />
                            </div>

                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                    {{ $notification->data['title'] ?? 'Notification' }}
                                </p>

                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                    {{ $notification->data['message'] ?? '' }}
                                </p>


                                <span class="text-[10px] text-gray-400 dark:text-gray-500 mt-1 block">
                                    {{ $notification->created_at->diffForHumans() }}
                                </span>
                            </div>

                            @if (!$notification->read_at)
                                <span class="ml-2 shrink-0 w-2 h-2 bg-sky-500 rounded-full mt-1"></span>
                            @endif
                        </div>

                        @if ($link)
                            </a>
                        @endif
                    @empty
                        <p class="text-center text-gray-400 dark:text-gray-500 py-6 text-sm">
                            No new notifications
                        </p>
                    @endforelse

                </div>

                <div class="text-center py-2">
                    <a href="{{ route('user.transactions') }}"
                        class="text-sky-600 hover:text-sky-700 dark:text-sky-400 dark:hover:text-sky-300 text-sm font-medium transition">
                        View All
                    </a>
                </div>
            </div>
        </div>

        <!-- Account Menu -->
        <div class="relative">
            <button @click="openDropdown = (openDropdown === 'account' ? null : 'account')"
                class="flex items-center gap-2 px-3 py-1 rounded-full hover:bg-gray-100 dark:hover:bg-zinc-800 transition">
                @if ($authUser->profile->profile_photo)
                    <img src="{{ Storage::disk('public')->url($authUser->profile->profile_photo) }}"
                        class="w-8 h-8 rounded-full object-cover" />
                @else
                    <div
                        class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-sm font-semibold text-gray-700">
                        {{ $authUser->initials() }}
                    </div>
                @endif

                <x-flux::icon.chevron-down class="w-3 h-3 text-gray-600" />
            </button>

            <div x-show="openDropdown === 'account'" x-collapse x-cloak
                class="absolute right-0 mt-3 w-60 bg-white dark:bg-zinc-900 shadow-xl rounded-xl overflow-hidden z-50">

                <!-- User Info -->
                <div class="px-4 py-3 border-b dark:border-zinc-700">
                    <p class="text-sm font-semibold text-gray-900 dark:text-white truncate">{{ auth()->user()->name }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 truncate">{{ auth()->user()->email }}</p>
                </div>

                <!-- KYC Status -->
                <div class="px-4 py-3 border-b dark:border-zinc-700">
                    @php
                        $kyc = \App\Models\Kyc::latestForUser(auth()->id())->first();
                    @endphp

                    @if (!$kyc)
                        <div
                            class="flex items-center gap-2 px-3 py-2 bg-gray-100 dark:bg-zinc-800 text-gray-700 dark:text-gray-300 rounded-lg font-medium text-xs">
                            <x-flux::icon.exclamation-triangle class="w-4 h-4 text-red-500" />
                            <span>KYC Status: Not Submitted</span>
                        </div>
                    @elseif($kyc->status === 'pending')
                        <div
                            class="flex items-center gap-2 px-3 py-2 bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-300 rounded-lg text-xs font-medium">
                            <x-flux::icon.clock class="w-4 h-4" />
                            <span>KYC Status: Pending</span>
                        </div>
                    @elseif($kyc->status === 'verified')
                        <div
                            class="flex items-center gap-2 px-3 py-2 bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 rounded-lg text-xs font-medium">
                            <x-flux::icon.check-circle class="w-4 h-4" />
                            <span>KYC Status: Approved</span>
                        </div>
                    @elseif($kyc->status === 'rejected')
                        <div
                            class="flex items-center gap-2 px-3 py-2 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 rounded-lg text-xs font-medium">
                            <x-flux::icon.x-circle class="w-4 h-4" />
                            <span>KYC Status: Rejected</span>
                        </div>
                    @endif
                </div>

                <!-- Links -->
                <div class="py-2 flex flex-col gap-1 text-sm">
                    <a href="{{ route('user.dashboard') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200 ">
                        <x-flux::icon.home class="w-4 h-4" /> Dashboard
                    </a>

                    <a href="{{ route('user.deposit') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200">
                        <x-flux::icon.plus-circle class="w-4 h-4" /> Deposit
                    </a>

                    <a href="{{ route('user.withdrawal') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200">
                        <x-flux::icon.arrow-up-right class="w-4 h-4" /> Withdrawal
                    </a>

                    <a href="{{ route('user.virtual.cards') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200">
                        <x-flux::icon.credit-card class="w-4 h-4" /> Virtual Cards
                    </a>

                    <a href="{{ route('user.local.transfer') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200">
                        <x-flux::icon.arrows-right-left class="w-4 h-4" /> Local Transfer
                    </a>

                    <a href="{{ route('user.settings.index') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-gray-100 dark:hover:bg-zinc-800 rounded-lg text-gray-700 dark:text-gray-200">
                        <x-flux::icon.cog class="w-4 h-4" /> Account Settings
                    </a>

                    <a href="{{ route('user.logout') }}"
                        class="flex items-center gap-2 px-4 py-2 hover:bg-red-50 dark:hover:bg-red-900 rounded-lg text-red-600">
                        <x-flux::icon.arrow-left-start-on-rectangle class="w-4 h-4" /> Logout
                    </a>
                </div>
            </div>
        </div>


    </div>

</div>
