@extends('layouts.user')

@section('title', __('expenses.page_title'))
@section('page_title', __('expenses.page_title'))
@section('breadcrumb', __('expenses.breadcrumb'))

@section('content')
@php
    use Carbon\Carbon;

    $money = fn ($value) => number_format((float) $value, 2);

    $locale = app()->getLocale();

    $formatDate = function ($date, $format = 'd M Y') use ($locale) {
        return $date ? Carbon::parse($date)->locale($locale)->translatedFormat($format) : '—';
    };

    $formatTime = function ($date, $format = 'h:i A') use ($locale) {
        return $date ? Carbon::parse($date)->locale($locale)->translatedFormat($format) : '—';
    };

    $monthName = function ($month) use ($locale) {
        return Carbon::createFromDate(now()->year, (int) $month, 1)
            ->locale($locale)
            ->translatedFormat('M');
    };

    $activeChips = [];

    if (request('date')) {
        $activeChips[] = [
            'label' => __('expenses.chips.date'),
            'value' => $formatDate(request('date'), 'd M Y'),
        ];
    }

    if (request('month')) {
        $activeChips[] = [
            'label' => __('expenses.chips.month'),
            'value' => $monthName(request('month')),
        ];
    }

    if (request('year')) {
        $activeChips[] = [
            'label' => __('expenses.chips.year'),
            'value' => request('year'),
        ];
    }

    if (request('expense_category_id')) {
        $activeChips[] = [
            'label' => __('expenses.chips.category'),
            'value' => optional($categories->firstWhere('id', (int) request('expense_category_id')))->name,
        ];
    }

    if (request('user_account_id')) {
        $activeChips[] = [
            'label' => __('expenses.chips.account'),
            'value' => optional($accounts->firstWhere('id', (int) request('user_account_id')))->name,
        ];
    }

    if (request('search')) {
        $activeChips[] = [
            'label' => __('expenses.chips.search'),
            'value' => request('search'),
        ];
    }
@endphp

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

    {{-- Header --}}
    <div class="relative overflow-hidden border border-slate-300 bg-gradient-to-r from-slate-100 via-white to-slate-100 px-4 py-3 shadow-sm">
        <div class="pointer-events-none absolute inset-0">
            <div class="absolute -right-10 -top-10 h-24 w-24 bg-slate-300/30 blur-2xl"></div>
            <div class="absolute bottom-0 left-0 h-14 w-full bg-gradient-to-r from-slate-200/40 via-slate-100/20 to-transparent"></div>
            <div class="absolute -bottom-6 left-1/2 h-20 w-[140%] -translate-x-1/2 border border-slate-300/30 rounded-[100%]"></div>
            <div class="absolute -bottom-10 left-1/2 h-20 w-[120%] -translate-x-1/2 border border-slate-300/20 rounded-[100%]"></div>
        </div>

        <div class="relative z-10 flex flex-wrap items-start justify-between gap-2 sm:items-center">
            <div>
                <h1 class="text-sm font-extrabold text-slate-900">
                    {{ __('expenses.header_title') }}
                </h1>
            </div>

            <div class="flex items-center gap-2">
                <a href="{{ route('user.expenses.create') }}"
                   class="border border-slate-900 bg-slate-900 px-3 py-1.5 text-[11px] font-semibold text-white transition hover:bg-slate-800">
                    {{ __('expenses.add_expense') }}
                </a>

                <a href="{{ route('user.expenses.index') }}"
                   class="border border-slate-300 bg-white/90 px-3 py-1.5 text-[11px] font-semibold text-slate-700 backdrop-blur transition hover:bg-white">
                    {{ __('expenses.reset') }}
                </a>
            </div>
        </div>
    </div>

    {{-- Summary Cards --}}
    <div class="grid grid-cols-1 gap-2 md:grid-cols-4">

        <div class="relative overflow-hidden border border-blue-200 bg-gradient-to-br from-blue-50 via-white to-sky-100/80 px-3 py-2.5 shadow-sm">
            <div class="pointer-events-none absolute inset-0">
                <div class="absolute -right-6 -top-6 h-16 w-16 bg-blue-200/45 blur-2xl"></div>
                <div class="absolute bottom-0 left-8 h-12 w-12 bg-sky-200/35 blur-2xl"></div>
                <div class="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-r from-blue-200/35 via-sky-100/20 to-transparent"></div>
                <div class="absolute -bottom-6 left-1/2 h-16 w-[140%] -translate-x-1/2 border border-blue-300/35 rounded-[100%]"></div>
            </div>
            <div class="relative z-10">
                <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">
                    {{ __('expenses.cards.total_filtered') }}
                </div>
                <div class="mt-1 text-base font-extrabold text-slate-900">{{ $money($totalAmount) }}</div>
                <div class="mt-0.5 text-[10px] text-slate-500">
                    {{ __('expenses.cards.items_count', ['count' => $countItems]) }}
                </div>
            </div>
        </div>

        <div class="relative overflow-hidden border border-emerald-200 bg-gradient-to-br from-emerald-50 via-white to-lime-100/80 px-3 py-2.5 shadow-sm">
            <div class="pointer-events-none absolute inset-0">
                <div class="absolute -right-6 -top-6 h-16 w-16 bg-emerald-200/45 blur-2xl"></div>
                <div class="absolute bottom-0 left-8 h-12 w-12 bg-lime-200/35 blur-2xl"></div>
                <div class="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-r from-emerald-200/35 via-lime-100/20 to-transparent"></div>
                <div class="absolute -bottom-6 left-1/2 h-16 w-[140%] -translate-x-1/2 border border-emerald-300/35 rounded-[100%]"></div>
            </div>
            <div class="relative z-10">
                <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">
                    {{ __('expenses.cards.today') }}
                </div>
                <div class="mt-1 text-base font-extrabold text-slate-900">{{ $money($todayAmount) }}</div>
                <div class="mt-0.5 text-[10px] text-slate-500">{{ now()->locale($locale)->translatedFormat('d M Y') }}</div>
            </div>
        </div>

        <div class="relative overflow-hidden border border-violet-200 bg-gradient-to-br from-violet-50 via-white to-purple-100/80 px-3 py-2.5 shadow-sm">
            <div class="pointer-events-none absolute inset-0">
                <div class="absolute -right-6 -top-6 h-16 w-16 bg-violet-200/45 blur-2xl"></div>
                <div class="absolute bottom-0 left-8 h-12 w-12 bg-purple-200/35 blur-2xl"></div>
                <div class="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-r from-violet-200/35 via-purple-100/20 to-transparent"></div>
                <div class="absolute -bottom-6 left-1/2 h-16 w-[140%] -translate-x-1/2 border border-violet-300/35 rounded-[100%]"></div>
            </div>
            <div class="relative z-10">
                <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">
                    {{ __('expenses.cards.this_month') }}
                </div>
                <div class="mt-1 text-base font-extrabold text-slate-900">{{ $money($monthAmount) }}</div>
                <div class="mt-0.5 text-[10px] text-slate-500">{{ now()->locale($locale)->translatedFormat('F Y') }}</div>
            </div>
        </div>

        <div class="relative overflow-hidden border border-amber-200 bg-gradient-to-br from-amber-50 via-white to-orange-100/80 px-3 py-2.5 shadow-sm">
            <div class="pointer-events-none absolute inset-0">
                <div class="absolute -right-6 -top-6 h-16 w-16 bg-amber-200/45 blur-2xl"></div>
                <div class="absolute bottom-0 left-8 h-12 w-12 bg-orange-200/35 blur-2xl"></div>
                <div class="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-r from-amber-200/35 via-orange-100/20 to-transparent"></div>
                <div class="absolute -bottom-6 left-1/2 h-16 w-[140%] -translate-x-1/2 border border-amber-300/35 rounded-[100%]"></div>
            </div>
            <div class="relative z-10">
                <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">
                    {{ __('expenses.cards.quick') }}
                </div>
                <div class="mt-1.5 flex flex-wrap gap-1.5">
                    <a class="border border-slate-300 bg-white/90 px-2.5 py-1 text-[10px] font-medium text-slate-700 backdrop-blur transition hover:bg-white"
                       href="{{ route('user.expenses.index', array_merge(request()->except('page'), ['date' => now()->toDateString()])) }}">
                        {{ __('expenses.quick.today') }}
                    </a>

                    <a class="border border-slate-300 bg-white/90 px-2.5 py-1 text-[10px] font-medium text-slate-700 backdrop-blur transition hover:bg-white"
                       href="{{ route('user.expenses.index', array_merge(request()->except('page'), ['month' => now()->month, 'year' => now()->year, 'date' => null])) }}">
                        {{ __('expenses.quick.this_month') }}
                    </a>

                    <a class="border border-slate-900 bg-slate-900 px-2.5 py-1 text-[10px] font-medium text-white transition hover:bg-slate-800"
                       href="{{ route('user.expenses.create') }}">
                        {{ __('expenses.quick.new') }}
                    </a>
                </div>
            </div>
        </div>
    </div>

    {{-- Filters --}}
    <div class="relative overflow-hidden border border-slate-300 bg-white px-4 py-3 shadow-sm">
        <div class="pointer-events-none absolute inset-x-0 bottom-0 h-14 bg-gradient-to-r from-slate-100/60 via-white to-slate-100/60"></div>

        <div class="relative z-10 flex flex-wrap items-center justify-between gap-2">
            <div class="text-sm font-bold text-slate-800">{{ __('expenses.filters.title') }}</div>
            <div class="text-[11px] text-slate-500">{{ __('expenses.filters.helper') }}</div>
        </div>

        <form class="relative z-10 mt-3 grid grid-cols-1 gap-2 text-xs md:grid-cols-12"
              method="GET"
              action="{{ route('user.expenses.index') }}">

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.date') }}</label>
                <input class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none"
                       type="date"
                       name="date"
                       value="{{ request('date') }}">
            </div>

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.month') }}</label>
                <select class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none" name="month">
                    <option value="">{{ __('expenses.filters.all') }}</option>
                    @for($mm = 1; $mm <= 12; $mm++)
                        <option value="{{ $mm }}" @selected(request('month') == (string) $mm)>
                            {{ $monthName($mm) }}
                        </option>
                    @endfor
                </select>
            </div>

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.year') }}</label>
                <select class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none" name="year">
                    <option value="">{{ __('expenses.filters.all') }}</option>
                    @for($y = now()->year; $y >= now()->year - 8; $y--)
                        <option value="{{ $y }}" @selected(request('year') == (string) $y)>{{ $y }}</option>
                    @endfor
                </select>
            </div>

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.category') }}</label>
                <select class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none" name="expense_category_id">
                    <option value="">{{ __('expenses.filters.all') }}</option>
                    @foreach($categories as $c)
                        <option value="{{ $c->id }}" @selected(request('expense_category_id') == (string) $c->id)>
                            {{ $c->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.account') }}</label>
                <select class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none" name="user_account_id">
                    <option value="">{{ __('expenses.filters.all') }}</option>
                    @foreach($accounts as $a)
                        <option value="{{ $a->id }}" @selected(request('user_account_id') == (string) $a->id)>
                            {{ $a->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="md:col-span-2">
                <label class="mb-1 block text-[11px] text-slate-500">{{ __('expenses.filters.search') }}</label>
                <input class="w-full border border-slate-300 px-2.5 py-1.5 text-xs focus:border-slate-400 focus:outline-none"
                       type="text"
                       name="search"
                       value="{{ request('search') }}"
                       placeholder="{{ __('expenses.filters.search_placeholder') }}">
            </div>

            <div class="md:col-span-12 flex flex-wrap items-center gap-2 pt-1">
                <button type="submit"
                        class="border border-slate-900 bg-slate-900 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-slate-800">
                    {{ __('expenses.filters.submit') }}
                </button>

                <a class="border border-slate-300 bg-slate-100 px-3 py-1.5 text-xs font-semibold text-slate-700 transition hover:bg-slate-200"
                   href="{{ route('user.expenses.index') }}">
                    {{ __('expenses.reset') }}
                </a>

                @if(count($activeChips))
                    <div class="ml-auto flex flex-wrap gap-1.5">
                        @foreach($activeChips as $chip)
                            @if(!empty($chip['value']))
                                <span class="border border-slate-300 bg-slate-100 px-2 py-1 text-[10px] text-slate-700">
                                    <span class="text-slate-500">{{ $chip['label'] }}:</span>
                                    {{ $chip['value'] }}
                                </span>
                            @endif
                        @endforeach
                    </div>
                @endif
            </div>
        </form>
    </div>

    {{-- Table --}}
    <div class="overflow-hidden border border-slate-300 bg-white shadow-sm">
        <div class="flex items-center justify-between border-b border-slate-300 bg-slate-50 px-4 py-2.5">
            <div class="text-sm font-bold text-slate-800">{{ __('expenses.table.title') }}</div>
            <div class="text-[11px] text-slate-500">
                {{ __('expenses.table.showing', ['count' => $expenses->count(), 'total' => $expenses->total()]) }}
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-xs">
                <thead class="bg-slate-100 text-slate-600">
                    <tr class="border-b border-slate-300 text-left">
                        <th class="px-3 py-2">{{ __('expenses.table.date_time') }}</th>
                        <th class="px-3 py-2">{{ __('expenses.table.trx') }}</th>
                        <th class="px-3 py-2">{{ __('expenses.table.category') }}</th>
                        <th class="px-3 py-2">{{ __('expenses.table.account') }}</th>
                        <th class="px-3 py-2">{{ __('expenses.table.proof') }}</th>
                        <th class="px-3 py-2 text-right">{{ __('expenses.table.amount') }}</th>
                        <th class="px-3 py-2 text-right">{{ __('expenses.table.action') }}</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-slate-200">
                    @forelse($expenses as $e)
                        <tr class="hover:bg-slate-50">
                            <td class="px-3 py-2.5">
                                <div class="font-semibold text-slate-800">{{ $formatDate($e->posted_at, 'd M Y') }}</div>
                                <div class="text-[10px] text-slate-500">{{ $formatTime($e->posted_at, 'h:i A') }}</div>
                            </td>

                            <td class="px-3 py-2.5 font-mono text-[11px] text-slate-700">
                                {{ $e->trx_no }}
                            </td>

                            <td class="px-3 py-2.5">
                                {{ $e->category?->name ?? '—' }}
                            </td>

                            <td class="px-3 py-2.5">
                                {{ $e->account?->name ?? '—' }}
                            </td>

                            <td class="px-3 py-2.5">
                                @if($e->proof_photo)
                                    <a href="{{ asset($e->proof_photo) }}"
                                       target="_blank"
                                       class="inline-flex items-center border border-slate-300 bg-slate-100 px-2.5 py-1 text-[10px] font-semibold text-slate-700 transition hover:bg-slate-200">
                                        {{ __('expenses.table.view_proof') }}
                                    </a>
                                @else
                                    <span class="text-[10px] text-slate-400">—</span>
                                @endif
                            </td>

                            <td class="px-3 py-2.5 text-right font-extrabold text-slate-900">
                                {{ $money($e->amount) }}
                            </td>

                            <td class="whitespace-nowrap px-3 py-2.5 text-right">
                                <a class="inline-flex items-center border border-slate-300 bg-slate-100 px-2.5 py-1 text-[10px] font-semibold text-slate-700 transition hover:bg-slate-200"
                                   href="{{ route('user.expenses.edit', $e) }}">
                                    {{ __('expenses.actions.edit') }}
                                </a>

                                <form class="js-del inline" method="POST" action="{{ route('user.expenses.destroy', $e) }}">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit"
                                            class="ml-1 inline-flex items-center border border-rose-200 bg-rose-50 px-2.5 py-1 text-[10px] font-semibold text-rose-700 transition hover:bg-rose-100">
                                        {{ __('expenses.actions.delete') }}
                                    </button>
                                </form>
                            </td>
                        </tr>

                        @if($e->note)
                            <tr class="bg-white">
                                <td colspan="7" class="px-3 py-2 text-[11px] text-slate-600">
                                    <span class="font-semibold">{{ __('expenses.note_label') }}</span>
                                    {{ $e->note }}
                                </td>
                            </tr>
                        @endif
                    @empty
                        <tr>
                            <td colspan="7" class="py-12 text-center text-slate-500">
                                <div class="text-sm font-semibold text-slate-800">{{ __('expenses.empty.title') }}</div>
                                <div class="mt-1 text-xs">{{ __('expenses.empty.subtitle') }}</div>

                                <a href="{{ route('user.expenses.create') }}"
                                   class="mt-3 inline-block border border-slate-900 bg-slate-900 px-3 py-1.5 text-xs text-white transition hover:bg-slate-800">
                                    {{ __('expenses.add_expense') }}
                                </a>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="px-4 py-3">
            {{ $expenses->links() }}
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('form.js-del').forEach(form => {
        form.addEventListener('submit', (e) => {
            if (typeof Swal === 'undefined') return;

            e.preventDefault();

            Swal.fire({
                title: @json(__('expenses.swal.delete_title')),
                text: @json(__('expenses.swal.delete_text')),
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: @json(__('expenses.swal.confirm_delete')),
                cancelButtonText: @json(__('expenses.swal.cancel')),
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });
        });
    });
});
</script>
@endsection