<?php

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

new class extends Component {
    // -----------------------------
    // STEP 1: Organization Details
    // -----------------------------
    #[Url]
    public $name; // Legal Name of Organization
    #[Url]
    public $tax_id_ein; // Tax ID / EIN

    public $type = 'company'; // Organization Type
    #[Url]
    public $organization_type = '';
    #[Url]
    public $year; // Founding Year
    #[Url]
    public $mailing_address; // Full Mailing Address

    // -----------------------------
    // STEP 2: Contact Information
    // -----------------------------
    #[Url]
    public $phone; // Contact Phone Number
    #[Url]
    public $contact_person; // Contact Person Name

    // -----------------------------
    // STEP 3: Organization Mission & Details
    // -----------------------------
    #[Url]
    public $mission_statement; // Organization Mission Statement
    #[Url]
    public $date_corporation; // Date of Incorporation

    // -----------------------------
    // STEP 4: Project Details
    // -----------------------------
    #[Url]
    public $project_title; // Project Title
    #[Url]
    public $project_description; // Project Description
    #[Url]
    public $amount; // Project Amount
    #[Url]
    public $additional_notes; // Optional Notes / Comments

    // -----------------------------
    // STEP TRACKING
    // -----------------------------
    #[Url]
    public int $currentStep = 1;
    #[Url]
    public int $totalSteps = 3;
    public function mount()
    {
        $user = auth()->user();

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

        if ($existingGrant) {
            return redirect()
                ->route('user.grants.index')
                ->with([
                    'message' => 'you have a pending grant request.',
                    'type' => 'info',
                ]);
        }
    }
    protected function rulesForCurrentStep(): array
    {
        switch ($this->currentStep) {
            // ───────────── STEP 1: Organization Details ─────────────
            case 1:
                return [
                    'name' => ['required', 'string', 'max:255'],
                    'tax_id_ein' => ['required', 'string', 'max:50'],
                    'organization_type' => ['required', 'string', 'in:non_profit,for_profit,government_entity,educational_institution,healthcare_provider,ngo,cooperative,other,company'],
                    'year' => ['required', 'date', 'before_or_equal:' . date('Y-m-d')],
                    'mailing_address' => ['required', 'string', 'max:500'],
                ];

            // ───────────── STEP 2: Contact Information ─────────────
            case 2:
                return [
                    'phone' => ['required', 'regex:/^\+?[0-9\s\-\(\)]{7,20}$/'],
                    'contact_person' => ['required', 'string', 'max:100'],
                    'mission_statement' => ['required', 'string', 'max:2000'],
                    'date_corporation' => ['required', 'date', 'before_or_equal:' . date('Y-m-d')],
                ];

            // ───────────── STEP 4: Project Details ─────────────
            case 3:
                return [
                    'project_title' => ['required', 'string', 'max:255'],
                    'project_description' => ['required', 'string', 'max:5000'],
                    'amount' => ['required', 'numeric', 'min:1'],
                    'additional_notes' => ['nullable', 'string', 'max:2000'],
                ];

            default:
                return [];
        }
    }

    protected function messages(): array
    {
        return [
            // ───────────── STEP 1: Organization Details ─────────────
            'name.required' => 'Please enter the legal name of your organization.',
            'name.string' => 'Organization name must be a valid string.',
            'name.max' => 'Organization name cannot exceed 255 characters.',

            'tax_id_ein.required' => 'Please enter your Tax ID / EIN.',
            'tax_id_ein.string' => 'Tax ID / EIN must be a valid string.',
            'tax_id_ein.max' => 'Tax ID / EIN cannot exceed 50 characters.',

            'organization_type.required' => 'Please select the organization type.',
            'organization_type.string' => 'Organization type must be a valid string.',
            'organization_type.in' => 'Selected organization type is invalid.',

            'year.required' => 'Please select the founding year.',
            'year.date' => 'Please enter a valid founding year.',
            'year.before_or_equal' => 'Founding year cannot be in the future.',

            'mailing_address.required' => 'Please enter the full mailing address.',
            'mailing_address.string' => 'Mailing address must be a valid string.',
            'mailing_address.max' => 'Mailing address cannot exceed 500 characters.',

            // ───────────── STEP 2: Contact Information ─────────────
            'phone.required' => 'Please enter a contact phone number.',
            'phone.regex' => 'Please enter a valid phone number, e.g., +1 (555) 555-5555.',

            'contact_person.required' => 'Please enter the contact person name.',
            'contact_person.string' => 'Contact person name must be a valid string.',
            'contact_person.max' => 'Contact person name cannot exceed 100 characters.',

            // ───────────── STEP 3: Organization Mission & Details ─────────────
            'mission_statement.required' => 'Please enter your organization mission statement.',
            'mission_statement.string' => 'Mission statement must be a valid string.',
            'mission_statement.max' => 'Mission statement cannot exceed 2000 characters.',

            'date_corporation.required' => 'Please enter the date of incorporation.',
            'date_corporation.date' => 'Please enter a valid date of incorporation.',
            'date_corporation.before_or_equal' => 'Date of incorporation cannot be in the future.',

            // ───────────── STEP 4: Project Details ─────────────
            'project_title.required' => 'Please enter the project title.',
            'project_title.string' => 'Project title must be a valid string.',
            'project_title.max' => 'Project title cannot exceed 255 characters.',

            'project_description.required' => 'Please enter the project description.',
            'project_description.string' => 'Project description must be a valid string.',
            'project_description.max' => 'Project description cannot exceed 5000 characters.',

            'amount.required' => 'Please provide a project amount.',
            'amount.numeric' => 'Amount must be a valid number.',
            'amount.min' => 'Amount must be at least 1.',

            'additional_notes.string' => 'Additional notes must be a valid string.',
            'additional_notes.max' => 'Additional notes cannot exceed 2000 characters.',
        ];
    }

    protected function rules(): array
    {
        return $this->rulesForCurrentStep();
    }

    protected function validateCurrentStep(): void
    {
        $this->skipTransition();
        $this->validate($this->rulesForCurrentStep());
    }

    public function updated($field)
    {
        $this->validateOnly($field, $this->rulesForCurrentStep());
    }

    #[Transition(type: 'forward')]
    public function nextStep()
    {
        $this->validateCurrentStep();
        if ($this->currentStep < $this->totalSteps) {
            $this->currentStep++;
        }
    }

    #[Transition(type: 'backward')]
    public function previousStep()
    {
        if ($this->currentStep > 1) {
            $this->currentStep--;
        }
    }

    public function companyGrant()
    {
        $this->validateCurrentStep();

        $user = auth()->user();

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

        // Step 1: build metadata once
        $metaFields = [
            'organization' => [
                'name' => $this->name,
                'tax_id_ein' => $this->tax_id_ein,
                'organization_type' => $this->organization_type,
                'year' => $this->year,
                'mailing_address' => $this->mailing_address,
            ],
            'contact' => [
                'phone' => $this->phone,
                'contact_person' => $this->contact_person,
            ],
            'mission' => [
                'mission_statement' => $this->mission_statement,
                'date_corporation' => $this->date_corporation,
            ],
            'project' => [
                'title' => $this->project_title,
                'description' => $this->project_description,
                'additional_notes' => $this->additional_notes,
            ],
        ];

        // Step 2: wrap in DB transaction closure
        try {
            DB::transaction(function () use ($user, $metaFields) {
                // Check if a pending grant already exists inside the transaction
                $existingGrant = Grant::where('user_id', $user->id)
                    ->where('type', 'company')
                    ->where('status', 'pending')
                    ->lockForUpdate() // lock row to prevent race condition
                    ->first();

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

                // Create the grant
                $grant = Grant::create([
                    'type' => 'company',
                    'user_id' => $user->id,
                    'amount' => $this->amount ?? 0,
                    'purposes' => [], // already cast to array in model
                    'metadata' => $metaFields, // already cast to array in model
                    'status' => 'pending',
                ]);

                // Log the submission
                GrantLog::create([
                    'grant_id' => $grant->id,
                    'user_id' => $user->id,
                    'action' => 'submitted',
                    'data' => [
                        'amount' => $this->amount,
                        'metadata' => $metaFields,
                    ],
                ]);

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

            $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(); // optional: reset form
            $this->currentStep = 1; // reset to first step
        } catch (\Exception $e) {
            \Log::error('Company Grant Submission Error: ' . $e->getMessage());
            $this->addError('error', $e->getMessage() === 'You already have a pending company grant application.' ? $e->getMessage() : 'Something went wrong. Please try again later.');
        }
    }
};

?>

<x-slot:title>
    {{ config('app.name') }} || Company 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">Company 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.building-office 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 Company
            </h2>

        </div>

        <div wire:transition="content">
            <div class="mb-10">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-2xl font-semibold">Step {{ $currentStep }} of {{ $totalSteps }}</h2>

                    @php
                        $stepLabels = [
                            1 => 'Organization Details',
                            2 => 'Contact Information',
                            3 => 'Project Information',
                        ];
                    @endphp

                    <span class="text-sm font-medium text-sky-500 dark:text-sky-100">
                        {{ $stepLabels[$currentStep] ?? '' }}
                    </span>
                </div>

                <div class="flex h-3 bg-gray-100 rounded-full overflow-hidden">
                    @for ($i = 1; $i <= $totalSteps; $i++)
                        <div
                            class="flex-1
                    @if ($i < $currentStep) bg-green-500
                    @elseif ($i === $currentStep) bg-sky-500
                    @else bg-gray-200 @endif">
                        </div>
                        @if ($i < $totalSteps)
                            <div class="w-[2px] bg-white"></div>
                        @endif
                    @endfor
                </div>
            </div>

            <form wire:submit.prevent="companyGrant" class="space-y-6" wire:key="step-{{ $currentStep }}">
                @include('partials.errors')
                @switch($currentStep)
                    {{-- ───────────── STEP 1: Organization Information ───────────── --}}
                    @case(1)
                        <x-step-header title="Organization Information"
                            subtitle="Provide the legal details about your organization." />

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <x-input wire:model.live.blur="name" label="Legal Name of Organization *"
                                    placeholder="Enter your organization's registered name" />
                            </div>
                            <div>
                                <x-input wire:model.live.blur="tax_id_ein" label="Tax ID / EIN *"
                                    placeholder="Enter your organization's Tax ID or EIN" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <x-select wire:model.live.blur="organization_type" id="type" label="Organization Type *"
                                    placeholder="Select an organization type">
                                    <option value="non_profit">Non-Profit Organization</option>
                                    <option value="for_profit">For-Profit Organization</option>
                                    <option value="government_entity">Government Entity</option>
                                    <option value="educational_institution">Educational Institution</option>
                                    <option value="healthcare_provider">Healthcare Provider</option>
                                    <option value="ngo">NGO</option>
                                    <option value="cooperative">Cooperative</option>
                                    <option value="other">Other</option>
                                </x-select>
                            </div>
                            <div>
                                <x-input wire:model.live.blur="year" label="Founding Year" type="date" />
                            </div>
                        </div>

                        <div>
                            <x-textarea wire:model.live.blur="mailing_address" label="Full Mailing Address *"
                                placeholder="Enter your organization's complete mailing address" />
                        </div>
                    @break

                    {{-- ───────────── STEP 2: Contact Information ───────────── --}}
                    @case(2)
                        <x-step-header title="Contact Information"
                            subtitle="Provide the details of the primary contact for this application." />

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <x-input wire:model.live.blur="phone" label="Contact Phone Number *"
                                    placeholder="e.g., 713-021-2222" type="tel" />
                            </div>
                            <div>
                                <x-input wire:model.live.blur="contact_person" label="Contact Person *"
                                    placeholder="Enter full name of contact person" />
                            </div>
                        </div>

                        <div>
                            <x-textarea wire:model.live.blur="mission_statement" label="Mission Statement *"
                                placeholder="Provide a brief statement describing your organization's mission" />
                        </div>

                        <div>
                            <x-input wire:model.live.blur="date_corporation" label="Date of Incorporation" type="date" />
                        </div>
                    @break

                    {{-- ───────────── STEP 3: Project Information ───────────── --}}
                    @case(3)
                        <x-step-header title="Project Information"
                            subtitle="Provide details about the project for which you are seeking funding." />

                        <div>
                            <x-input wire:model.live.blur="project_title" label="Project Title *"
                                placeholder="Enter the title of your project" />
                        </div>

                        <div>
                            <x-textarea wire:model.live.blur="project_description" label="Project Description *"
                                placeholder="Describe your project, goals, and expected outcomes" />
                        </div>

                        <div>
                            <x-input wire:model.live.blur="amount" label="Requested Funding Amount *"
                                placeholder="Enter the funding amount requested" type="number" />
                        </div>

                        <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>
                    @break
                @endswitch

                {{-- ───────────── Navigation Buttons ───────────── --}}

                {{-- Navigation --}}
                <div class="flex justify-between pt-6">
                    @if ($currentStep > 1)
                        <x-button type="button" wire:click="previousStep" variant="secondary">
                            Previous
                        </x-button>
                    @endif

                    @if ($currentStep < $totalSteps)
                        <x-button type="button" wire:click="nextStep">
                            Continue
                        </x-button>
                    @else
                        <x-button type="submit" icon="send">
                            Submit Application
                        </x-button>
                    @endif
                </div>

            </form>
        </div>


    </div>

</div>
