<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\User;
use App\Models\Kyc;
use Illuminate\Support\Facades\Storage;
use App\Notifications\KycStatusNotification;

new class extends Component {
    use WithFileUploads;

    public User $user;
    public $photo; // For wire:model upload

    public function mount(User $user)
    {
        $this->user = $user->load('kyc'); // load all KYC documents
    }

    // 1️⃣ Define rules
    protected $rules = [
        'photo' => 'required|image|max:10240|mimes:jpg,jpeg,png,webp',
    ];

    // 2️⃣ Define custom messages
    protected $messages = [
        'photo.required' => 'Please upload a photo.',
        'photo.image' => 'The uploaded file must be an image.type: jpg, jpeg, png, webp',
        'photo.max' => 'The photo must not be larger than 10 MB.',
        'photo.mimes' => 'The photo must be a file of type: jpg, jpeg, png, webp.',
    ];

    /** PROFILE PHOTO */
    public function updateProfilePhoto()
    {
        $this->validate();
        $profile = $this->user->profile ?? $this->user->profile()->create([]);

        // Delete old photo if exists
        if ($profile->profile_photo && Storage::disk('public')->exists($profile->profile_photo)) {
            Storage::disk('public')->delete($profile->profile_photo);
        }

        // Store new photo
        $path = $this->photo->store('avatars', 'public');

        $profile->update([
            'profile_photo' => $path,
        ]);

        $publicUrl = Storage::disk('public')->url($path) . '?t=' . time();

        $this->dispatch('profile-image-updated', name: $this->user->name, photoUrl: $publicUrl . '?t=' . time());

        $this->dispatch('showToast', message: 'Profile image updated successfully.', type: 'success');

        $this->reset('photo');
    }

    /** OPEN REJECT MODAL */
    public function openRejectModal(int $documentId): void
    {
        $this->dispatch('open-reject-modal', id: $documentId);
    }

    /** CONFIRM REJECTION (called from AlpineJS) */
    public function confirmReject(int $documentId, string $reason): void
    {
        $this->rejectKycDocument($documentId, $reason);
    }

    /** APPROVE KYC DOCUMENT */
    public function approveKycDocument(int $id): void
    {
        $document = Kyc::findOrFail($id);

        if ($document->status === Kyc::STATUS_VERIFIED) {
            return;
        }

        $document->update([
            'status' => Kyc::STATUS_VERIFIED,
            'verified_at' => now(),
            'rejection_reason' => null,
        ]);
        $documentType = $document->id_type ?? 'Unknown';
        $document->user->notify(new KycStatusNotification(documentType: $documentType, status: 'approved'));
        $this->dispatch('notification-sent');
        $this->dispatch('showToast', message: 'Document approved and user notified.', type: 'success');
    }

    /** REJECT KYC DOCUMENT */
    public function rejectKycDocument(int $documentId, string $reason): void
    {
        $reason = trim($reason);
        if (strlen($reason) < 5) {
            $this->addError('reason', 'Rejection reason must be at least 5 characters');
            return;
        }

        $document = Kyc::findOrFail($documentId);

        if ($document->status === Kyc::STATUS_REJECTED) {
            return;
        }

        $document->update([
            'status' => Kyc::STATUS_REJECTED,
            'rejection_reason' => $reason,
            'verified_at' => null,
        ]);

        $documentType = $document->id_type ?? 'Unknown';
        $document->user->notify(new KycStatusNotification(documentType: $documentType, status: 'rejected', reason: $reason));
        $this->dispatch('notification-sent');
        $this->dispatch('reject-success');
        $this->dispatch('showToast', message: 'Document rejected and user notified.', type: 'success');
    }
};
?>
<div>
    <div class="lg:flex lg:space-x-6">

        {{-- LEFT COLUMN --}}
        <div
            class="lg:w-1/3 bg-linear-to-b from-gray-50 to-white dark:from-gray-900 dark:to-gray-800 p-6 rounded-xl shadow-lg flex flex-col items-center space-y-6">

            {{-- PROFILE PHOTO --}}
            {{-- PROFILE PHOTO --}}
            <div x-data="{
                photoPreview: null,
                showSaveButton: false,
                description: 'Choose a photo to update your profile',
                originalDescription: 'Choose a photo to update your profile',
                uploadProgress: 0,
                uploading: false,
            
                init() {
                    // Start upload
                    this.$el.addEventListener('livewire-upload-start', () => {
                        this.uploading = true;
                        this.uploadProgress = 0;
                        this.description = 'Uploading... 0%';
                        this.showSaveButton = false;
                    });
            
                    // Progress
                    this.$el.addEventListener('livewire-upload-progress', event => {
                        this.uploadProgress = event.detail.progress;
                        this.description = 'Uploading... ' + this.uploadProgress + '%';
                    });
            
                    // Upload finished
                    this.$el.addEventListener('livewire-upload-finish', () => {
                        this.uploading = false;
                        this.description = this.originalDescription;
                        this.showSaveButton = true;
                    });
            
                    // Upload error
                    this.$el.addEventListener('livewire-upload-error', () => {
                        this.uploading = false;
                        this.description = 'Upload failed. Try again.';
                        this.showSaveButton = false;
                    });
            
                    // Profile updated
                    window.addEventListener('profile-image-updated', e => {
                        this.photoPreview = e.detail.photoUrl;
                        this.showSaveButton = false;
                        this.description = this.originalDescription;
                    });
                },
            
                handleFileChange(event) {
                    const file = event.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = e => this.photoPreview = e.target.result;
                        reader.readAsDataURL(file);
            
                        // Do NOT show Save button yet — will show after upload finish
                        this.showSaveButton = false;
                    } else {
                        this.photoPreview = null;
                        this.showSaveButton = false;
                    }
                }
            }" class="flex flex-col items-center space-y-2">

                <div class="relative group cursor-pointer" @click="$refs.photoInput.click()">
                    <div class="h-28 w-28 rounded-full overflow-hidden border-4 border-sky-500 shadow relative">
                        <template x-if="photoPreview">
                            <img :src="photoPreview" class="h-full w-full object-cover" />
                        </template>
                        <template x-if="!photoPreview">
                            <img src="{{ optional($user->profile)->profile_photo
                                ? Storage::disk('public')->url($user->profile->profile_photo)
                                : 'https://ui-avatars.com/api/?name=' . urlencode($user->name) }}"
                                alt="{{ $user->name }}’s profile photo"
                                class="h-full w-full object-cover transition-opacity duration-300" alt="Profile Photo">
                        </template>

                        <div x-show="uploading"
                            class="absolute inset-0 bg-black/50 flex flex-col items-center justify-center text-white text-xs font-medium transition">
                            Uploading... <span x-text="uploadProgress + '%'"></span>
                        </div>
                    </div>

                    <div
                        class="absolute inset-0 bg-black/50 flex items-center justify-center text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition rounded-full">
                        Change Photo
                    </div>
                </div>
                <p class="text-xs text-gray-500" x-text="description"></p>

                <!-- File Input -->
                <input type="file" x-ref="photoInput" wire:model="photo" class="hidden"
                    @change="handleFileChange($event)" />

                <!-- Display validation error -->
                @error('photo')
                    <p class="text-xs text-red-500 mt-1">{{ $message }}</p>
                @enderror

                <!-- Save Button -->
                <button x-show="showSaveButton" x-cloak x-transition wire:click="updateProfilePhoto"
                    wire:loading.attr="disabled" class="text-xs text-sky-600 hover:underline flex items-center gap-2"
                    :disabled="uploading">
                    <span wire:loading.remove>Save Photo</span>
                    <span wire:loading>
                        <svg class="animate-spin h-4 w-4 text-sky-600" 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-8v8H4z"></path>
                        </svg>
                        Saving...
                    </span>
                </button>
            </div>

            {{-- BASIC INFO --}}
            <div class="text-center space-y-1">
                <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100">
                    {{ $user->name }}
                </h2>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                    {{ $user->email }}
                </p>
            </div>

            {{-- ACCOUNT INFO --}}
            <div class="w-full space-y-3 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-600 dark:text-gray-300">Account Created</span>
                    <span class="font-medium text-gray-800 dark:text-gray-100">
                        {{ $user->created_at->format('M d, Y') }}
                    </span>
                </div>

                @php
                    $latestKyc = $user->kyc->firstWhere('is_latest', true); // LEFT column
                    $sortedKyc = $user->kyc->sortByDesc('is_latest'); // RIGHT column
                @endphp

                <div class="flex justify-between items-center">
                    <span class="text-gray-600 dark:text-gray-300">KYC Status</span>

                    @if ($latestKyc)
                        @if ($latestKyc->isRejected())
                            <span class="bg-red-100 text-red-800 px-2 py-1 rounded-full text-xs font-semibold">
                                Rejected
                            </span>
                        @elseif ($latestKyc->isVerified())
                            <span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-semibold">
                                Verified
                            </span>
                        @else
                            <span class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs font-semibold">
                                Pending Review
                            </span>
                        @endif
                    @else
                        <span class="bg-gray-100 text-gray-800 px-2 py-1 rounded-full text-xs font-semibold">
                            No KYC Uploaded
                        </span>
                    @endif
                </div>
            </div>
        </div>

        {{-- RIGHT COLUMN --}}
        <div class="lg:w-2/3 bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg">

            <h2 class="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-6">
                KYC Documents
            </h2>

            <div class="space-y-4">

                @forelse ($sortedKyc as $document)
                    <div
                        class="border dark:border-gray-700 rounded-lg p-4 space-y-4
                        {{ $document->is_latest ? 'ring-2 ring-sky-500 dark:ring-sky-400' : '' }}">

                        {{-- Header --}}
                        <div class="flex justify-between items-center">
                            <h3 class="font-medium text-gray-800 dark:text-gray-100">
                                {{ ucfirst($document->id_type) }}
                                @if ($document->is_latest)
                                    <span class="ml-2 text-xs text-sky-600 dark:text-sky-400">(Latest)</span>
                                @endif
                            </h3>

                            {{-- Status Badge --}}
                            @if ($document->isVerified())
                                <span class="bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs font-semibold">
                                    Verified
                                </span>
                            @elseif($document->isRejected())
                                <span class="bg-red-100 text-red-800 px-2 py-1 rounded-full text-xs font-semibold">
                                    Rejected
                                </span>
                            @else
                                <span
                                    class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs font-semibold">
                                    Awaiting Review
                                </span>
                            @endif
                        </div>

                        {{-- Files --}}
                        <div class="space-y-1">
                            @foreach ($document->id_document_paths ?? [] as $path)
                                @if (Storage::disk('public')->exists($path))
                                    <a href="{{ Storage::disk('public')->url($path) }}" target="_blank"
                                        class="text-sky-600 hover:underline text-sm block">
                                        View Uploaded Document
                                    </a>
                                @else
                                    <span class="text-red-500 text-xs block">
                                        File Missing
                                    </span>
                                @endif
                            @endforeach
                        </div>
                        {{-- Actions --}}
                        @if ($document->isPending())
                            <div class="flex space-x-3">
                                <x-flux::button wire:click="approveKycDocument({{ $document->id }})" type="button"
                                    variant="primary" color="green" class="flex-1 text-xs">
                                    Approve Document
                                </x-flux::button>

                                <x-flux::button type="button" variant="danger"
                                    wire:click="openRejectModal({{ $document->id }})" class="flex-1 text-xs">
                                    Reject Document
                                </x-flux::button>
                            </div>
                        @endif
                    </div>
                @empty
                    <div class="text-center text-gray-500 dark:text-gray-400 text-sm py-6">
                        No KYC documents uploaded.
                    </div>
                @endforelse

            </div>
        </div>
    </div>

    {{-- Reject Modal --}}
    <div x-data="{
        open: false,
        documentId: null,
        reason: '',
        closeModal() {
            this.open = false;
            this.documentId = null;
            this.reason = '';
        }
    }"
        x-on:open-reject-modal.window="
        open = true;
        documentId = $event.detail.id;
        reason = '';
    "
        x-on:reject-success.window="closeModal()" x-show="open" x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md p-6 space-y-4"
            @click.away="closeModal()">

            <h2 class="text-lg font-semibold text-gray-800 dark:text-gray-100">
                Reject KYC Document
            </h2>

            <p class="text-sm text-gray-600 dark:text-gray-400">
                Please provide a reason for rejection.
                This explanation will be visible to the user.
            </p>

            <div>
                <x-textarea wire:model.defer="reason" label="Rejection Reason" x-model="reason" rows="4" />
            </div>

            <div class="flex justify-end space-x-3 pt-2">
                <button type="button" @click="closeModal()"
                    class="px-4 py-2 text-sm bg-gray-200 dark:bg-gray-600 rounded-md">
                    Cancel
                </button>

                <x-flux::button type="button" wire:loading.attr="disabled" wire:target="confirmReject"
                    @click="$wire.call('confirmReject', documentId, reason)" icon="exclamation-circle"
                    variant="danger">
                    <span wire:loading.remove wire:target="confirmReject">Reject</span>
                    <span wire:loading wire:target="confirmReject">Rejecting...</span>
                </x-flux::button>

            </div>
        </div>
    </div>

</div>
