<?php

use Livewire\Component;
use App\Models\Loan;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;
use Livewire\Attributes\Computed;
use App\Traits\WithTableHelpers;
use App\Services\LoanHandler;
use Livewire\Attributes\On;

new #[Layout('layouts::base')] class extends Component {
    public Loan $loan;
    use WithPagination, WithTableHelpers;
    public string $currencySymbol = '$';
    public array $currencies = [];
    public $perPage = 10;
    public int $page = 1;
    public string $installmentSearch = '';

    protected function loanSearchableFields(): array
    {
        return ['id', 'user.name', 'user.email', 'amount', 'total_interest', 'status', 'created_at', 'first_due_date'];
    }

    public function mount(Loan $loan)
    {
        $this->loan = $loan;
        $profileCurrency = $loan->account?->profile?->currency ?? 'USD';
        $this->currencySymbol = \App\Support\Currency::symbol($profileCurrency);

        $this->loadCurrencies();
    }
    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }
    #[On('refreshLoans')]
    #[Computed]
    public function loans()
    {
        $query = Loan::query()
            ->with(['account.profile.user'])
            ->where('account_id', $this->loan->account_id)
            ->where('id', '!=', $this->loan->id);

        $this->applySearch($query, $this->loanSearchableFields());

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }

    #[Computed]
    public function installments()
    {
        $query = $this->loan->installments();

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }

    public function loadCurrencies(): void
    {
        $this->currencies = \Illuminate\Support\Facades\Cache::rememberForever('currencies_json', function () {
            return collect(json_decode(file_get_contents(resource_path('data/currencies.json')), true))
                ->sortBy('name')
                ->values()
                ->toArray();
        });
    }

    public function approveLoan(Loan $loan): void
    {
        try {
            // Resolve the LoanHandler service only when needed
            app(abstract: LoanHandler::class)->approve($loan);

            // Notify user
            $this->dispatch('showToast', message: 'Loan approved successfully!', type: 'success');

            // Optional: refresh loans table if you have one
            $this->dispatch('refreshLoans');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function rejectLoan(Loan $loan, string $reason = 'Loan rejected'): void
    {
        try {
            // Resolve service and reject loan
            app(abstract: LoanHandler::class)->rejectLoan($loan, $reason);

            // Notify user
            $this->dispatch('showToast', message: 'Loan rejected successfully!', type: 'success');

            // Optional: refresh loans table if you have one
            $this->dispatch('refreshLoans');
        } catch (\Exception $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }

    public function markInstallmentPaid($installmentId)
    {
        try {
            app(LoanHandler::class)->markAsPaid($installmentId);

            $this->loan->refresh();

            $this->dispatch('showToast', message: 'Installment marked as paid', type: 'success');
            $this->dispatch('refreshLoans');
        } catch (\Throwable $e) {
            $this->dispatch('showToast', message: $e->getMessage(), type: 'error');
        }
    }
};
?>

<div class="space-y-8 py-6">

    {{-- Page Header --}}
    <x-page-header title="Loan #{{ $loan->id }}" subtitle="Approve or review loan details" rightText="Back to List"
        back-url="{{ route('admin.loans.index') }}" />


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

        {{-- ================= Loan Summary (Hero Section) ================= --}}
        <div
            class="bg-linear-to-r from-sky-500 to-purple-500 text-white rounded-2xl shadow-lg p-6 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div>
                <h2 class="text-2xl font-bold">Loan #{{ $loan->id }}</h2>
                <div class="flex justify-between mt-2">
                    <span>Status:</span>
                    @php
                        $statusClasses = match ($loan->status) {
                            'approved' => 'bg-green-100 text-green-800',
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'rejected' => 'bg-red-100 text-red-800',
                            'overdue' => 'bg-red-200 text-red-900',
                            'completed' => 'bg-blue-100 text-blue-800',
                            'defaulted' => 'bg-gray-200 text-gray-800',
                            default => 'bg-gray-100 text-gray-700',
                        };
                        $statusText = ucfirst($loan->status);
                    @endphp

                    <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses }}">
                        {{ $statusText }}
                    </span>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row items-center sm:space-x-6 gap-2">
                <div class="text-center sm:text-right">
                    <p class="text-xl font-bold">
                        {{ $loan->account ? \App\Support\Currency::symbol($loan->account->profile->currency) . number_format($loan->amount, 2) : '-' }}
                    </p>
                    <p class="text-sm opacity-80">Principal Amount</p>
                </div>

                @if ($loan->status === 'pending')
                    <div class="flex space-x-2">
                        <x-flux::button wire:click="approveLoan({{ $loan->id }})" variant="primary" color="green">
                            Approve
                        </x-flux::button>
                        <x-flux::button wire:click="rejectLoan({{ $loan->id }})" variant="danger">
                            Reject
                        </x-flux::button>
                    </div>
                @endif
            </div>
        </div>

        {{-- ================= Main Content: Left + Right Columns ================= --}}
        <div class="grid grid-cols-1 md:grid-cols-3 lg:space-x-6">

            {{-- ================= Left Column: Loan Details & Installments ================= --}}
            <div class="md:col-span-2 space-y-6">

                {{-- Loan Details Cards --}}
                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">
                    <x-transaction-card icon="flux::icon.currency-dollar" bgColor="bg-sky-100"
                        darkBgColor="dark:bg-sky-800" textColor="text-sky-600" darkTextColor="dark:text-sky-300"
                        label="Amount" value="{{ number_format($loan->amount, 2) }}" />

                    <x-transaction-card icon="flux::icon.percent-badge" bgColor="bg-red-100"
                        darkBgColor="dark:bg-red-800" textColor="text-red-600" darkTextColor="dark:text-red-300"
                        label="Total Interest" value="{{ number_format($loan->total_interest, 2) }}" />

                    <x-transaction-card icon="flux::icon.banknotes" bgColor="bg-green-100"
                        darkBgColor="dark:bg-green-800" textColor="text-green-600" darkTextColor="dark:text-green-300"
                        label="Total Repayment" value="{{ number_format($loan->total_repayment, 2) }}" />

                    <x-transaction-card icon="flux::icon.calendar" bgColor="bg-yellow-100"
                        darkBgColor="dark:bg-yellow-800" textColor="text-yellow-600"
                        darkTextColor="dark:text-yellow-300" label="First Due"
                        value="{{ $loan->first_due_date?->format('d M Y') ?? '-' }}" />
                </div>

                {{-- More Loan Info --}}
                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 grid grid-cols-2 sm:grid-cols-4 gap-6">
                    <x-transaction-card icon="flux::icon.clock" bgColor="bg-indigo-100" darkBgColor="dark:bg-indigo-800"
                        textColor="text-indigo-600" darkTextColor="dark:text-indigo-300" label="Duration (months)"
                        value="{{ $loan->duration }}" />

                    <x-transaction-card icon="flux::icon.document-text" bgColor="bg-purple-100"
                        darkBgColor="dark:bg-purple-800" textColor="text-purple-600"
                        darkTextColor="dark:text-purple-300" label="Purpose" value="{{ $loan->purpose ?? 'N/A' }}" />

                    <x-transaction-card icon="flux::icon.percent-badge" bgColor="bg-teal-100"
                        darkBgColor="dark:bg-teal-800" textColor="text-teal-600" darkTextColor="dark:text-teal-300"
                        label="Monthly Repayment" value="{{ number_format($loan->monthly_repayment, 2) }}" />

                    <x-transaction-card icon="flux::icon.calendar-days" bgColor="bg-pink-100"
                        darkBgColor="dark:bg-pink-800" textColor="text-pink-600" darkTextColor="dark:text-pink-300"
                        label="Last Due" value="{{ $loan->last_due_date?->format('d M Y') ?? '-' }}" />
                </div>


                {{-- Loan Timestamps --}}
                <div class="text-sm text-gray-600 dark:text-gray-400">
                    <div class="bg-gray-100 dark:bg-gray-900 p-4 rounded-xl shadow-sm">
                        <p class="font-medium">Last Updated</p>
                        <p>{{ $loan->updated_at->toDayDateTimeString() }}</p>
                    </div>
                </div>

            </div>

            {{-- ================= Right Column: Borrower Profile ================= --}}
            <div class="md:col-span-1 mt-6 lg:mt-0 space-y-6 sticky top-6">
                @php
                    $user = $loan->account->profile->user ?? null;
                    $avatar = $loan->account->profile->profile_photo
                        ? Storage::disk('public')->url($loan->account->profile->profile_photo)
                        : null;
                @endphp

                <div
                    class="bg-white/30 dark:bg-gray-800/30 backdrop-blur-md rounded-xl shadow-lg p-6 flex flex-col items-center text-center space-y-4">
                    <div
                        class="w-28 h-28 rounded-full overflow-hidden border-4 border-sky-500 flex items-center justify-center text-4xl font-semibold bg-gray-300 dark:bg-gray-700">
                        @if ($avatar)
                            <img src="{{ $avatar }}" alt="User Avatar" class="w-full h-full object-cover">
                        @else
                            {{ strtoupper(substr($user->name ?? 'N/A', 0, 1)) }}
                        @endif
                    </div>

                    <h4 class="font-bold text-lg text-gray-900 dark:text-white">{{ $user->name ?? 'N/A' }}</h4>
                    <p class="text-gray-500 dark:text-gray-400 lowercase">{{ $user->email ?? 'N/A' }}</p>
                    <span
                        class="px-3 py-1 bg-sky-100 dark:bg-sky-700 text-sky-800 dark:text-white rounded-full text-sm font-medium">
                        KYC: {{ ucfirst($user->kyc_status ?? 'N/A') }}
                    </span>

                    <a href="{{ route('admin.users.show', $user) }}"
                        class="mt-3 px-5 py-2 bg-sky-600 hover:bg-sky-700 text-white font-semibold rounded-lg transition">
                        View Profile
                    </a>
                </div>
            </div>

        </div>

        <x-page-header title="Loan Installments Payment" subtitle="Overview of all payment for the above loan.">
        </x-page-header>
        <x-table.wrapper :items="$this->installments">

            {{-- ================= HEADERS ================= --}}
            <x-slot name="head">
                <x-table.head label="#" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Due Date" field="due_date" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Principal" field="principal" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Interest" field="interest" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Penalty" field="penalty" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Total" field="total" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Paid At" field="paid_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Action" />
            </x-slot>

            {{-- ================= DESKTOP ================= --}}
            <x-slot name="body">
                @forelse ($this->installments as $inst)
                    @php
                        // Auto Status Color Detection
                        $statusClasses = match ($inst->status) {
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'overdue' => 'bg-red-200 text-red-900',
                            'paid' => 'bg-green-100 text-green-800',
                            default => 'bg-gray-100 text-gray-700',
                        };

                        // Highlight overdue entire row
                        $rowHighlight = $inst->status === 'overdue' ? 'bg-red-50 dark:bg-red-900/30' : '';
                    @endphp

                    <x-table.row wire:key="installment-{{ $inst->id }}"
                        class="{{ $rowHighlight }} hover:shadow-md transition">

                        <x-table.cell>
                            {{ $inst->installment_number }}
                        </x-table.cell>

                        <x-table.cell>
                            {{ $inst->due_date?->format('d M Y') ?? '-' }}
                        </x-table.cell>

                        <x-table.cell>
                            {{ $currencySymbol }}{{ number_format($inst->principal, 2) }}
                        </x-table.cell>

                        <x-table.cell>
                            {{ $currencySymbol }}{{ number_format($inst->interest, 2) }}
                        </x-table.cell>

                        <x-table.cell>
                            {{ $currencySymbol }}{{ number_format($inst->penalty, 2) }}
                        </x-table.cell>

                        <x-table.cell class="font-semibold">
                            {{ $currencySymbol }}{{ number_format($inst->total, 2) }}
                        </x-table.cell>

                        <x-table.cell>
                            <span class="px-2 py-1 rounded-full text-xs font-medium {{ $statusClasses }}">
                                {{ ucfirst($inst->status) }}
                            </span>
                        </x-table.cell>

                        <x-table.cell>
                            {{ $inst->paid_at?->format('d M Y H:i') ?? '-' }}
                        </x-table.cell>

                        <x-table.cell>
                            @if ($inst->status === 'pending')
                                <x-flux::button type="button" variant="primary"
                                    wire:click="markInstallmentPaid({{ $inst->id }})" size="xs"
                                    color="green">
                                    Mark Paid
                                </x-flux::button>
                            @else
                                —
                            @endif
                        </x-table.cell>

                    </x-table.row>

                @empty
                    <tr>
                        <td colspan="9" class="px-6 py-8 text-center text-gray-400 dark:text-gray-500">
                            No installments found
                        </td>
                    </tr>
                @endforelse
            </x-slot>

            {{-- ================= MOBILE VERSION ================= --}}
            <x-slot name="mobile">
                @forelse ($this->installments as $inst)
                    @php
                        $statusClasses = match ($inst->status) {
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'overdue' => 'bg-red-200 text-red-900',
                            'paid' => 'bg-green-100 text-green-800',
                            default => 'bg-gray-100 text-gray-700',
                        };

                        $cardHighlight =
                            $inst->status === 'overdue' ? 'border-red-400 bg-red-50 dark:bg-red-900/30' : '';
                    @endphp

                    <x-table.mobile-card wire:key="mobile-installment-{{ $inst->id }}"
                        class="rounded-xl shadow-md p-4 mb-4 {{ $cardHighlight }}">

                        <div class="space-y-2 text-sm text-gray-700 dark:text-gray-300">

                            <div><strong>#:</strong> {{ $inst->installment_number }}</div>
                            <div><strong>Due:</strong> {{ $inst->due_date?->format('d M Y') ?? '-' }}</div>

                            <div><strong>Principal:</strong>
                                {{ $currencySymbol }}{{ number_format($inst->principal, 2) }}
                            </div>

                            <div><strong>Interest:</strong>
                                {{ $currencySymbol }}{{ number_format($inst->interest, 2) }}
                            </div>

                            <div><strong>Penalty:</strong>
                                {{ $currencySymbol }}{{ number_format($inst->penalty, 2) }}
                            </div>

                            <div class="font-semibold">
                                <strong>Total:</strong>
                                {{ $currencySymbol }}{{ number_format($inst->total, 2) }}
                            </div>

                            <div>
                                <strong>Status:</strong>
                                <span
                                    class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium {{ $statusClasses }}">
                                    {{ ucfirst($inst->status) }}
                                </span>
                            </div>

                            <div>
                                <strong>Paid At:</strong>
                                {{ $inst->paid_at?->format('d M Y H:i') ?? '-' }}
                            </div>

                        </div>

                        @if ($inst->status === 'pending')
                            <div class="mt-3">
                                <x-flux::button type="button" variant="primary"
                                    wire:click="markInstallmentPaid({{ $inst->id }})" size="sm"
                                    color="green">
                                    Mark Paid
                                </x-flux::button>
                            </div>
                        @endif

                    </x-table.mobile-card>

                @empty
                    <div class="px-6 py-6 text-center text-gray-400 dark:text-gray-500">
                        No installments found
                    </div>
                @endforelse
            </x-slot>

            {{-- Footer (pagination + perPage dropdown) --}}
            <x-slot name="footer">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4 mt-6">
                    <div class="w-full md:w-auto text-center">{{ $this->loans->links() }}</div>
                </div>
            </x-slot>
        </x-table.wrapper>


        <x-page-header title="Other Loans"
            subtitle="Overview of all user loans, their statuses, interest, repayment details, and transaction history made by user.">
        </x-page-header>

        <x-table.wrapper :items="$this->loans">

            {{-- SEARCH --}}
            <x-slot name="search">
                <div class="flex items-center justify-between gap-4">
                    <div class="w-full md:w-1/3">
                        <div class="relative">
                            <x-flux::icon.magnifying-glass
                                class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 dark:text-gray-500" />
                            <input type="text" wire:model.live="search" placeholder="Search by name or email"
                                class="w-full pl-10 pr-4 py-2 text-sm rounded-md bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-600 focus:border-sky-600 transition" />
                        </div>
                    </div>
                </div>
            </x-slot>

            {{-- HEADERS --}}
            <x-slot name="head">
                <x-table.head label="Loan ID" field="id" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="User" />
                <x-table.head label="Amount" field="amount" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Interest" field="total_interest" sortable :sortField="$sortField"
                    :sortDirection="$sortDirection" />
                <x-table.head label="Created" field="created_at" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="First Due" field="first_due_date" sortable :sortField="$sortField"
                    :sortDirection="$sortDirection" />
                <x-table.head label="Status" field="status" sortable :sortField="$sortField" :sortDirection="$sortDirection" />
                <x-table.head label="Action" />
            </x-slot>

            {{-- BODY (DESKTOP) --}}
            <x-slot name="body">
                @forelse ($this->loans as $loan)
                    @php
                        $user = $loan->user;
                        $account = $loan->account;
                        $profile = $account?->profile;
                        $statusClasses = match ($loan->status) {
                            'approved' => 'bg-green-500 text-white',
                            'pending' => 'bg-yellow-400 text-black',
                            'rejected' => 'bg-red-500 text-white',
                            'overdue' => 'bg-red-600 text-white',
                            'completed' => 'bg-blue-500 text-white',
                            'defaulted' => 'bg-gray-500 text-white',
                            default => 'bg-gray-300 text-black',
                        };
                    @endphp

                    <x-table.row wire:key="row-{{ $loan->id }}"
                        class="hover:shadow-lg transition-shadow duration-200 rounded-lg mb-2">

                        {{-- Loan ID --}}
                        <x-table.cell>{{ $loan->id ?? '_' }}</x-table.cell>

                        {{-- User --}}
                        <x-table.cell>
                            <a href="{{ route('admin.users.show', $user) }}"
                                class="text-sm font-medium hover:underline">
                                {{ $user->name }} ({{ $user->email }})
                            </a>
                        </x-table.cell>

                        {{-- Amount --}}
                        <x-table.cell>{{ $currencySymbol }}{{ number_format($loan->amount, 2) }}</x-table.cell>

                        {{-- Interest --}}
                        <x-table.cell>{{ $currencySymbol }}{{ number_format($loan->total_interest, 2) }}</x-table.cell>

                        {{-- Created date --}}
                        <x-table.cell>{{ $loan->created_at?->format('d M Y') ?? '-' }}</x-table.cell>

                        {{-- First Due --}}
                        <x-table.cell>{{ $loan->first_due_date?->format('d M Y') ?? '-' }}</x-table.cell>

                        {{-- Status --}}
                        <x-table.cell>
                            <span class="px-2 py-1 rounded-full text-xs {{ $statusClasses }}">
                                {{ ucfirst($loan->status) }}
                            </span>
                        </x-table.cell>

                        {{-- Actions --}}
                        <x-table.cell>
                            <a href="{{ route('admin.loans.show', $loan) }}"
                                class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition">
                                View
                            </a>
                        </x-table.cell>

                    </x-table.row>
                @empty
                    <tr>
                        <td colspan="8" class="px-6 py-10 text-center text-gray-400 dark:text-gray-500">
                            No loans found
                        </td>
                    </tr>
                @endforelse
            </x-slot>

            {{-- MOBILE --}}
            <x-slot name="mobile">
                @forelse ($this->loans as $loan)
                    @php
                        $user = $loan->user;
                        $account = $loan->account;
                        $profile = $account?->profile;

                        $statusClasses = match ($loan->status) {
                            'approved' => 'bg-green-100 text-green-800',
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'rejected' => 'bg-red-100 text-red-800',
                            'overdue' => 'bg-red-200 text-red-900',
                            'completed' => 'bg-blue-100 text-blue-800',
                            'defaulted' => 'bg-gray-200 text-gray-800',
                            default => 'bg-gray-100 text-gray-700',
                        };
                    @endphp

                    <x-table.mobile-card class="rounded-xl shadow-md p-4 mb-4 hover:shadow-xl transition duration-200">

                        <div class="flex flex-col text-sm text-gray-700 dark:text-gray-300 space-y-1">
                            <div><strong>Loan ID:</strong> {{ $loan->id ?? '_' }}</div>
                            <div><strong>User:</strong> {{ $user->name }} ({{ $user->email }})</div>
                            <div><strong>Amount:</strong> {{ $currencySymbol }}{{ number_format($loan->amount, 2) }}
                            </div>
                            <div><strong>Interest:</strong>
                                {{ $currencySymbol }}{{ number_format($loan->total_interest, 2) }}</div>
                            <div><strong>Created:</strong> {{ $loan->created_at?->format('d M Y') ?? '-' }}</div>
                            <div><strong>First Due:</strong> {{ $loan->first_due_date?->format('d M Y') ?? '-' }}</div>
                            <div><strong>Status:</strong>
                                <span
                                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses }}">
                                    {{ ucfirst($loan->status) }}
                                </span>
                            </div>
                        </div>

                        <div class="mt-3 flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0">
                            <a href="{{ route('admin.loans.show', $loan) }}"
                                class="flex-1 inline-flex items-center justify-center px-4 py-2 text-sm font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition">
                                View
                            </a>

                        </div>

                    </x-table.mobile-card>
                @empty
                    <div class="px-6 py-6 text-center text-gray-400 dark:text-gray-500">
                        No loans found
                    </div>
                @endforelse
            </x-slot>

            {{-- FOOTER / PAGINATION --}}
            <x-slot name="footer">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4 mt-6">
                    <div class="w-full md:w-auto text-center">{{ $this->loans->links() }}</div>
                </div>
            </x-slot>

        </x-table.wrapper>
    </div>

</div>
