<?php

use Livewire\Component;
use Livewire\Attributes\Validate;
use App\Models\Grant;
use App\Models\GrantLog;
use Illuminate\Support\Facades\DB;
use App\Notifications\GrantConfirmationNotification;

new class extends Component {
    #[Validate('required', message: 'Please provide an amount')]
    #[Validate('numeric', message: 'Amount must be a number')]
    #[Validate('min:1', message: 'Enter a valid amount')]
    public $amount;

    #[
        Validate(
            [
                'subscription' => 'required|array|min:1',
                'subscription.*' => 'required|string|in:program_funding,equipment_funding,research_funding,community_outreach',
            ],
            message: [
                'subscription.required' => 'Please select at least one funding purpose.',
                'subscription.min' => 'Please select at least one funding purpose.',
                'subscription.*.in' => 'Invalid selection.',
            ],
        ),
    ]
    public $subscription = [];

    public $type = 'personal';

    public function mount()
    {
        $user = auth()->user();

        $existingGrant = Grant::where('user_id', $user->id)->where('type', 'personal')->where('status', 'pending')->first();

        if ($existingGrant) {
            return redirect()
                ->route('user.grants.index')
                ->with([
                    'message' => 'you have a pending grant request.',
                    'type' => 'info',
                ]);
        }
    }

    public function personalGrant()
    {
        $this->validate();
        $user = auth()->user();

        // Step 0: check KYC
        if (!$user->kyc_verified) {
            $this->addError('error', 'Complete KYC before submitting.');
            return;
        }

        try {
            DB::beginTransaction();

            $existingGrant = Grant::where('user_id', $user->id)
                ->where('type', 'personal')
                ->where('status', 'pending')
                ->lockForUpdate() // lock row to prevent race condition
                ->first();

            if ($existingGrant) {
                throw new \Exception('You already have a pending personal grant application.');
            }

            $grant = Grant::create([
                'type' => 'personal',
                'user_id' => auth()->id(),
                'amount' => $this->amount,
                'purposes' => $this->subscription,
                'status' => 'pending',
            ]);

            GrantLog::create([
                'grant_id' => $grant->id,
                'user_id' => auth()->id(),
                'action' => 'submitted',
                'data' => [
                    'amount' => $this->amount,
                    'purposes' => $this->subscription,
                ],
            ]);

            auth()->user()->notify(new GrantConfirmationNotification($grant));

            DB::commit();

            $this->dispatch('showToast', message: 'Your grant application has been submitted!', type: 'success');
            $this->dispatch('notification-sent');
            $this->dispatch('transaction-success', type: 'grant', amount: $this->amount);
            $this->reset(['amount', 'subscription']);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Grant submission failed: ' . $e->getMessage());
            $this->dispatch('showToast', message: 'There was an error submitting your grant. Please try again.', type: 'error');
        }
    }
};

?>

<x-slot:title>
    {{ config('app.name') }} || Personal Grant Application
</x-slot:title>


<div class="space-y-6 py-4 font-sans">

    <!-- Header / Navigation -->
    <div class="flex flex-wrap items-center justify-between gap-2">
        <a href="{{ route('user.grants.index') }}"
            class="flex items-center gap-1 px-3 py-1.5 rounded-md text-black dark:text-white hover:shadow hover:bg-gray-100 dark:hover:bg-gray-700 transition">
            <x-flux::icon.arrow-left variant="solid" class="w-4 h-4" />
            <span class="text-sm font-medium">Individual Grant Application</span>
        </a>

        <a href="{{ route('user.grants.history') }}"
            class="flex items-center gap-1 px-3 py-1.5 rounded-md text-black dark:text-white hover:shadow hover:bg-gray-100 dark:hover:bg-gray-700 transition">
            <x-flux::icon.receipt-percent variant="solid" class="w-4 h-4" />
            <span class="text-sm font-medium">Track Request</span>
        </a>

    </div>

    <!-- Card Wrapper -->
    <div
        class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-md border border-gray-200/50 dark:border-gray-700/50 
               rounded-2xl shadow-md dark:shadow-lg p-6 sm:p-8 space-y-4">

        <!-- Header Icon + Title -->
        <div class="flex items-center gap-2">
            <x-flux::icon.user variant="solid" class="w-4 h-4" />
            <h2 class="text-sm md:text-base capitalize font-semibold text-gray-900 dark:text-white">Apply as Individual
            </h2>

        </div>

        <form wire:submit.prevent='personalGrant' class="space-y-4">
            <div>
                <x-input label="Requested Amount *" type="number" step="0.01" min="1"
                    placeholder="Enter the amount you would like to request for your grant"
                    wire:model.live.blur="amount" />
            </div>

            @php
                $fundingOptions = [
                    [
                        'value' => 'program_funding',
                        'title' => 'Program Funding',
                        'description' => 'Educational, cultural, or social programs',
                        'icon' => 'academic-cap',
                    ],
                    [
                        'value' => 'equipment_funding',
                        'title' => 'Equipment Funding',
                        'description' => 'Equipment or technology purchases',
                        'icon' => 'cpu-chip',
                    ],
                    [
                        'value' => 'research_funding',
                        'title' => 'Research Funding',
                        'description' => 'Research or field studies',
                        'icon' => 'beaker',
                    ],
                    [
                        'value' => 'community_outreach',
                        'title' => 'Community Outreach',
                        'description' => 'Community and underserved population support',
                        'icon' => 'users',
                    ],
                ];

            @endphp
            <x-checkbox-card-group label="Please select all funding purposes that apply to your application:"
                wire:model.live.blur="subscription" :options="$fundingOptions" columns="2" error="subscription" />

            <div
                class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg flex flex-col sm:flex-row gap-3 items-start sm:items-center shadow-sm">
                <x-flux::icon.information-circle class="w-5 h-5 text-sky-500 shrink-0" />
                <div class="space-y-1">
                    <h3 class="font-semibold text-sm tracking-wide">Important Information
                    </h3>
                    <p class="text-xs text-gray-600 dark:text-sky-200 leading-relaxed">
                        By submitting this application, you acknowledge that the final approved amount will be
                        determined during our review process based on your eligibility and requested amount. You'll
                        receive notification once your application has been processed.
                    </p>
                </div>
            </div>

            <x-button type="submit" size="md" icon="send" iconPosition="right">
                Submit Application
            </x-button>


        </form>
    </div>

</div>
