@extends('layouts.app', [
    'pageTitle' => $title,
])

@section('content')
@php
    $purchaseCollection = $purchases->getCollection();

    $summaryTotal = $purchaseCollection->sum('total_price');
    $summaryPaid = $purchaseCollection->sum(function ($item) {
        return $item->paid_amount ?? 0;
    });
    $summaryRemaining = $purchaseCollection->sum(function ($item) {
        return $item->remaining ?? 0;
    });

    $countPaid = $purchaseCollection->where('payment_status', 'paid')->count();
    $countPartial = $purchaseCollection->where('payment_status', 'partial')->count();
    $countUnpaid = $purchaseCollection->where('payment_status', 'unpaid')->count();

    $totalRows = $purchaseCollection->count();
@endphp

<div class="space-y-6">
    {{-- Hero Header --}}
    <div class="relative overflow-hidden rounded-3xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="absolute right-0 top-0 h-40 w-40 rounded-full bg-brand-100/60 blur-3xl dark:bg-brand-500/10"></div>
        <div class="absolute bottom-0 left-0 h-32 w-32 rounded-full bg-success-100/60 blur-3xl dark:bg-success-500/10"></div>

        <div class="relative flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
            <div>
                <div class="mb-2 inline-flex items-center gap-2 rounded-full border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-medium text-brand-700 dark:border-brand-500/20 dark:bg-brand-500/10 dark:text-brand-400">
                    <span class="inline-block h-2 w-2 rounded-full bg-brand-500"></span>
                    Purchase Intelligence
                </div>
                <h2 class="text-2xl font-semibold tracking-tight text-gray-900 dark:text-white">
                    {{ $title }}
                </h2>
                <p class="mt-2 max-w-2xl text-sm text-gray-500 dark:text-gray-400">
                    Monitor pembelian bahan, progres pembayaran, dan sisa hutang supplier dalam satu tampilan yang lebih ringkas dan cepat dibaca.
                </p>
            </div>

            <div class="flex flex-wrap items-center gap-3">
                <a href="{{ route('purchases.create') }}"
                   class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-4 py-3 text-sm font-medium text-white shadow-theme-xs hover:bg-brand-600">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Tambah Pembelian
                </a>
            </div>
        </div>
    </div>

    @include('partials.alerts')

    {{-- KPI Cards --}}
    <div class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Total Pembelian</p>
                    <h3 class="mt-2 text-2xl font-semibold text-gray-900 dark:text-white">
                        {{ number_format($totalRows, 0, ',', '.') }}
                    </h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Data pada halaman ini</p>
                </div>
                <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10"/>
                    </svg>
                </div>
            </div>
        </div>

        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Nilai Pembelian</p>
                    <h3 class="mt-2 text-2xl font-semibold text-gray-900 dark:text-white">
                        Rp {{ number_format($summaryTotal, 0, ',', '.') }}
                    </h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Akumulasi total tagihan</p>
                </div>
                <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-primary-50 text-primary-600 dark:bg-blue-500/10 dark:text-blue-400">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-3.314 0-6 1.79-6 4s2.686 4 6 4 6-1.79 6-4-2.686-4-6-4zm0 0V4m0 12v4"/>
                    </svg>
                </div>
            </div>
        </div>

        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Sudah Dibayar</p>
                    <h3 class="mt-2 text-2xl font-semibold text-success-600 dark:text-success-400">
                        Rp {{ number_format($summaryPaid, 0, ',', '.') }}
                    </h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ $countPaid }} lunas, {{ $countPartial }} sebagian</p>
                </div>
                <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-success-50 text-success-600 dark:bg-success-500/10 dark:text-success-400">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                    </svg>
                </div>
            </div>
        </div>

        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Sisa Hutang</p>
                    <h3 class="mt-2 text-2xl font-semibold text-error-600 dark:text-error-400">
                        Rp {{ number_format($summaryRemaining, 0, ',', '.') }}
                    </h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ $countUnpaid }} belum dibayar</p>
                </div>
                <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-error-50 text-error-600 dark:bg-error-500/10 dark:text-error-400">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
            </div>
        </div>
    </div>

    {{-- Filter Panel --}}
    <div class="rounded-3xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <h3 class="text-base font-semibold text-gray-900 dark:text-white">Filter & Segmentasi</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">Persempit data pembelian berdasarkan bahan, tipe, status, dan rentang tanggal.</p>
            </div>

            @if(request()->filled('material_id') || request()->filled('type') || request()->filled('payment_status') || request()->filled('date_from') || request()->filled('date_to'))
                <div class="inline-flex items-center gap-2 rounded-full bg-warning-50 px-3 py-1 text-xs font-medium text-warning-700 dark:bg-warning-500/10 dark:text-warning-400">
                    Filter aktif
                </div>
            @endif
        </div>

        <form action="{{ route('purchases.index') }}" method="GET" class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-6">
            <div class="xl:col-span-1">
                <x-form.select name="material_id" placeholder="Semua Bahan">
                    @foreach($materials as $material)
                        <option value="{{ $material->id }}" {{ request('material_id') == $material->id ? 'selected' : '' }}>
                            {{ $material->name }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div class="xl:col-span-1">
                <x-form.select name="type" placeholder="Semua Tipe">
                    @foreach($types as $key => $label)
                        <option value="{{ $key }}" {{ request('type') == $key ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div class="xl:col-span-1">
                <x-form.select name="payment_status" placeholder="Semua Status">
                    @foreach($paymentStatuses as $key => $label)
                        <option value="{{ $key }}" {{ request('payment_status') == $key ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div class="xl:col-span-1">
                <x-form.date-picker name="date_from" :defaultDate="request('date_from')" placeholder="Dari Tanggal"/>
            </div>

            <div class="xl:col-span-1">
                <x-form.date-picker name="date_to" :defaultDate="request('date_to')" placeholder="Sampai Tanggal"/>
            </div>

            <div class="flex items-end gap-3 xl:col-span-1">
                <button type="submit" class="inline-flex flex-1 items-center justify-center gap-2 rounded-xl bg-gray-900 px-4 py-2.5 text-sm font-medium text-white hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-200">
                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2l-7 7v5l-4 2v-7L3 6V4z"/>
                    </svg>
                    Filter
                </button>

                <a href="{{ route('purchases.index') }}" class="inline-flex items-center justify-center rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">
                    Reset
                </a>
            </div>
        </form>
    </div>

    {{-- Purchase Feed --}}
    <div class="rounded-3xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-100 px-5 py-4 dark:border-gray-800">
            <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h3 class="text-base font-semibold text-gray-900 dark:text-white">Daftar Pembelian</h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Tampilan ringkas dengan progress pembayaran dan prioritas hutang.
                    </p>
                </div>
                <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ number_format($purchases->total(), 0, ',', '.') }} total data
                </div>
            </div>
        </div>

        <div class="p-5">
            @forelse($purchases as $purchase)
                @php
                    $progress = ($purchase->total_price ?? 0) > 0
                        ? min(100, (($purchase->paid_amount ?? 0) / $purchase->total_price) * 100)
                        : 0;

                    $statusClasses = match($purchase->payment_status) {
                        'paid' => 'bg-success-100 text-success-700 dark:bg-success-500/15 dark:text-success-400',
                        'partial' => 'bg-warning-100 text-warning-700 dark:bg-warning-500/15 dark:text-warning-400',
                        default => 'bg-error-100 text-error-700 dark:bg-error-500/15 dark:text-error-400',
                    };

                    $statusLabel = match($purchase->payment_status) {
                        'paid' => 'Lunas',
                        'partial' => 'Sebagian',
                        default => 'Belum Bayar',
                    };
                @endphp

                <div class="group mb-4 rounded-2xl border border-gray-200 bg-gray-50/60 p-4 transition hover:border-brand-300 hover:bg-white dark:border-gray-800 dark:bg-gray-900/30 dark:hover:border-brand-500/30 dark:hover:bg-white/[0.02]">
                    <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                        <div class="min-w-0 flex-1">
                            <div class="mb-3 flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                                <div class="min-w-0">
                                    <div class="mb-2 flex flex-wrap items-center gap-2">
                                        <span class="inline-flex rounded-full px-2.5 py-1 text-xs font-medium {{ $statusClasses }}">
                                            {{ $statusLabel }}
                                        </span>

                                        @if($purchase->hasDebt())
                                            <span class="inline-flex rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-500/10 dark:text-brand-400">
                                                Perlu Tindak Lanjut
                                            </span>
                                        @endif
                                    </div>

                                    <h4 class="truncate text-base font-semibold text-gray-900 dark:text-white">
                                        {{ $purchase->material->name ?? '-' }}
                                    </h4>

                                    <div class="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-gray-500 dark:text-gray-400">
                                        <span>{{ $purchase->purchase_date->translatedFormat('d F Y') }}</span>
                                        <span>•</span>
                                        <span>{{ $purchase->type_label ?? '-' }}</span>
                                        <span>•</span>
                                        <span>{{ $purchase->supplierRelation->name ?? $purchase->supplier ?? '-' }}</span>
                                    </div>
                                </div>

                                <div class="shrink-0 text-left md:text-right">
                                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Total Tagihan</p>
                                    <p class="text-lg font-semibold text-gray-900 dark:text-white">
                                        {{ $purchase->formatted_total }}
                                    </p>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 gap-3 md:grid-cols-3">
                                <div class="rounded-2xl border border-gray-200 bg-white px-4 py-3 dark:border-gray-800 dark:bg-white/[0.02]">
                                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Sudah Dibayar</p>
                                    <p class="mt-1 text-sm font-semibold text-success-600 dark:text-success-400">
                                        {{ $purchase->formatted_paid }}
                                    </p>
                                </div>

                                <div class="rounded-2xl border border-gray-200 bg-white px-4 py-3 dark:border-gray-800 dark:bg-white/[0.02]">
                                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Sisa Hutang</p>
                                    <p class="mt-1 text-sm font-semibold {{ ($purchase->remaining ?? 0) > 0 ? 'text-error-600 dark:text-error-400' : 'text-gray-900 dark:text-white' }}">
                                        {{ $purchase->formatted_remaining }}
                                    </p>
                                </div>

                                <div class="rounded-2xl border border-gray-200 bg-white px-4 py-3 dark:border-gray-800 dark:bg-white/[0.02]">
                                    <p class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Progres Pembayaran</p>
                                    <p class="mt-1 text-sm font-semibold text-brand-600 dark:text-brand-400">
                                        {{ number_format($progress, 0) }}%
                                    </p>
                                </div>
                            </div>

                            <div class="mt-4">
                                <div class="mb-2 flex items-center justify-between">
                                    <span class="text-xs font-medium text-gray-500 dark:text-gray-400">Payment Progress</span>
                                    <span class="text-xs font-semibold text-gray-700 dark:text-gray-300">{{ number_format($progress, 0) }}%</span>
                                </div>
                                <div class="h-2.5 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-gray-800">
                                    <div
                                        class="h-full rounded-full transition-all duration-500 {{ $purchase->payment_status === 'paid' ? 'bg-success-500' : ($purchase->payment_status === 'partial' ? 'bg-warning-500' : 'bg-error-500') }}"
                                        style="width: {{ $progress }}%"
                                    ></div>
                                </div>
                            </div>
                        </div>

                        <div class="flex shrink-0 flex-wrap items-center gap-2 xl:w-[220px] xl:flex-col xl:items-stretch">
                            <a href="{{ route('purchases.show', $purchase) }}"
                               class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                                <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12H9m12 0A9 9 0 113 12a9 9 0 0118 0z"/>
                                </svg>
                                Lihat Detail
                            </a>

                            @if($purchase->hasDebt())
                                <a href="{{ route('purchases.show', $purchase) }}"
                                   class="inline-flex items-center justify-center gap-2 rounded-xl border border-warning-300 bg-warning-50 px-4 py-2.5 text-sm font-medium text-warning-700 hover:bg-warning-100 dark:border-warning-500/20 dark:bg-warning-500/10 dark:text-warning-400">
                                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a5 5 0 00-10 0v2m-2 0h14l-1 11H6L5 9z"/>
                                    </svg>
                                    Bayar Hutang
                                </a>
                            @endif

                            <button
                                @click="$dispatch('open-delete-modal', { action: '{{ route('purchases.destroy', $purchase) }}', title: 'Hapus Pembelian?', description: 'Hapus pembelian ini? Stok akan dikurangi.' })"
                                type="button"
                                class="inline-flex items-center justify-center gap-2 rounded-xl border border-error-300 bg-error-50 px-4 py-2.5 text-sm font-medium text-error-700 hover:bg-error-100 dark:border-error-500/20 dark:bg-error-500/10 dark:text-error-400"
                            >
                                <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3M4 7h16"/>
                                </svg>
                                Hapus
                            </button>
                        </div>
                    </div>
                </div>
            @empty
                <div class="flex flex-col items-center justify-center rounded-2xl border border-dashed border-gray-300 px-6 py-16 text-center dark:border-gray-700">
                    <div class="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400">
                        <svg class="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10"/>
                        </svg>
                    </div>
                    <h4 class="text-base font-semibold text-gray-900 dark:text-white">Belum ada data pembelian</h4>
                    <p class="mt-2 max-w-md text-sm text-gray-500 dark:text-gray-400">
                        Data pembelian belum tersedia untuk filter yang dipilih. Tambahkan pembelian baru atau ubah filter pencarian.
                    </p>
                    <a href="{{ route('purchases.create') }}"
                       class="mt-5 inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                        <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                        </svg>
                        Tambah Pembelian
                    </a>
                </div>
            @endforelse
        </div>
    </div>

    {{-- Pagination --}}
    @if($purchases->hasPages())
        <div class="rounded-2xl border border-gray-200 bg-white px-4 py-3 dark:border-gray-800 dark:bg-white/[0.03]">
            {{ $purchases->links() }}
        </div>
    @endif
</div>

<x-ui.delete-confirm />
@endsection