@extends('layouts.admin')

@section('title', 'Daftar Produksi')

@section('content')
    <!-- Breadcrumb -->
    @php
        $breadcrumbs = [
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Master', 'url' => '#'],
            ['label' => 'Produksi', 'url' => route('admin.productions.index')],
        ];
    @endphp
    <x-breadcrumb :items="$breadcrumbs" />

    <!-- Notifikasi Modern -->
    <x-admin-notification />

    {{-- Quick Stats --}}
    @php
        $totalProductions = \App\Models\Production::count();
        $unassignedCount = \App\Models\Production::whereNull('teknisi_id')
            ->whereNotIn('status', ['selesai', 'dibatalkan'])
            ->count();
        $inProgressCount = \App\Models\Production::where('status', 'dalam_proses')->count();
        $completedCount = \App\Models\Production::where('status', 'selesai')->count();
    @endphp

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs font-medium text-gray-600 dark:text-gray-400 uppercase tracking-wide">Total Produksi
                    </p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">{{ $totalProductions }}</p>
                </div>
                <div class="p-3 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
                    <i class="fas fa-industry text-blue-600 dark:text-blue-400 text-xl"></i>
                </div>
            </div>
        </div>

        <a href="{{ route('admin.productions.index', ['status' => 'menunggu', 'teknisi' => 'unassigned']) }}"
            class="bg-white dark:bg-gray-800 rounded-lg border border-yellow-200 dark:border-yellow-800 p-4 border-l-4 border-l-yellow-500 hover:border-yellow-300 dark:hover:border-yellow-700 transition-all duration-200 cursor-pointer group">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs font-medium text-gray-600 dark:text-gray-400 uppercase tracking-wide">Belum Ditugaskan
                    </p>
                    <p
                        class="text-2xl font-bold text-yellow-600 dark:text-yellow-400 mt-1 group-hover:text-yellow-700 dark:group-hover:text-yellow-300 transition-colors">
                        {{ $unassignedCount }}
                    </p>
                    @if ($unassignedCount > 0)
                        <p
                            class="text-xs text-yellow-600 dark:text-yellow-400 mt-1 opacity-0 group-hover:opacity-100 transition-opacity">
                            Klik untuk lihat →
                        </p>
                    @endif
                </div>
                <div
                    class="p-3 bg-yellow-100 dark:bg-yellow-900/40 rounded-lg group-hover:bg-yellow-200 dark:group-hover:bg-yellow-900/60 transition-colors">
                    <i class="fas fa-user-plus text-yellow-600 dark:text-yellow-400 text-xl"></i>
                </div>
            </div>
        </a>

        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs font-medium text-gray-600 dark:text-gray-400 uppercase tracking-wide">Dalam Proses</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">{{ $inProgressCount }}</p>
                </div>
                <div class="p-3 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
                    <i class="fas fa-spinner text-blue-600 dark:text-blue-400 text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs font-medium text-gray-600 dark:text-gray-400 uppercase tracking-wide">Selesai</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">{{ $completedCount }}</p>
                </div>
                <div class="p-3 bg-green-100 dark:bg-green-900/40 rounded-lg">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Header & Action Bar -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white mb-4">Daftar Produksi</h1>

        <!-- Filter Section -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <form method="GET" action="{{ route('admin.productions.index') }}" id="filterForm"
                class="flex flex-col sm:flex-row items-end gap-3">
                <!-- Search Bar -->
                <div class="relative flex-1 w-full sm:w-auto">
                    <input type="text" name="search" id="searchInput" value="{{ request('search') }}"
                        placeholder="Cari order, customer, produk..." class="form-input-search" />
                    <i
                        class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none"></i>
                    @if (request('search'))
                        <button type="button" onclick="clearSearch()"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300">
                            <i class="fas fa-times"></i>
                        </button>
                    @endif
                </div>

                <!-- Status Filter -->
                <div class="relative w-full sm:w-auto">
                    <select name="status" id="statusFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Status</option>
                        <option value="menunggu" {{ request('status') === 'menunggu' ? 'selected' : '' }}>Menunggu</option>
                        <option value="dalam_proses" {{ request('status') === 'dalam_proses' ? 'selected' : '' }}>Dalam
                            Proses</option>
                        <option value="selesai" {{ request('status') === 'selesai' ? 'selected' : '' }}>Selesai</option>
                        <option value="dibatalkan" {{ request('status') === 'dibatalkan' ? 'selected' : '' }}>Dibatalkan
                        </option>
                    </select>
                    <i
                        class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>

                <!-- Teknisi Assignment Filter -->
                <div class="relative w-full sm:w-auto">
                    <select name="teknisi" id="teknisiFilter" onchange="submitFilter()" class="form-select">
                        <option value="">Semua Penugasan</option>
                        <option value="unassigned" {{ request('teknisi') === 'unassigned' ? 'selected' : '' }}>Belum
                            Ditugaskan</option>
                        <option value="assigned" {{ request('teknisi') === 'assigned' ? 'selected' : '' }}>Sudah Ditugaskan
                        </option>
                    </select>
                    <i
                        class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500 pointer-events-none text-xs"></i>
                </div>
            </form>
        </div>
    </div>

    <!-- Active Filters Info -->
    @if (request('search') || request('status') || request()->filled('teknisi'))
        <div class="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
            <div class="flex flex-wrap items-center gap-2">
                <span class="text-sm font-medium text-blue-800 dark:text-blue-200">Filter Aktif:</span>

                @if (request('search'))
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-200">
                        <i class="fas fa-search mr-1"></i>
                        Pencarian: "{{ request('search') }}"
                        <button onclick="clearFilter('search')" class="ml-2 hover:text-blue-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif

                @if (request('status'))
                    @php
                        $statusLabels = [
                            'menunggu' => 'Menunggu',
                            'dalam_proses' => 'Dalam Proses',
                            'selesai' => 'Selesai',
                            'dibatalkan' => 'Dibatalkan',
                        ];
                        $statusLabel = $statusLabels[request('status')] ?? ucfirst(request('status'));
                    @endphp
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-200">
                        <i class="fas fa-filter mr-1"></i>
                        Status: {{ $statusLabel }}
                        <button onclick="clearFilter('status')" class="ml-2 hover:text-green-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif

                @if (request()->filled('teknisi'))
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-800 dark:text-purple-200">
                        <i class="fas fa-{{ request('teknisi') === 'unassigned' ? 'user-slash' : 'user-check' }} mr-1"></i>
                        Penugasan: {{ request('teknisi') === 'unassigned' ? 'Belum Ditugaskan' : 'Sudah Ditugaskan' }}
                        <button onclick="clearFilter('teknisi')" class="ml-2 hover:text-purple-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </span>
                @endif

                <button onclick="clearAllFilters()"
                    class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-700 transition-colors">
                    <i class="fas fa-times-circle mr-1"></i>
                    Hapus Semua Filter
                </button>
            </div>
        </div>
    @endif

    <!-- Table Container -->
    <div
        class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden transition-colors duration-300">
        <div class="overflow-x-auto">
            <table class="w-full" style="min-width: 1480px;">
                <thead class="bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-600">
                    <tr>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 50px;">No</th>
                        <th class="px-5 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 180px;">Order Info</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 100px;">Gambar</th>
                        <th class="px-5 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 200px;">Produk</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 100px;">Status</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 110px;">Planning</th>
                        <th class="px-5 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 160px;">Teknisi</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 110px;">Pembayaran</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 120px;">Periode</th>
                        <th class="px-5 py-3.5 text-right text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 150px;">Total Biaya</th>
                        <th class="px-5 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300"
                            style="width: 180px;">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse ($productions as $production)
                        <tr
                            class="hover:bg-blue-50/50 dark:hover:bg-gray-700/80 transition-colors duration-200 cursor-pointer">
                            <td class="px-4 py-4 text-center align-middle text-sm text-gray-900 dark:text-white">
                                {{ $loop->iteration + $productions->firstItem() - 1 }}</td>
                            <td class="px-5 py-4 align-middle">
                                <div class="flex items-center space-x-3">
                                    <div class="relative">
                                        <div
                                            class="w-10 h-10 bg-gradient-to-br from-indigo-400 to-indigo-600 rounded-lg flex items-center justify-center text-white font-bold">
                                            #{{ $production->order->id }}
                                        </div>
                                        @php
                                            // Hitung jumlah bahan dan sparepart yang direvisi oleh teknisi
                                            $revisedMaterialsCount = $production->productionMaterials
                                                ->where('is_admin_suggested', true)
                                                ->whereNotNull('revised_by_teknisi_at')
                                                ->count();
                                            $revisedSparepartsCount = $production->productionSpareparts
                                                ->where('is_admin_suggested', true)
                                                ->whereNotNull('revised_by_teknisi_at')
                                                ->count();
                                            $totalRevised = $revisedMaterialsCount + $revisedSparepartsCount;
                                        @endphp
                                        @if ($totalRevised > 0)
                                            <div class="absolute -top-1 -right-1 w-5 h-5 bg-orange-500 dark:bg-orange-600 rounded-full flex items-center justify-center border-2 border-white dark:border-gray-800 shadow-lg animate-pulse"
                                                title="{{ $totalRevised }} item inputan admin telah direvisi oleh teknisi">
                                                <span class="text-xs font-bold text-white">{{ $totalRevised }}</span>
                                            </div>
                                        @endif
                                    </div>
                                    <div>
                                        <div class="flex items-center gap-2">
                                            <p class="font-semibold text-gray-900 dark:text-white">
                                                {{ $production->order->customer_name ?? 'N/A' }}</p>
                                            @if ($totalRevised > 0)
                                                <span
                                                    class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-200 border border-orange-300 dark:border-orange-700"
                                                    title="Ada {{ $totalRevised }} item yang direvisi">
                                                    <i class="fas fa-edit mr-1"></i> Revisi
                                                </span>
                                            @endif
                                        </div>
                                        <p class="text-xs text-gray-600 dark:text-gray-400">Order ID:
                                            {{ $production->order->id }}</p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-4 text-center align-middle">
                                <div class="flex justify-center">
                                    @if ($production->product && $production->product->product_image)
                                        <img src="{{ asset('uploads/products/' . $production->product->product_image) }}"
                                            alt="Gambar Produk" class="h-20 w-20 object-contain"
                                            style="background: transparent;"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                        <!-- Fallback jika gambar gagal dimuat -->
                                        <div class="h-20 w-20 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center"
                                            style="display: none;">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-xl"></i>
                                        </div>
                                    @elseif ($production->product && $production->product->images && $production->product->images->count() > 0)
                                        <img src="{{ asset('uploads/products/' . $production->product->images->first()->image_path) }}"
                                            alt="Gambar Produk" class="h-20 w-20 object-contain"
                                            style="background: transparent;"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                        <!-- Fallback jika gambar gagal dimuat -->
                                        <div class="h-20 w-20 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center"
                                            style="display: none;">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-xl"></i>
                                        </div>
                                    @else
                                        <div
                                            class="h-20 w-20 bg-gray-100 dark:bg-gray-600 rounded flex items-center justify-center">
                                            <i class="fas fa-image text-gray-400 dark:text-gray-500 text-xl"></i>
                                        </div>
                                    @endif
                                </div>
                            </td>
                            <td class="px-5 py-4 align-middle">
                                <p class="font-medium text-gray-900 dark:text-white text-sm">
                                    {{ $production->product->product_title }}
                                </p>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Qty: <span
                                        class="font-medium text-gray-900 dark:text-white">{{ $production->order->quantity ?? 1 }}
                                        unit</span></p>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Kategori: <span
                                        class="font-medium text-gray-900 dark:text-white">{{ $production->product->category_name }}</span>
                                </p>
                            </td>
                            <td class="px-4 py-4 text-center align-middle">
                                @php
                                    $statusConfig = [
                                        'menunggu' => [
                                            'bg' => 'bg-gray-100',
                                            'text' => 'text-gray-700',
                                            'icon' => 'fa-clock',
                                        ],
                                        'dalam_proses' => [
                                            'bg' => 'bg-yellow-100',
                                            'text' => 'text-yellow-700',
                                            'icon' => 'fa-spinner',
                                        ],
                                        'selesai' => [
                                            'bg' => 'bg-green-100',
                                            'text' => 'text-green-700',
                                            'icon' => 'fa-check-circle',
                                        ],
                                        'dibatalkan' => [
                                            'bg' => 'bg-red-100',
                                            'text' => 'text-red-700',
                                            'icon' => 'fa-times-circle',
                                        ],
                                    ];
                                    $config = $statusConfig[$production->status] ?? [
                                        'bg' => 'bg-gray-100',
                                        'text' => 'text-gray-700',
                                        'icon' => 'fa-question',
                                    ];
                                @endphp
                                <span
                                    class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md {{ $config['bg'] }} {{ $config['text'] }}">
                                    <i class="fas {{ $config['icon'] }} text-xs"></i>
                                    <span>{{ ucfirst(str_replace('_', ' ', $production->status)) }}</span>
                                </span>
                            </td>
                            <td class="px-4 py-4 text-center align-middle">
                                <!-- Planning Status Badge -->
                                @if ($production->teknisi_id)
                                    @if ($production->planning_status === 'planning')
                                        <span
                                            class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300">
                                            <i class="fas fa-edit text-xs"></i> Planning
                                        </span>
                                    @elseif($production->planning_status === 'pending_approval')
                                        <span
                                            class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-yellow-100 dark:bg-yellow-900/40 text-yellow-800 dark:text-yellow-300">
                                            <i class="fas fa-clock text-xs"></i> Pending
                                        </span>
                                    @elseif($production->planning_status === 'approved')
                                        <span
                                            class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-green-100 dark:bg-green-900/40 text-green-800 dark:text-green-300">
                                            <i class="fas fa-check-circle text-xs"></i> Approved
                                        </span>
                                    @elseif($production->planning_status === 'rejected')
                                        <span
                                            class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-red-100 dark:bg-red-900/40 text-red-800 dark:text-red-300">
                                            <i class="fas fa-times-circle text-xs"></i> Rejected
                                        </span>
                                    @else
                                        <span
                                            class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-gray-100 dark:bg-gray-700/50 text-gray-700 dark:text-gray-300">
                                            <i class="fas fa-question text-xs"></i>
                                            {{ ucfirst($production->planning_status ?? 'N/A') }}
                                        </span>
                                    @endif
                                @else
                                    <span
                                        class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-gray-100 dark:bg-gray-700/50 text-gray-700 dark:text-gray-300">
                                        <i class="fas fa-minus text-xs"></i> -
                                    </span>
                                @endif
                            </td>
                            <td class="px-5 py-4 text-center align-middle">
                                @if ($production->teknisi_id)
                                    <div class="flex items-center justify-center space-x-2">
                                        <div
                                            class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-sm">
                                            {{ strtoupper(substr($production->teknisi->name, 0, 1)) }}
                                        </div>
                                        <div class="text-left">
                                            <p class="text-sm font-medium text-gray-900 dark:text-white">
                                                {{ $production->teknisi->name }}</p>
                                            <p class="text-xs text-gray-500 dark:text-gray-400">Kepala Produksi</p>
                                        </div>
                                    </div>
                                    @if ($production->assigned_at)
                                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                            Ditugaskan: {{ $production->assigned_at->format('d/m/Y H:i') }}
                                        </p>
                                    @endif
                                @else
                                    <span
                                        class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-gray-100 dark:bg-gray-700/50 text-gray-700 dark:text-gray-300">
                                        <i class="fas fa-user-slash text-xs"></i>
                                        Belum Ditugaskan
                                    </span>
                                @endif
                            </td>
                            <td class="px-4 py-4 text-center align-middle">
                                <!-- Payment Status & Method (Combined) -->
                                @php
                                    $paymentStatus = $production->order->status ?? 'menunggu';
                                    $paymentMethod = strtolower($production->order->payment_method ?? 'transfer');

                                    // Payment Status Config
                                    $paymentStatusConfig = [
                                        'selesai' => [
                                            'label' => 'Lunas',
                                            'bg' => 'bg-green-100 dark:bg-green-900/40',
                                            'text' => 'text-green-800 dark:text-green-300',
                                            'icon' => 'fa-check-circle',
                                        ],
                                        'diproses' => [
                                            'label' => 'Diproses',
                                            'bg' => 'bg-blue-100 dark:bg-blue-900/40',
                                            'text' => 'text-blue-800 dark:text-blue-300',
                                            'icon' => 'fa-spinner',
                                        ],
                                        'menunggu_verifikasi' => [
                                            'label' => 'Verifikasi',
                                            'bg' => 'bg-yellow-100 dark:bg-yellow-900/40',
                                            'text' => 'text-yellow-800 dark:text-yellow-300',
                                            'icon' => 'fa-clock',
                                        ],
                                        'menunggu' => [
                                            'label' => 'Menunggu',
                                            'bg' => 'bg-gray-100 dark:bg-gray-700/50',
                                            'text' => 'text-gray-700 dark:text-gray-300',
                                            'icon' => 'fa-clock',
                                        ],
                                    ];

                                    $statusConfig = $paymentStatusConfig[$paymentStatus] ?? [
                                        'label' => ucfirst(str_replace('_', ' ', $paymentStatus)),
                                        'bg' => 'bg-gray-100 dark:bg-gray-700/50',
                                        'text' => 'text-gray-700 dark:text-gray-300',
                                        'icon' => 'fa-question',
                                    ];

                                    // Payment Method Colors
                                    $paymentMethodColors = [
                                        'transfer' => 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300',
                                        'qris' => 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300',
                                        'dp' =>
                                            'bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300',
                                        'cod' =>
                                            'bg-orange-50 dark:bg-orange-900/20 text-orange-700 dark:text-orange-300',
                                    ];
                                    $methodClass =
                                        $paymentMethodColors[$paymentMethod] ??
                                        'bg-gray-50 dark:bg-gray-700/30 text-gray-600 dark:text-gray-400';
                                @endphp

                                <div class="space-y-1.5">
                                    <span
                                        class="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-md {{ $statusConfig['bg'] }} {{ $statusConfig['text'] }}">
                                        <i class="fas {{ $statusConfig['icon'] }} text-[10px]"></i>
                                        <span class="whitespace-nowrap">{{ $statusConfig['label'] }}</span>
                                    </span>
                                    <div>
                                        <span
                                            class="inline-flex items-center px-2 py-0.5 text-[10px] font-medium rounded {{ $methodClass }}">
                                            {{ strtoupper($paymentMethod) }}
                                        </span>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-4 text-center align-middle">
                                <div class="text-sm text-gray-900 dark:text-white font-medium">
                                    {{ $production->start_date?->format('d/m/Y') ?? 'N/A' }}</div>
                                @if ($production->end_date)
                                    <div class="text-xs text-gray-600 dark:text-gray-400"><i
                                            class="fas fa-arrow-right mx-1"></i>{{ $production->end_date->format('d/m/Y') }}
                                    </div>
                                @endif
                            </td>
                            <td class="px-5 py-4 text-right align-middle">
                                @php
                                    // Perhitungan yang benar:
                                    // - total_material_cost & total_sparepart_cost di DB sudah TOTAL (sudah dikalikan dengan order quantity)
                                    // - labor_cost di DB adalah TOTAL untuk semua produk
                                    $materialTotal = $production->total_material_cost ?? 0; // Sudah TOTAL di DB
                                    $sparepartTotal = $production->total_sparepart_cost ?? 0; // Sudah TOTAL di DB
                                    $directTotal = $materialTotal + $sparepartTotal; // Sudah TOTAL
                                    $laborTotal = $production->labor_cost ?? 0; // Sudah TOTAL di DB
                                    $actualTotal = $directTotal + $laborTotal; // Sudah TOTAL
                                @endphp
                                <div class="font-bold text-gray-900 dark:text-white">Rp
                                    {{ number_format($actualTotal, 0, ',', '.') }}</div>
                                <div class="text-xs text-gray-600 dark:text-gray-400 mt-1">
                                    <div>Material: Rp {{ number_format($materialTotal, 0, ',', '.') }}</div>
                                    <div>Sparepart: Rp {{ number_format($sparepartTotal, 0, ',', '.') }}</div>
                                    @if ($laborTotal > 0)
                                        <div class="text-blue-600 dark:text-blue-400 font-medium">Upah: Rp
                                            {{ number_format($laborTotal, 0, ',', '.') }}</div>
                                    @endif
                                </div>
                            </td>
                            <td class="px-5 py-4 text-center align-middle">
                                <div class="flex items-center justify-center space-x-2"
                                    style="display: flex; align-items: center; justify-content: center;">
                                    <!-- Show/View -->
                                    <a href="{{ route('admin.productions.show', $production->id) }}"
                                        class="inline-flex items-center justify-center w-9 h-9 text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded transition-colors duration-200"
                                        title="Detail">
                                        <i class="fas fa-eye text-base"></i>
                                    </a>

                                    <!-- Cancel -->
                                    @if (in_array($production->status, ['dalam_proses', 'menunggu']))
                                        <form id="cancel-form-{{ $production->id }}"
                                            action="{{ route('admin.productions.cancel', $production->id) }}"
                                            method="POST" class="inline m-0 p-0"
                                            style="display: inline-block; margin: 0; padding: 0;">
                                            @csrf
                                            <button type="button" data-id="{{ $production->id }}"
                                                onclick="confirmCancelFromBtn(this)"
                                                class="inline-flex items-center justify-center w-9 h-9 text-orange-600 dark:text-orange-400 hover:text-orange-700 dark:hover:text-orange-300 hover:bg-orange-50 dark:hover:bg-orange-900/20 rounded transition-colors duration-200"
                                                title="Batalkan">
                                                <i class="fas fa-ban text-base"></i>
                                            </button>
                                        </form>
                                    @endif

                                    <!-- Assign/Unassign Teknisi -->
                                    @if (!in_array($production->status, ['selesai', 'dibatalkan']))
                                        @if (!$production->teknisi_id)
                                            <form id="assign-form-{{ $production->id }}"
                                                action="{{ route('admin.productions.assign-teknisi', $production->id) }}"
                                                method="POST" class="inline m-0 p-0"
                                                style="display: inline-block; margin: 0; padding: 0;">
                                                @csrf
                                                <button type="button" data-id="{{ $production->id }}"
                                                    onclick="confirmAssignFromBtn(this); return false;"
                                                    class="inline-flex items-center justify-center w-9 h-9 text-green-600 dark:text-green-400 hover:text-green-700 dark:hover:text-green-300 hover:bg-green-50 dark:hover:bg-green-900/20 rounded transition-colors duration-200"
                                                    title="Tugaskan ke Teknisi">
                                                    <i class="fas fa-user-plus text-base"></i>
                                                </button>
                                            </form>
                                        @else
                                            <form id="unassign-form-{{ $production->id }}"
                                                action="{{ route('admin.productions.unassign-teknisi', $production->id) }}"
                                                method="POST" class="inline m-0 p-0"
                                                style="display: inline-block; margin: 0; padding: 0;">
                                                @csrf
                                                <button type="button" data-id="{{ $production->id }}"
                                                    onclick="confirmUnassignFromBtn(this); return false;"
                                                    class="inline-flex items-center justify-center w-9 h-9 text-yellow-600 dark:text-yellow-400 hover:text-yellow-700 dark:hover:text-yellow-300 hover:bg-yellow-50 dark:hover:bg-yellow-900/20 rounded transition-colors duration-200"
                                                    title="Batalkan Tugas Teknisi">
                                                    <i class="fas fa-user-minus text-base"></i>
                                                </button>
                                            </form>
                                        @endif
                                    @endif

                                    <!-- Delete -->
                                    @if ($production->status !== 'selesai')
                                        <form id="delete-form-{{ $production->id }}"
                                            action="{{ route('admin.productions.destroy', $production->id) }}"
                                            method="POST" class="inline m-0 p-0"
                                            style="display: inline-block; margin: 0; padding: 0;"
                                            onsubmit="return confirmDelete(event, {{ $production->id }})">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit"
                                                class="inline-flex items-center justify-center w-9 h-9 text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors duration-200"
                                                title="Hapus">
                                                <i class="fas fa-trash text-base"></i>
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="11" class="px-6 py-16 text-center">
                                <div class="flex flex-col items-center">
                                    <div
                                        class="w-20 h-20 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                                        <i class="fas fa-industry text-3xl text-gray-400 dark:text-gray-500"></i>
                                    </div>
                                    <p class="text-gray-600 dark:text-gray-300 text-lg font-semibold mb-1">Belum ada data
                                        produksi</p>
                                    <p class="text-gray-500 dark:text-gray-400 text-sm">Produksi akan muncul setelah order
                                        diterima</p>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pagination -->
    @if ($productions->hasPages())
        <div class="mt-6 flex justify-center">
            {{ $productions->onEachSide(1)->links() }}
        </div>
    @endif

    {{-- CSRF & Axios setup --}}
    <script>
        // Pasang token CSRF untuk semua request Axios
        axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').content;

        // Helpers: read data-id / data-url wrappers to avoid Blade in onclick
        function goToUrl(btn) {
            const url = btn.dataset.url;
            if (url) window.location.href = url;
        }
        // Function confirmComplete dihapus - Admin tidak bisa selesaikan produksi langsung
        function confirmCancelFromBtn(btn) {
            const id = Number(btn.dataset.id);
            if (!id) return;
            confirmCancel(id);
        }

        function confirmAssignFromBtn(btn) {
            const id = Number(btn.dataset.id);
            if (!id) return;
            confirmAssign(id);
        }

        function confirmUnassignFromBtn(btn) {
            const id = Number(btn.dataset.id);
            if (!id) return;
            confirmUnassign(id);
        }

        function confirmCancel(id) {
            Swal.fire({
                title: 'Batalkan Produksi?',
                html: '<p>Apakah Anda yakin ingin membatalkan produksi ini?</p><p class="text-sm text-red-600">Tindakan ini tidak dapat diubah!</p>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ea580c',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-ban mr-2"></i>Ya, batalkan!',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                reverseButtons: true,
                buttonsStyling: true,
                customClass: {
                    confirmButton: 'px-4 py-2 rounded-lg font-semibold',
                    cancelButton: 'px-4 py-2 rounded-lg font-semibold'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    document.getElementById('cancel-form-' + id).submit();
                }
            });
        }

        function confirmAssign(id) {
            console.log('confirmAssign called with id:', id);

            // Cek apakah SweetAlert sudah ter-load
            if (typeof Swal === 'undefined') {
                console.error('SweetAlert2 tidak ter-load!');
                // Fallback: langsung submit form
                const form = document.getElementById('assign-form-' + id);
                if (form) {
                    if (confirm('Tugaskan produksi ini ke Teknisi?')) {
                        form.submit();
                    }
                }
                return false;
            }

            // Cek apakah form ada sebelum menampilkan dialog
            const form = document.getElementById('assign-form-' + id);
            if (!form) {
                console.error('Form tidak ditemukan: assign-form-' + id);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Form tidak ditemukan! Silakan refresh halaman dan coba lagi.'
                });
                return false;
            }

            // Tampilkan dialog konfirmasi
            Swal.fire({
                title: 'Tugaskan ke Teknisi?',
                html: '<p>Apakah Anda yakin ingin menugaskan produksi ini ke Kepala Produksi?</p><p class="text-sm text-green-600">Teknisi akan mendapat notifikasi tugas baru.</p>',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#16a34a',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-user-plus mr-2"></i>Ya, tugaskan!',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                reverseButtons: true,
                buttonsStyling: true,
                allowOutsideClick: false,
                customClass: {
                    confirmButton: 'px-4 py-2 rounded-lg font-semibold',
                    cancelButton: 'px-4 py-2 rounded-lg font-semibold'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    // Pastikan form masih ada dan valid
                    const formElement = document.getElementById('assign-form-' + id);
                    if (!formElement) {
                        console.error('Form not found after confirmation: assign-form-' + id);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Form tidak ditemukan! Silakan refresh halaman dan coba lagi.'
                        });
                        return;
                    }

                    console.log('Submitting form for production:', id);
                    console.log('Form action:', formElement.action);
                    console.log('Form method:', formElement.method);

                    // Tampilkan loading
                    Swal.fire({
                        title: 'Memproses...',
                        html: 'Mohon tunggu...',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    // Submit form menggunakan fetch/AJAX
                    const formData = new FormData(formElement);
                    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

                    if (!csrfToken) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'CSRF token tidak ditemukan! Silakan refresh halaman.'
                        });
                        return;
                    }

                    fetch(formElement.action, {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': csrfToken,
                                'X-Requested-With': 'XMLHttpRequest',
                                'Accept': 'application/json'
                            },
                            body: formData
                        })
                        .then(async response => {
                            console.log('Response status:', response.status);
                            console.log('Response headers:', Object.fromEntries(response.headers
                                .entries()));

                            if (response.status === 419) {
                                throw new Error('CSRF token mismatch. Refresh halaman dan coba lagi.');
                            }

                            // Try to parse as JSON first
                            let data;
                            try {
                                const text = await response.text();
                                console.log('Response text:', text);
                                data = text ? JSON.parse(text) : null;
                            } catch (e) {
                                console.warn('Response is not JSON, treating as success');
                                data = {
                                    success: true
                                };
                            }

                            if (!response.ok) {
                                const errorMessage = data?.message || data?.errors?.assign?.[0] ||
                                    'Terjadi kesalahan saat mengirim request';
                                throw new Error(errorMessage);
                            }

                            return data;
                        })
                        .then(data => {
                            console.log('Success response:', data);

                            if (data && data.success === false) {
                                throw new Error(data.message || 'Gagal menugaskan teknisi');
                            }

                            // Show success message
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                html: data?.message || 'Produksi berhasil ditugaskan ke teknisi!',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                // Reload halaman untuk melihat perubahan
                                window.location.reload();
                            });
                        })
                        .catch(error => {
                            console.error('Error submitting form:', error);
                            Swal.fire({
                                icon: 'error',
                                title: 'Terjadi Kesalahan',
                                html: error.message || 'Gagal mengirim form. Silakan coba lagi.',
                                confirmButtonText: 'OK'
                            });
                        });
                } else {
                    console.log('User cancelled the assignment');
                }
            }).catch((error) => {
                console.error('Error in confirmAssign:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Terjadi Kesalahan',
                    text: 'Terjadi kesalahan saat menugaskan teknisi. Silakan coba lagi.'
                });
            });

            return false;
        }

        function confirmUnassign(id) {
            Swal.fire({
                title: 'Batalkan Tugas Teknisi?',
                html: '<p>Apakah Anda yakin ingin membatalkan tugas teknisi untuk produksi ini?</p><p class="text-sm text-yellow-600">Teknisi tidak akan bisa mengakses produksi ini lagi.</p>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#eab308',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-user-minus mr-2"></i>Ya, batalkan!',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                reverseButtons: true,
                buttonsStyling: true,
                customClass: {
                    confirmButton: 'px-4 py-2 rounded-lg font-semibold',
                    cancelButton: 'px-4 py-2 rounded-lg font-semibold'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const form = document.getElementById('unassign-form-' + id);
                    if (form) {
                        form.submit();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Form tidak ditemukan!'
                        });
                    }
                }
            });
        }

        function confirmDelete(event, id) {
            event.preventDefault();
            const form = event.target.closest('form');

            Swal.fire({
                title: 'Yakin ingin menghapus?',
                text: 'Data produksi ini akan dihapus secara permanen!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal',
                reverseButtons: true,
                customClass: {
                    popup: 'rounded-lg',
                    confirmButton: 'px-4 py-2 rounded-md font-medium',
                    cancelButton: 'px-4 py-2 rounded-md font-medium'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });
        }
    </script>

    <style>
        /* Custom scrollbar untuk tabel */
        .overflow-x-auto::-webkit-scrollbar {
            height: 8px;
        }

        .overflow-x-auto::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 4px;
        }

        .overflow-x-auto::-webkit-scrollbar-thumb {
            background: #cbd5e0;
            border-radius: 4px;
        }

        .overflow-x-auto::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        /* Dark mode scrollbar */
        .dark .overflow-x-auto::-webkit-scrollbar-track {
            background: #374151;
        }

        .dark .overflow-x-auto::-webkit-scrollbar-thumb {
            background: #6b7280;
        }

        .dark .overflow-x-auto::-webkit-scrollbar-thumb:hover {
            background: #9ca3af;
        }
    </style>

    <script>
        // Submit filter dengan parameter yang bersih
        function submitFilter() {
            const params = new URLSearchParams();

            // Ambil nilai dari setiap input/select
            const search = document.getElementById('searchInput')?.value?.trim() || '';
            const status = document.getElementById('statusFilter')?.value || '';
            const teknisi = document.getElementById('teknisiFilter')?.value || '';

            // Hanya tambahkan parameter yang memiliki nilai
            if (search) {
                params.append('search', search);
            }
            if (status) {
                params.append('status', status);
            }
            if (teknisi) {
                params.append('teknisi', teknisi);
            }

            // Redirect dengan parameter yang bersih
            const url = '{{ route('admin.productions.index') }}' + (params.toString() ? '?' + params.toString() : '');
            window.location.href = url;
        }

        // Clear search only
        function clearSearch() {
            const url = new URL(window.location);
            url.searchParams.delete('search');
            window.location.href = url.toString();
        }

        // Clear search only
        function clearSearch() {
            const url = new URL(window.location);
            url.searchParams.delete('search');
            window.location.href = url.toString();
        }

        // Clear individual filter
        function clearFilter(filterName) {
            const url = new URL(window.location);
            url.searchParams.delete(filterName);
            window.location.href = url.toString();
        }

        // Clear all filters
        function clearAllFilters() {
            window.location.href = '{{ route('admin.productions.index') }}';
        }

        // Submit form search dengan Enter
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        submitFilter();
                    }
                });
            }
        });
    </script>

    <style>
        /* Konsisten Style untuk semua Index Pages */
        .form-input-search,
        .form-select {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            line-height: 1.5 !important;
            padding: 0 2.5rem 0 2.5rem !important;
            margin: 0 !important;
        }

        .form-input-search {
            width: 100%;
            padding-left: 2.5rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .dark .form-input-search {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }

        .form-input-search:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }

        .form-select {
            width: 100%;
            padding-left: 1rem !important;
            padding-right: 2.5rem !important;
            border: 1px solid rgb(209 213 219);
            border-radius: 0.5rem;
            background-color: white;
            color: rgb(17 24 39);
            font-size: 0.875rem;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            transition: all 0.2s;
        }

        .dark .form-select {
            border-color: rgb(75 85 99);
            background-color: rgb(55 65 81);
            color: white;
        }

        .form-select:focus {
            outline: none;
            ring: 2px;
            ring-color: rgb(59 130 246);
        }

        .action-btn-primary,
        .action-btn-danger {
            height: 40px !important;
            min-height: 40px !important;
            max-height: 40px !important;
            box-sizing: border-box !important;
            padding: 0 1rem !important;
            margin: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-weight: 500;
            border-radius: 0.5rem;
            transition: all 0.2s;
            white-space: nowrap;
        }

        .action-btn-primary {
            background-color: rgb(59 130 246);
            color: white;
        }

        .action-btn-primary:hover {
            background-color: rgb(37 99 235);
        }

        .action-btn-danger {
            background-color: rgb(239 68 68);
            color: white;
        }

        .action-btn-danger:hover:not(:disabled) {
            background-color: rgb(220 38 38);
        }

        .action-btn-danger:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
@endsection
