@extends('layouts.app')

@section('content')
    @php
        $summary = $summary ?? [];
        $machineStats = $machineStats ?? [];
        $machines = $machines ?? collect();
        $categories = $categories ?? collect();
        $products = $products ?? collect();
        $materials = $materials ?? collect();
        $dailyData = $dailyData ?? collect();
        $materialMachines = $materialMachines ?? [];
        $materialMachineCostPerClick = $materialMachineCostPerClick ?? [];
        $startDate = $startDate ?? now()->startOfMonth()->toDateString();
        $endDate = $endDate ?? now()->toDateString();

        /*
         * Sinkronisasi total:
         * - "Rincian per Mesin" memakai $machineStats.
         * - Supaya "Total Klik" dan "Total Biaya" tidak berbeda,
         *   total utama juga dihitung dari sumber yang sama.
         * - Jika $machineStats kosong, fallback ke $summary.
         */
        $machineStatsCollection = collect($machineStats);
        $machineStatsTotalClicks = (int) $machineStatsCollection->sum(fn ($stat) => (int) ($stat['total_clicks'] ?? 0));
        $machineStatsTotalCost = (float) $machineStatsCollection->sum(fn ($stat) => (float) ($stat['total_cost'] ?? 0));

        $syncedTotalClicks = $machineStatsCollection->isNotEmpty()
            ? $machineStatsTotalClicks
            : (int) ($summary['total_clicks'] ?? 0);

        $syncedTotalCost = $machineStatsCollection->isNotEmpty()
            ? $machineStatsTotalCost
            : (float) ($summary['total_cost'] ?? 0);

        $reportData = $reportData ?? new \Illuminate\Pagination\LengthAwarePaginator(
            [],
            0,
            (int) request('per_page', 15),
            1,
            [
                'path' => request()->url(),
                'query' => request()->query(),
            ]
        );
    @endphp

    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Laporan Klik' }}" />

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <x-posgraf.stat-card title="Total Order" value="{{ number_format($summary['total_orders'] ?? 0) }}" color="brand">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Total Qty" value="{{ number_format($summary['total_qty'] ?? 0) }} pcs" color="success">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Total Klik" value="{{ number_format($syncedTotalClicks) }}" color="purple">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Total Biaya" value="Rp {{ number_format($syncedTotalCost, 0, ',', '.') }}" color="error">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>
    </div>

    <div class="grid grid-cols-1 gap-6 mb-6 lg:grid-cols-3">
        <div class="lg:col-span-2">
            <x-posgraf.chart-card title="Tren Klik Harian" id="clicksChart" />
        </div>

        <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="px-6 py-5 border-b border-gray-100 dark:border-gray-700/50">
                <h3 class="text-base font-medium text-gray-800 dark:text-white/90">Rincian per Mesin</h3>
            </div>
            <div class="p-6">
                @if(count($machineStats) > 0)
                    <div class="space-y-4">
                        @foreach($machineStats as $stat)
                            <div class="flex flex-col gap-1">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium text-gray-800 dark:text-gray-300">{{ $stat['name'] ?? '-' }}</span>
                                    <span class="text-sm font-bold text-gray-800 dark:text-white/90">{{ number_format($stat['total_clicks'] ?? 0) }} Klik</span>
                                </div>
                                <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                                    <span>Biaya: Rp {{ number_format($stat['cost_per_click'] ?? 0, 0, ',', '.') }}/klik</span>
                                    <span>Total: Rp {{ number_format($stat['total_cost'] ?? 0, 0, ',', '.') }}</span>
                                </div>
                            </div>
                            @if(!$loop->last)
                                <hr class="border-gray-100 dark:border-gray-700/50">
                            @endif
                        @endforeach

                        <hr class="border-gray-200 dark:border-gray-700/50">

                        <div class="flex flex-col gap-1 pt-1">
                            <div class="flex items-center justify-between">
                                <span class="text-sm font-bold text-gray-800 dark:text-white/90">Total Klik</span>
                                <span class="text-sm font-bold text-brand-600 dark:text-brand-400">
                                    {{ number_format($machineStatsTotalClicks) }} Klik
                                </span>
                            </div>
                            <div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                                <span>Total Biaya</span>
                                <span>Rp {{ number_format($machineStatsTotalCost, 0, ',', '.') }}</span>
                            </div>
                        </div>
                    </div>
                @else
                    <p class="text-sm text-gray-500 dark:text-gray-400">Belum ada data mesin.</p>
                @endif
            </div>
        </div>
    </div>

    <div class="mb-6 rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6">
        <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Filter Laporan</h3>
            <p class="text-sm text-gray-500 dark:text-gray-400">Saring data berdasarkan periode, mesin, kategori, produk, dan bahan.</p>
        </div>

        <form method="GET" action="{{ route('reports.clicks') }}" class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-6">
            <div>
                <x-form.date-picker
                    name="start_date"
                    label="Dari Tanggal"
                    placeholder="Pilih tanggal"
                    :defaultDate="$startDate"
                />
            </div>

            <div>
                <x-form.date-picker
                    name="end_date"
                    label="Sampai Tanggal"
                    placeholder="Pilih tanggal"
                    :defaultDate="$endDate"
                />
            </div>

            <div>
                <x-form.select name="machine_id" label="Mesin" placeholder="Semua Mesin">
                    @foreach($machines as $machine)
                        <option value="{{ $machine->id }}" {{ request('machine_id') == $machine->id ? 'selected' : '' }}>
                            {{ $machine->name }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div>
                <x-form.select name="category_id" label="Kategori" placeholder="Semua Kategori">
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                            {{ $category->name }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div>
                <x-form.select name="product_id" label="Produk" placeholder="Semua Produk">
                    @foreach($products as $product)
                        <option value="{{ $product->id }}" {{ request('product_id') == $product->id ? 'selected' : '' }}>
                            {{ $product->name }}
                        </option>
                    @endforeach
                </x-form.select>
            </div>

            <div>
                <x-form.select name="material_id" label="Bahan" 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="sm:col-span-2 xl:col-span-6 flex items-end gap-2">
                <button type="submit" class="h-11 rounded-xl bg-brand-500 px-5 text-sm font-bold text-white hover:bg-brand-600">
                    Terapkan
                </button>
                <a
                    href="{{ route('reports.clicks') }}"
                    class="h-11 flex items-center justify-center rounded-xl border border-gray-300 px-4 text-sm font-bold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300"
                >
                    Reset
                </a>
            </div>
        </form>
    </div>

    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center gap-3">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Detail Penjualan per Produk &amp; Bahan</h3>

                    @if(\Illuminate\Support\Facades\Route::has('print.laporan-klik'))
                        <a
                            href="{{ route('print.laporan-klik', array_merge(
                                ['start_date' => $startDate, 'end_date' => $endDate],
                                request()->only(['machine_id', 'category_id', 'product_id', 'material_id'])
                            )) }}"
                            target="_blank"
                            class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600 transition-colors"
                        >
                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
                            </svg>
                            Cetak
                        </a>
                    @endif
                </div>

                @if($reportData->total() > 0)
                    <div class="flex items-center gap-3">
                        <div class="flex items-center gap-2">
                            <label class="text-sm text-gray-500 dark:text-gray-400">Tampilkan</label>
                            <select
                                onchange="window.location.href = updateQueryParam(window.location.href, 'per_page', this.value)"
                                class="h-9 rounded-lg border border-gray-300 bg-transparent px-3 text-sm text-gray-700 focus:border-brand-500 focus:outline-none dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300"
                            >
                                @foreach([10, 15, 25, 50] as $option)
                                    <option value="{{ $option }}" {{ request('per_page', 15) == $option ? 'selected' : '' }}>{{ $option }}</option>
                                @endforeach
                            </select>
                        </div>
                        <span class="text-sm text-gray-500 dark:text-gray-400">
                            {{ $reportData->firstItem() }}-{{ $reportData->lastItem() }} dari {{ number_format($reportData->total()) }}
                        </span>
                    </div>
                @endif
            </div>
        </div>

        @if($reportData->count() > 0)
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900/50">
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Produk</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Bahan</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Mesin</th>
                            <th class="px-5 py-3 text-center text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Order</th>
                            <th class="px-5 py-3 text-center text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Qty</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Total Klik</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Biaya/Klik</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Total Biaya</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                        @foreach($reportData as $row)
                            <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02] transition-colors">
                                <td class="px-5 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{{ $row->product_name ?: '-' }}</td>
                                <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">{{ $row->material_name ?: '-' }}</td>
                                <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">{{ $row->machine_names ?? ($materialMachines[$row->material_id] ?? '-') }}</td>
                                <td class="px-5 py-4 text-center text-sm text-gray-800 dark:text-white/90">{{ number_format($row->total_orders ?? 0) }}</td>
                                <td class="px-5 py-4 text-center text-sm text-gray-800 dark:text-white/90">{{ number_format($row->total_qty ?? 0) }}</td>
                                <td class="px-5 py-4 text-right text-sm font-semibold text-brand-600 dark:text-brand-400">{{ number_format($row->total_clicks ?? 0) }}</td>
                                <td class="px-5 py-4 text-right text-sm text-gray-800 dark:text-white/90">Rp {{ number_format($row->cost_per_click ?? ($materialMachineCostPerClick[$row->material_id] ?? 0), 0, ',', '.') }}</td>
                                <td class="px-5 py-4 text-right text-sm font-semibold text-error-600 dark:text-error-400">Rp {{ number_format($row->total_cost ?? 0, 0, ',', '.') }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot class="border-t-2 border-gray-300 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50">
                        <tr>
                            <td colspan="5" class="px-5 py-4 text-sm font-semibold text-gray-800 dark:text-white/90">Total</td>
                            <td class="px-5 py-4 text-right text-base font-bold text-brand-600 dark:text-brand-400">{{ number_format($syncedTotalClicks) }}</td>
                            <td class="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">-</td>
                            <td class="px-5 py-4 text-right text-base font-bold text-error-600 dark:text-error-400">Rp {{ number_format($syncedTotalCost, 0, ',', '.') }}</td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            @if(method_exists($reportData, 'hasPages') && $reportData->hasPages())
                <div class="border-t border-gray-200 px-5 py-4 dark:border-gray-800">
                    {{ $reportData->links() }}
                </div>
            @endif
        @else
            <div class="p-10 text-center">
                <svg class="mx-auto h-12 w-12 text-gray-300 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                </svg>
                <h3 class="mt-3 text-sm font-medium text-gray-900 dark:text-white">Tidak ada data</h3>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                    @if($products->count() == 0 && $materials->count() == 0)
                        Belum ada produk atau bahan dengan tracking klik yang diaktifkan.
                    @else
                        Tidak ada order dalam periode yang dipilih.
                    @endif
                </p>
            </div>
        @endif
    </div>

    <div class="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <h4 class="mb-3 text-sm font-semibold text-gray-800 dark:text-white/90">Produk dengan Tracking Aktif</h4>
            @if($products->count() > 0)
                <div class="flex flex-wrap gap-2">
                    @foreach($products as $product)
                        <span class="inline-flex rounded-full bg-brand-100 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-500/15 dark:text-brand-400">
                            {{ $product->name }}
                        </span>
                    @endforeach
                </div>
            @else
                <p class="text-sm text-gray-500 dark:text-gray-400">Tidak ada produk dengan tracking aktif</p>
            @endif
        </div>

        <div class="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
            <h4 class="mb-3 text-sm font-semibold text-gray-800 dark:text-white/90">Bahan dengan Tracking Aktif</h4>
            @if($materials->count() > 0)
                <div class="flex flex-wrap gap-2">
                    @foreach($materials as $material)
                        <span class="inline-flex rounded-full bg-success-100 px-2.5 py-1 text-xs font-medium text-success-700 dark:bg-success-500/15 dark:text-success-400">
                            {{ $material->name }}
                        </span>
                    @endforeach
                </div>
            @else
                <p class="text-sm text-gray-500 dark:text-gray-400">Tidak ada bahan dengan tracking aktif</p>
            @endif
        </div>
    </div>

    @push('scripts')
        <script>
            function updateQueryParam(url, param, value) {
                const urlObj = new URL(url);
                urlObj.searchParams.set(param, value);
                urlObj.searchParams.delete('page');
                return urlObj.toString();
            }
        </script>
    @endpush

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const chartEl = document.getElementById('clicksChart');
                const dailyData = @json($dailyData);

                const formatNumber = value => Number(value || 0).toLocaleString('id-ID');

                const seriesData = dailyData.map(item => ({
                    x: new Date(item.date).getTime(),
                    y: parseInt(item.total_clicks || 0),
                }));

                const values = seriesData.map(item => item.y);
                const minValue = values.length ? Math.min(...values) : 0;
                const avgValue = values.length
                    ? Math.round(values.reduce((total, value) => total + value, 0) / values.length)
                    : 0;

                const chartOptions = {
                    series: [
                        {
                            name: 'Klik Harian',
                            data: seriesData,
                        },
                    ],
                    chart: {
                        fontFamily: 'Outfit, sans-serif',
                        type: 'area',
                        height: 350,
                        background: 'transparent',
                        zoom: {
                            enabled: true,
                            type: 'x',
                            autoScaleYaxis: true,
                        },
                        toolbar: {
                            show: true,
                            offsetX: 0,
                            offsetY: -2,
                            tools: {
                                download: true,
                                selection: true,
                                zoom: true,
                                zoomin: true,
                                zoomout: true,
                                pan: true,
                                reset: true,
                            },
                        },
                        animations: {
                            enabled: true,
                            easing: 'easeinout',
                            speed: 500,
                        },
                    },
                    colors: ['#00E396'],
                    dataLabels: {
                        enabled: false,
                    },
                    stroke: {
                        curve: 'straight',
                        width: 2,
                    },
                    fill: {
                        type: 'gradient',
                        gradient: {
                            shadeIntensity: 1,
                            opacityFrom: 0.28,
                            opacityTo: 0.03,
                            stops: [0, 100],
                        },
                    },
                    markers: {
                        size: 0,
                        hover: {
                            size: 5,
                        },
                    },
                    grid: {
                        borderColor: '#e5e7eb',
                        strokeDashArray: 4,
                        xaxis: {
                            lines: {
                                show: false,
                            },
                        },
                        yaxis: {
                            lines: {
                                show: true,
                            },
                        },
                    },
                    xaxis: {
                        type: 'datetime',
                        axisBorder: {
                            show: false,
                        },
                        axisTicks: {
                            show: false,
                        },
                        labels: {
                            datetimeUTC: false,
                            style: {
                                colors: '#9ca3af',
                                fontSize: '12px',
                            },
                        },
                        tooltip: {
                            enabled: false,
                        },
                    },
                    yaxis: {
                        opposite: true,
                        min: minValue > 0 ? 0 : undefined,
                        labels: {
                            formatter: function (value) {
                                return Math.round(value).toLocaleString('id-ID');
                            },
                            style: {
                                colors: '#9ca3af',
                                fontSize: '12px',
                            },
                        },
                    },
                    annotations: {
                        yaxis: values.length
                            ? [
                                {
                                    y: avgValue,
                                    borderColor: '#f59e0b',
                                    strokeDashArray: 4,
                                    label: {
                                        borderColor: '#f59e0b',
                                        style: {
                                            color: '#ffffff',
                                            background: '#f59e0b',
                                            fontSize: '11px',
                                            fontWeight: 600,
                                        },
                                        text: 'Rata-rata: ' + formatNumber(avgValue),
                                    },
                                },
                            ]
                            : [],
                    },
                    tooltip: {
                        theme: 'light',
                        shared: false,
                        x: {
                            format: 'dd MMM yyyy',
                        },
                        y: {
                            formatter: function (value) {
                                return formatNumber(value) + ' klik';
                            },
                        },
                    },
                    noData: {
                        text: 'Belum ada data klik harian',
                    },
                };

                if (chartEl && typeof ApexCharts !== 'undefined') {
                    chartEl.innerHTML = '';
                    const chart = new ApexCharts(chartEl, chartOptions);
                    chart.render();
                }
            });
        </script>
    @endpush
@endsection
