@extends('layouts.app')

@section('content')
    @php
        $currentUser = auth()->user();

        $canCreateMaterial = $currentUser && (
            (method_exists($currentUser, 'isDeveloper') && $currentUser->isDeveloper()) ||
            (method_exists($currentUser, 'isOwner') && $currentUser->isOwner()) ||
            $currentUser->can('manage materials') ||
            $currentUser->can('manage stock') ||
            $currentUser->can('create materials') ||
            $currentUser->can('create stock') ||
            $currentUser->can('create material stock')
        );

        $canEditMaterial = $currentUser && (
            (method_exists($currentUser, 'isDeveloper') && $currentUser->isDeveloper()) ||
            (method_exists($currentUser, 'isOwner') && $currentUser->isOwner()) ||
            $currentUser->can('manage materials') ||
            $currentUser->can('manage stock') ||
            $currentUser->can('edit materials') ||
            $currentUser->can('edit stock') ||
            $currentUser->can('edit material stock')
        );

        $canDeleteMaterial = $currentUser && (
            (method_exists($currentUser, 'isDeveloper') && $currentUser->isDeveloper()) ||
            (method_exists($currentUser, 'isOwner') && $currentUser->isOwner()) ||
            $currentUser->can('manage materials') ||
            $currentUser->can('manage stock') ||
            $currentUser->can('delete materials') ||
            $currentUser->can('delete stock') ||
            $currentUser->can('delete material stock')
        );

        $canShowActionColumn = $canEditMaterial || $canDeleteMaterial;
    @endphp

    <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] lg:p-6">
        <div class="mb-6 flex flex-wrap items-center justify-between gap-4">
            <div>
                <h2 class="text-xl font-semibold text-gray-800 dark:text-white/90">{{ $title }}</h2>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    Kelola data bahan, harga dasar, tipe hitung, dan stok bahan.
                </p>
            </div>

            @if($canCreateMaterial)
                <a href="{{ route('stock.materials.create') }}"
                    class="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-theme-xs transition hover:bg-brand-600 focus:outline-none focus:ring-2 focus:ring-brand-500/40">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd"
                            d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
                            clip-rule="evenodd" />
                    </svg>
                    Tambah Bahan
                </a>
            @endif
        </div>

        <form method="GET" class="mb-6 flex flex-wrap items-end gap-3">
            <div class="w-full md:w-72">
                <label for="search" class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-300">
                    Cari Bahan
                </label>
                <input type="text" name="search" id="search" value="{{ request('search') }}"
                    placeholder="Cari nama bahan..."
                    class="block h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:text-white/90">
            </div>

            <div class="w-full md:w-64">
                <x-form.select
                    name="category"
                    label="Kategori"
                    placeholder="Semua Kategori"
                    :value="request('category')"
                    :options="$categories->pluck('name', 'id')->toArray()"
                    :searchable="true"
                />
            </div>

            <div class="w-full md:w-44">
                <x-form.select
                    name="stock"
                    label="Status Stok"
                    placeholder="Semua Stok"
                    :value="request('stock')"
                    :options="['low' => 'Stok Rendah', 'out' => 'Stok Habis']"
                />
            </div>

            <div class="flex gap-2">
                <button type="submit"
                    class="h-11 rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-700 transition hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300">
                    Filter
                </button>

                <a href="{{ route('stock.materials.index') }}"
                    class="inline-flex h-11 items-center rounded-lg border border-gray-300 px-4 text-sm font-medium text-gray-700 transition hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-800">
                    Reset
                </a>
            </div>
        </form>

        @if (session('success'))
            <div class="mb-4 rounded-lg bg-success-50 p-4 text-sm text-success-700 dark:bg-success-500/10 dark:text-success-500">
                {{ session('success') }}
            </div>
        @endif

        @if (session('error'))
            <div class="mb-4 rounded-lg bg-error-50 p-4 text-sm text-error-700 dark:bg-error-500/10 dark:text-error-500">
                {{ session('error') }}
            </div>
        @endif

        <div class="overflow-hidden rounded-xl border border-gray-200 dark:border-gray-800">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
                    <thead class="bg-gray-50 dark:bg-gray-800/50">
                        <tr>
                            <th class="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Nama
                            </th>
                            <th class="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Kategori
                            </th>
                            <th class="px-5 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Tipe
                            </th>
                            <th class="px-5 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Harga Dasar
                            </th>
                            <th class="px-5 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Stok
                            </th>
                            <th class="px-5 py-3 text-center text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Status
                            </th>
                            @if($canShowActionColumn)
                                <th class="px-5 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                    Aksi
                                </th>
                            @endif
                        </tr>
                    </thead>

                    <tbody class="divide-y divide-gray-200 bg-white dark:divide-gray-800 dark:bg-white/[0.03]">
                        @forelse ($materials as $material)
                            @php
                                $isLowStock = !$material->is_custom
                                    && (float) $material->min_stock > 0
                                    && (float) $material->stock <= (float) $material->min_stock;

                                $measurementMode = $material->measurement_mode ?? 'manual';
                                $priceUnitLabel = $measurementMode === 'm2' ? 'm²' : ($measurementMode === 'roll' ? 'm' : $material->unit);

                                $hasComponentsTable = $hasMaterialComponentsTable ?? false;
                                $componentPreview = $hasComponentsTable ? $material->components->take(3) : collect();
                                $remainingComponents = $hasComponentsTable ? max($material->components->count() - $componentPreview->count(), 0) : 0;
                            @endphp

                            <tr>
                                <td class="px-5 py-4 text-sm">
                                    <div class="font-medium text-gray-800 dark:text-white/90">
                                        {{ $material->name }}
                                    </div>

                                    <div class="mt-1 flex flex-wrap gap-1.5">
                                        @if($material->is_custom)
                                            <span class="inline-flex items-center rounded-full bg-warning-50 px-2.5 py-0.5 text-xs font-medium text-warning-700 dark:bg-warning-500/15 dark:text-warning-400">
                                                Custom
                                            </span>
                                        @endif

                                        @if($measurementMode === 'm2')
                                            <span class="inline-flex items-center rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700 dark:bg-brand-500/15 dark:text-brand-400">
                                                Hitung m²
                                            </span>
                                        @elseif($measurementMode === 'roll')
                                            <span class="inline-flex items-center rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700 dark:bg-brand-500/15 dark:text-brand-400">
                                                Hitung Roll
                                            </span>
                                        @endif

                                        @if($material->track_clicks)
                                            <span class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-700 dark:bg-gray-500/15 dark:text-gray-300">
                                                Track Klik
                                            </span>
                                        @endif
                                    </div>

                                    @if($hasComponentsTable && $material->components->isNotEmpty())
                                        <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                            Komponen:
                                            @foreach($componentPreview as $idx => $component)
                                                <span class="font-medium">
                                                    {{ $component->componentMaterial->name ?? '-' }}
                                                </span>
                                                x {{ rtrim(rtrim(number_format((float) $component->qty, 4, '.', ''), '0'), '.') }}{{ $idx < $componentPreview->count() - 1 ? ',' : '' }}
                                            @endforeach
                                            @if($remainingComponents > 0)
                                                +{{ $remainingComponents }} lagi
                                            @endif
                                        </div>
                                    @elseif($material->is_custom && $material->sourceMaterial)
                                        <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                            Komponen legacy:
                                            <span class="font-medium">{{ $material->sourceMaterial->name }}</span>
                                            x {{ rtrim(rtrim(number_format((float) $material->conversion_qty, 4, '.', ''), '0'), '.') }}
                                        </div>
                                    @endif

                                    @if($material->is_custom)
                                        <div class="mt-1 text-xs text-brand-600 dark:text-brand-400">
                                            Stok mengikuti bahan komponen
                                        </div>
                                    @endif

                                    @if($measurementMode === 'roll' && !empty($material->roll_width_cm))
                                        <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                            Lebar roll: {{ rtrim(rtrim(number_format((float) $material->roll_width_cm, 4, '.', ''), '0'), '.') }} cm
                                        </div>
                                    @endif
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">
                                    {{ $material->category->name ?? '-' }}
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">
                                    <div>{{ $material->is_custom ? 'Custom' : 'Standar' }}</div>
                                    <div class="text-xs text-gray-400 dark:text-gray-500">
                                        @if($measurementMode === 'm2')
                                            Per m²
                                        @elseif($measurementMode === 'roll')
                                            Per meter panjang
                                        @elseif($material->is_custom)
                                            Stok dari komponen
                                        @else
                                            Manual
                                        @endif
                                    </div>
                                </td>

                                <td class="whitespace-nowrap px-5 py-4 text-right text-sm text-gray-500 dark:text-gray-400">
                                    Rp {{ number_format((float) $material->base_price, 0, ',', '.') }}/{{ $priceUnitLabel }}
                                </td>

                                <td class="whitespace-nowrap px-5 py-4 text-right text-sm">
                                    @if($material->is_custom)
                                        <div class="font-medium text-brand-600 dark:text-brand-400">
                                            Mengikuti komponen
                                        </div>
                                        <div class="text-xs text-gray-400 dark:text-gray-500">
                                            Stok bahan custom tidak dipakai
                                        </div>
                                    @else
                                        <div class="{{ $isLowStock ? 'font-medium text-error-500' : 'text-gray-500 dark:text-gray-400' }}">
                                            {{ number_format((float) $material->stock, 2, ',', '.') }} {{ $material->unit }}
                                        </div>

                                        @if((float) $material->min_stock > 0)
                                            <div class="text-xs {{ $isLowStock ? 'text-error-500' : 'text-gray-400 dark:text-gray-500' }}">
                                                Min: {{ number_format((float) $material->min_stock, 2, ',', '.') }}
                                            </div>
                                        @endif
                                    @endif
                                </td>

                                <td class="whitespace-nowrap px-5 py-4 text-center">
                                    <div class="flex flex-col items-center gap-1">
                                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {{ $material->is_active ? 'bg-success-50 text-success-700 dark:bg-success-500/15 dark:text-success-500' : 'bg-gray-100 text-gray-700 dark:bg-gray-500/15 dark:text-gray-400' }}">
                                            {{ $material->is_active ? 'Aktif' : 'Nonaktif' }}
                                        </span>

                                        @if($isLowStock)
                                            <span class="inline-flex items-center rounded-full bg-error-50 px-2.5 py-0.5 text-xs font-medium text-error-700 dark:bg-error-500/15 dark:text-error-400">
                                                Stok Rendah
                                            </span>
                                        @endif
                                    </div>
                                </td>

                                @if($canShowActionColumn)
                                    <td class="whitespace-nowrap px-5 py-4 text-right text-sm">
                                        <div class="flex items-center justify-end gap-2">
                                            @if($canEditMaterial)
                                                <a href="{{ route('stock.materials.edit', $material) }}"
                                                    class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-600 transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-600 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:border-brand-500/30 dark:hover:bg-brand-500/10 dark:hover:text-brand-400"
                                                    title="Edit">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                        <path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z" />
                                                        <path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd" />
                                                    </svg>
                                                </a>
                                            @endif

                                            @if($canDeleteMaterial)
                                                <button
                                                    @click="$dispatch('open-delete-modal', { action: '{{ route('stock.materials.destroy', $material) }}', title: 'Hapus Bahan?', description: 'Hapus bahan ini?' })"
                                                    type="button"
                                                    class="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-600 transition hover:border-error-300 hover:bg-error-50 hover:text-error-600 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:border-error-500/30 dark:hover:bg-error-500/10 dark:hover:text-error-400"
                                                    title="Hapus">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                                        <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                                                    </svg>
                                                </button>
                                            @endif
                                        </div>
                                    </td>
                                @endif
                            </tr>
                        @empty
                            <tr>
                                <td colspan="{{ $canShowActionColumn ? 7 : 6 }}" class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">
                                    Belum ada data bahan
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-4">
            {{ $materials->withQueryString()->links() }}
        </div>
    </div>

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