<div>
    <div class="card">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">WIP Tracking</h5>

                <div class="d-flex gap-2">
                    <input type="date" class="form-control form-control-sm" wire:model.live="selectedDate">
                </div>
            </div>

            <ul class="nav nav-tabs mt-3" role="tablist">
                <li class="nav-item">
                <button
                    class="nav-link {{ $activeTab === 'daily' ? 'active' : '' }}"
                    type="button"
                    wire:click="setActiveTab('daily')"
                >
                    Daily
                </button>
                </li>

                <li class="nav-item">
                <button
                    class="nav-link {{ $activeTab === 'weekly' ? 'active' : '' }}"
                    type="button"
                    wire:click="setActiveTab('weekly')"
                >
                    Weekly
                </button>
                </li>

                <li class="nav-item">
                <button
                    class="nav-link {{ $activeTab === 'monthly' ? 'active' : '' }}"
                    type="button"
                    wire:click="setActiveTab('monthly')"
                >
                    Monthly
                </button>
                    
                </li>
            </ul>
        </div>

        <div class="card-body tab-content">
        <div class="tab-pane fade {{ $activeTab === 'daily' ? 'show active' : '' }}" id="daily-tab">
            <div style="height:500px;" wire:ignore>
    <canvas id="dailyWipChart"></canvas>
</div>

            <div class="mt-4">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0">
                    Daily WIP Entries
                    @if($dailyUserId)
                        <span class="text-muted">(Selected user)</span>
                    @endif
                </h6>

                <div class="d-flex gap-2">
                    @if($dailyUserId)
                        <button type="button" class="btn btn-sm btn-outline-secondary" wire:click="$set('dailyUserId', null)">
                            Show All
                        </button>
                    @endif

                    <input
                        type="text"
                        class="form-control form-control-sm"
                        placeholder="Search user, client, action, description..."
                        wire:model.live.debounce.300ms="dailySearch"
                        style="width: 320px;"
                    >
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-sm table-bordered align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Time</th>
                            <th>User</th>
                           
                            <th>Client Reference</th>
                            <th>Action</th>
                            <th>Units</th>
                            <th>Hours</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                    @forelse($dailyEntries as $entry)
                        <tr wire:key="daily-wip-entry-{{ $entry->id }}">
                            <td>{{ $entry->started_at?->format('H:i') }}</td>

                            <td>
                                {{ trim(($entry->user_name_first ?? '') . ' ' . ($entry->user_name_last ?? '')) ?: '-' }}
                            </td>

                            <td>
                                @if($entry->joined_client_id)
                                    <a href="{{ route('clients.show', $entry->client_slug) }}" wire:navigate>
                                        {{ '1' . str_pad($entry->joined_client_id, 5, '0', STR_PAD_LEFT) }}
                                    </a>
                                    -
                                    {{ trim(($entry->client_name_first ?? '') . ' ' . ($entry->client_name_last ?? '')) ?: '-' }}
                                @else
                                    - {{$entry->client_id ?? $entry->id}}
                                @endif
                            </td>

                            <td>{{ ucfirst($entry->activity_type) }}</td>
                            <td>{{ $entry->units }}</td>
                            <td>{{ $entry->hours }}</td>
                            <td>{{ $entry->description }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="text-center text-muted">
                                No WIP entries found for this date.
                            </td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </div>
            </div>

            <div class="tab-pane fade {{ $activeTab === 'weekly' ? 'show active' : '' }}" id="weekly-tab">
            <div style="height:500px;" wire:ignore>
    <canvas id="weeklyWipChart"></canvas>
</div>
            </div>

            <div class="tab-pane fade {{ $activeTab === 'monthly' ? 'show active' : '' }}" id="monthly-tab">
            <div style="height:500px;" wire:ignore>
    <canvas id="monthlyWipChart"></canvas>
</div>
            <div class="table-responsive mt-3">
            <table class="table table-bordered table-sm text-center mb-0">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Jan</th>
                        <th>Feb</th>
                        <th>Mar</th>
                        <th>Apr</th>
                        <th>May</th>
                        <th>Jun</th>
                        <th>Jul</th>
                        <th>Aug</th>
                        <th>Sep</th>
                        <th>Oct</th>
                        <th>Nov</th>
                        <th>Dec</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($monthlyTableData as $row)
                        <tr>
                            <td class="text-start fw-semibold">
                                {{ $row['name'] }}
                            </td>

                            @foreach($row['months'] as $value)
                                <td>{{ number_format($value) }}</td>
                            @endforeach
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
                
            </div>
        </div>
    </div>

    @script

<script>
    let dailyChart = null;
    let weeklyChart = null;
    let monthlyChart = null;

    function resetCanvas(canvasId) {
        const oldCanvas = document.getElementById(canvasId);

        if (!oldCanvas) {
            return null;
        }

        const parent = oldCanvas.parentElement;
        const newCanvas = document.createElement('canvas');

        newCanvas.id = canvasId;

        parent.innerHTML = '';
        parent.appendChild(newCanvas);

        return newCanvas;
    }

    function destroyChart(chart) {
        if (chart) {
            chart.destroy();
        }
    }

    function renderChart(canvasId, chartData, period, oldChart) {
        destroyChart(oldChart);

        const canvas = resetCanvas(canvasId);

        if (!canvas || !window.Chart) {
            return null;
        }

        return new Chart(canvas, {
            type: chartData.type,
            data: {
                labels: chartData.labels,
                datasets: chartData.datasets.map(dataset => ({
                    ...dataset,
                    tension: chartData.type === 'line' ? 0.35 : 0,
                    fill: false
                }))
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                onClick(event, elements, chart) {
                    if (!elements.length) {
                        return;
                    }

                    const element = elements[0];
                    const dataset = chart.data.datasets[element.datasetIndex];
                    const label = chart.data.labels[element.index];

                    $wire.showEntries(period, dataset.userId, label);
                },
                plugins: {
                    title: {
                        display: true,
                        text: chartData.title,
                        font: {
                            size: 22,
                            weight: 'bold'
                        }
                    },
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Units Completed'
                        }
                    }
                }
            }
        });
    }

    function renderAllCharts(dailyData, weeklyData, monthlyData) {
        dailyChart = renderChart('dailyWipChart', dailyData, 'daily', dailyChart);
        weeklyChart = renderChart('weeklyWipChart', weeklyData, 'weekly', weeklyChart);
        monthlyChart = renderChart('monthlyWipChart', monthlyData, 'monthly', monthlyChart);

        setTimeout(() => {
            dailyChart?.resize();
            weeklyChart?.resize();
            monthlyChart?.resize();
        }, 200);
    }

    renderAllCharts(
        @json($dailyData),
        @json($weeklyData),
        @json($monthlyData)
    );

    Livewire.on('wip-charts-updated', event => {
        renderAllCharts(
            event.dailyData,
            event.weeklyData,
            event.monthlyData
        );
    });

    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
        tab.addEventListener('shown.bs.tab', () => {
            setTimeout(() => {
                dailyChart?.resize();
                weeklyChart?.resize();
                monthlyChart?.resize();
            }, 200);
        });
    });
</script>
@endscript