<div class="dashboard-container">

    <div class="grid-2-1">
        <div class="grid-4">
            <a class="dashboard-card dashboard-card-link" href="#" wire:click="addMember()">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Aggiungi utente</div>
                    <i class="dashboard-card-icon fa-solid fa-user-plus"></i>
                </div>
            </a>

            <a class="dashboard-card dashboard-card-link" href="#" wire:click="addSupplier()">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Aggiungi fornitore</div>
                    <i class="dashboard-card-icon fa-solid fa-user-cog"></i>
                </div>
            </a>

            <a class="dashboard-card dashboard-card-link" href="#" wire:click="addIn()">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Aggiungi entrata</div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-trend-up"></i>
                </div>
            </a>

            <a class="dashboard-card dashboard-card-link" href="#" wire:click="addOut()">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Aggiungi uscita</div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-transfer"></i>
                </div>
            </a>

            <div class="dashboard-card dashboard-stat">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Utenti Totali</div>
                    <i class="dashboard-card-icon fa-solid fa-user"></i>
                </div>
                <div class="dashboard-card-value">{{$activeUsers}}</div>
                <div class="dashboard-card-info"><span {{$activeUsers> 0 ? 'class=more' : 'class=less'}}>{{$activeUsers}}</span> dal mese scorso</div>
            </div>

            <div class="dashboard-card dashboard-stat">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Tesserati</div>
                    <i class="dashboard-card-icon fa-solid fa-address-card"></i>
                </div>
                <div class="dashboard-card-value">{{$registeredUsers}}</div>
                <div class="dashboard-card-info"><span {{$registeredUsers> 0 ? 'class=more' : 'class=less'}}>{{$registeredUsers}}</span> dal mese scorso</div>
            </div>

            <div class="dashboard-card dashboard-stat">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Certificati scaduti</div>
                    <i class="dashboard-card-icon fa-solid fa-file-lines"></i>
                </div>
                <div class="dashboard-card-value">{{$expiredCertificates}}</div>
                <div class="dashboard-card-info"><span {{$expiredCertificates> 0 ? 'class=more' : 'class=less'}}>{{$expiredCertificates}}</span> dal mese scorso</div>
            </div>

            <div class="dashboard-card dashboard-stat">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Abbonamenti sospesi</div>
                    <i class="dashboard-card-icon fa-solid fa-user-xmark"></i>
                </div>
                <div class="dashboard-card-value">{{$suspendedSubscriptions}}</div>
                <div class="dashboard-card-info"><span {{$suspendedSubscriptions> 0 ? 'class=more' : 'class=less'}}>{{$suspendedSubscriptions}}</span> dal mese scorso</div>
            </div>
    
            <!-- Corsi Section -->
            <div class="dashboard-card grid-w-3">
                <div class="dashboard-card-title">Corsi</div>
                @if(count($courses) > 0)
                <div class="courses-list">
                    @foreach($courses as $course)
                    @php
                        $course_time = trim(str_replace(" - ", "\n", $course['time']));
                    @endphp
                    <div class="course-item">
                        <div class="course-time">{{$course_time}}</div>
                        <div class="course-divider"></div>
                        <div class="course-name">{{$course['full_name'] ?? $course['course_name']}}</div>
                        {{-- <div class="course-days">{{$course['days']}}</div> --}}
                    </div>
                    @endforeach
                </div>
                @else
                <div style="text-align: center; color: #666; padding: 40px;">
                    Nessun corso programmato per oggi
                    <div style="font-size: 12px; margin-top: 10px; color: #999;">
                        Oggi è: <strong>{{$dayName ?? 'N/A'}}</strong>
                    </div>
                </div>
                @endif
            </div>
            <div class="d-flex flex-column gap-4">
                <div class="dashboard-card dashboard-stat">
                    <div class="dashboard-card-header">
                        <div class="dashboard-card-title">Corsi attivi</div>
                        <i class="dashboard-card-icon fa-solid fa-book-open"></i>
                    </div>
                    <div class="dashboard-card-value">{{$active_courses}}</div>
                </div>
                <div class="dashboard-card dashboard-stat">
                    <div class="dashboard-card-header">
                        <div class="dashboard-card-title">Abbonamenti attivi</div>
                        <i class="dashboard-card-icon fa-solid fa-book-open"></i>
                    </div>
                    <div class="dashboard-card-value">{{$active_subscriptions}}</div>
                </div>
            </div>
            
            {{-- campi e sale --}}
            {{-- <div class="dashboard-card"> --}}
                {{-- <div class="dashboard-card-title">Campi e sale</div> --}}
            {{-- </div> --}}

            {{-- grafico --}}
            {{-- <div class="dashboard-card grid-w-2"></div> --}}
        </div>
        
        <!-- To Do Section -->
        <div class="card-inverted d-flex dashboard-card flex-column justify-content-between">
            <div>
                <div class="dashboard-card-title">To do</div>
                {{-- <div style="font-size: 14px; color: #666; margin-bottom: 10px;">{{date('d/m/Y')}}</div> --}}
        
                <!-- Notes List -->
                @if(count($savedNotes) > 0)
                <div class="notes-list">
                    @foreach($savedNotes as $note)
                    <div class="note-item">
                        <div class="note-content">
                            <div class="note-text">{{$note['text']}}</div>
                            <div class="note-date">{{$note['created_at']}}</div>
                        </div>
                        <div class="note-checkbox" wire:click="completeNote('{{$note['id']}}')" title="Segna come completato">
                            ✓
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div class="empty-notes">
                    Nessuna nota salvata
                </div>
                @endif
            </div>
    
            <!-- Add Note Section -->
            <div class="notes-section">
                <textarea class="notes-input" placeholder="Inserisci una nuova nota..." wire:model="notes"></textarea>
                <button class="save-btn" wire:click="saveNote">SALVA</button>
            </div>
        </div>
    </div>

    <div class="grid-2">
        <!-- Courses Participation Section -->
        <div class="dashboard-card">
            <div class="dashboard-card-title">Corsi con più iscritti</div>
            @if(count($active_member_courses) > 0)
            <div style="padding: 20px 0 0;">
                @foreach($active_member_courses as $course)
                <div style="margin-bottom: 30px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                        <span style="font-weight: bold; color: var(--color-text); font-size: 13px;">{{$course['name']}}</span>
                        {{-- <span style="font-size: 12px; color: #666;">{{$course['participants']}} partecipanti</span> --}}
                    </div>
                    <div class="participation-bar">
                        <div class="participation-fill" style="width: {{($course['count'] * 100) / $active_member_courses_count}}%"></div>
                    </div>
                </div>
                @endforeach
            </div>
            @else
            <div style="text-align: center; color: #666; padding: 40px;">
                Nessun corso con partecipazioni
            </div>
            @endif
        </div>

        <!-- User Statistics Cards -->
        <div class="dashboard-card">
            <div class="dashboard-card-title">Ultimi utenti registrati</div>
            @if(count($recentUsers) > 0)
            <table class="recent-users-table">
                <thead>
                    <tr>
                        <th>Cognome</th>
                        <th>Nome</th>
                        <th>Telefono</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($recentUsers as $user)
                    <tr>
                        <td>{{$user['surname']}}</td>
                        <td>{{$user['name']}}</td>
                        <td>{{$user['phone']}}</td>
                        <td>{{$user['email']}}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            @else
            <div style="text-align: center; color: #666; padding: 40px;">
                Nessun utente registrato di recente
            </div>
            @endif
        </div>
    </div>

    @php
        $current_month = now()->locale('it-IT')->translatedFormat("M Y");
    @endphp
    <div class="grid-2">
        <div class="grid-3">
            <!-- Financial Cards moved here -->

            {{-- <div class="dashboard-card dashboard-stat card-inverted card-receive">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Da incassare<br/><small><small><i>{{$current_month}}</i></small></small></div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-trend-up"></i>
                </div>
                <div class="dashboard-card-value">{{number_format($toPay, 2, ",", ".")}}</div>
            </div> --}}

            <div class="dashboard-card dashboard-stat card-inverted card-income">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Incassato<br/><small><small><i>{{$current_month}}</i></small></small></div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-trend-up"></i>
                </div>
                <div class="dashboard-card-value">{{number_format($received, 2, ",", ".")}}</div>
            </div>

            <div class="dashboard-card dashboard-stat card-inverted card-expense">
                <div class="dashboard-card-header">
                    <div class="dashboard-card-title">Pagato<br/><small><small><i>{{$current_month}}</i></small></small></div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-transfer"></i>
                </div>
                <div class="dashboard-card-value">{{number_format($paid, 2, ",", ".")}}</div>
            </div>

            <div class="dashboard-card dashboard-stat card-inverted card-topay">
                <div class="dashboard-card-header">
                    {{-- <div class="dashboard-card-title">Da pagare<br/><small><small><i>{{$current_month}}</i></small></small></div> --}}
                    <div class="dashboard-card-title">Da pagare<br/><small><small><i>&nbsp;</i></small></small></div>
                    <i class="dashboard-card-icon fa-solid fa-money-bill-transfer"></i>
                </div>
                <div class="dashboard-card-value">{{number_format($toPay, 2, ",", ".")}}</div>
            </div>

            <div class="dashboard-card grid-w-3">
                <div class="dashboard-card-title">Ultimi movimenti finanziari</div>
                @if(count($recentTransactions) > 0)
                <div class="transaction-list">
                    @foreach($recentTransactions as $transaction)
                    <div class="transaction-item">
                        <div class="transaction-name">{{$transaction['name']}}</div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div class="transaction-amount">€ {{number_format($transaction['amount'], 2)}}</div>
                            <div class="transaction-type {{$transaction['type'] == 'ENTRATA' ? 'income' : 'expense'}}">
                                {{$transaction['type']}}
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div style="text-align: center; color: #666; padding: 40px;">
                    Nessun movimento finanziario recente
                </div>
                @endif
            </div>
        </div>
        
        <div class="dashboard-card" wire:ignore>
            <canvas id="dashboard-chart"></canvas>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    // window.addEventListener('note-saved', event => {
    //     // Show success message
    //     if (typeof toastr !== 'undefined') {
    //         toastr.success('Nota salvata con successo!');
    //     } else {
    //         alert('Nota salvata con successo!');
    //     }
    // });

    window.addEventListener('courses-activated', event => {
        if (typeof toastr !== 'undefined') {
            toastr.success(event.detail.message);
        } else {
            alert(event.detail.message);
        }
    });

    window.addEventListener('debug-completed', event => {
        if (typeof toastr !== 'undefined') {
            toastr.info('Debug completato - controlla i log');
        } else {
            alert('Debug completato - controlla i log');
        }
    });

    // Optional: Add keyboard shortcut to save note
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'Enter') {
            let textarea = document.querySelector('.notes-input');
            if (textarea === document.activeElement) {
                Livewire.emit('saveNote');
            }
        }
    });
</script>

<script>
    function createDashboardChart() {
        const chartId = `dashboard-chart`;
        const canvas = document.getElementById(chartId);
        if (!canvas) {
            console.error('Canvas not found for ID:', chartId);
            return;
        }

        const ctx = canvas.getContext('2d');

        const incomeGradient = ctx.createLinearGradient(0, 0, 0, 400);
        incomeGradient.addColorStop(0, 'rgba(0, 184, 148, 1)');
        incomeGradient.addColorStop(1, 'rgba(0, 184, 148, 1)');

        const expenseGradient = ctx.createLinearGradient(0, 0, 0, 400);
        expenseGradient.addColorStop(0, 'rgba(255, 107, 107, 1)');
        expenseGradient.addColorStop(1, 'rgba(255, 107, 107, 1)');

        const chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [
                    'Gennaio',
                    'Febbraio',
                    'Marzo',
                    'Aprile',
                    'Maggio',
                    'Giugno',
                    'Luglio',
                    'Agosto',
                    'Settembre',
                    'Ottobre',
                    'Novembre',
                    'Dicembre',
                ],
                datasets: [
                    {
                        label: 'Entrate',
                        data: Array.from({length: 12}, () => Math.floor(Math.random() * (100)) + 1),
                        backgroundColor: incomeGradient,
                        borderColor: '#00b894',
                        borderWidth: 0,
                        borderRadius: {
                            topLeft: 8,
                            topRight: 8,
                            bottomLeft: 0,
                            bottomRight: 0,
                        },
                        borderSkipped: false,
                        barThickness: "flex",
                        barPercentage: 0.65,
                        categoryPercentage: 0.4,
                    },
                    {
                        label: 'Uscite',
                        data: Array.from({length: 12}, () => Math.floor(Math.random() * (100)) + 1),
                        backgroundColor: expenseGradient,
                        borderColor: '#ff6b6b',
                        borderWidth: 0,
                        borderRadius: {
                            topLeft: 8,
                            topRight: 8,
                            bottomLeft: 0,
                            bottomRight: 0,
                        },
                        borderSkipped: false,
                        barThickness: "flex",
                        barPercentage: 0.65,
                        categoryPercentage: 0.4,
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            pointStyle: "rect",
                            font: { weight: '500' }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 1)',
                        titleColor: '#212529',
                        bodyColor: '#495057',
                        borderColor: '#e9ecef',
                        borderWidth: 2,
                        cornerRadius: 0,
                        callbacks: {
                            label: function (context) {
                                return context.dataset.label + ': €' +
                                    new Intl.NumberFormat('it-IT', {minimumFractionDigits: 2, maximumFractionDigits: 2}).format(context.parsed.y);
                            }
                        }
                    },
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { font: { weight: '500' } }
                    },
                    y: {
                        beginAtZero: true,
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: {
                            callback: function (value) {
                                return '€' + new Intl.NumberFormat('it-IT', {minimumFractionDigits: 2, maximumFractionDigits: 2}).format(value);
                            }
                        }
                    }
                },
                elements: {
                    bar: {
                        borderRadius: {
                            topLeft: 8,
                            topRight: 8,
                            bottomLeft: 0,
                            bottomRight: 0
                        }
                    }
                },
                animation: {
                    duration: 1000,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function () {
        createDashboardChart();
    });
</script>
@endpush