@extends('layouts.app')

@section('content')
<div class="finance-form-container">
    <div class="form-header" data-aos="fade-down">
        <h1 class="form-title">
            <i class="fas fa-plus-circle"></i>
            เพิ่มรายการใหม่
        </h1>
        <a href="{{ route('finance.records.index') }}" class="btn-back">
            <i class="fas fa-arrow-left"></i> กลับ
        </a>
    </div>

    <form method="POST" action="{{ route('finance.records.store') }}" 
          class="finance-form" id="recordForm" data-aos="fade-up">
        @csrf

        <!-- Type Selection -->
        <div class="type-selector">
            <label class="type-option">
                <input type="radio" name="type" value="income" 
                       {{ old('type', $type) === 'income' ? 'checked' : '' }}
                       onchange="loadCategories(this.value)">
                <div class="type-card income">
                    <i class="fas fa-arrow-circle-up"></i>
                    <span>รายรับ</span>
                    <small>บันทึกเงินที่ได้รับ</small>
                </div>
            </label>
            <label class="type-option">
                <input type="radio" name="type" value="expense" 
                       {{ old('type', $type) === 'expense' ? 'checked' : '' }}
                       onchange="loadCategories(this.value)">
                <div class="type-card expense">
                    <i class="fas fa-arrow-circle-down"></i>
                    <span>รายจ่าย</span>
                    <small>บันทึกค่าใช้จ่าย</small>
                </div>
            </label>
        </div>

        <div class="form-grid">
            <!-- Date -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-calendar"></i> วันที่
                    <span class="required">*</span>
                </label>
                <input type="date" 
                       name="record_date" 
                       class="form-control @error('record_date') is-invalid @enderror"
                       value="{{ old('record_date', date('Y-m-d')) }}"
                       max="{{ date('Y-m-d') }}"
                       required>
                @error('record_date')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Category -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-tag"></i> หมวดหมู่
                    <span class="required">*</span>
                </label>
                <select name="category" 
                        class="form-control category-select @error('category') is-invalid @enderror"
                        id="categorySelect"
                        required>
                    <option value="">-- เลือกหมวดหมู่ --</option>
                    @foreach($categories as $value => $name)
                        <option value="{{ $value }}" 
                                {{ old('category') == $value ? 'selected' : '' }}>
                            {{ $name }}
                        </option>
                    @endforeach
                </select>
                @error('category')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
            </div>

            <!-- Amount -->
            <div class="form-group">
                <label class="form-label">
                    <i class="fas fa-coins"></i> จำนวนเงิน
                    <span class="required">*</span>
                </label>
                <div class="input-group">
                    <span class="input-addon">฿</span>
                    <input type="number" 
                           name="amount" 
                           class="form-control amount-input @error('amount') is-invalid @enderror"
                           value="{{ old('amount') }}"
                           step="0.01"
                           min="0.01"
                           max="9999999.99"
                           placeholder="0.00"
                           required>
                </div>
                @error('amount')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
                <small class="form-hint">กรอกจำนวนเงินที่ต้องการบันทึก</small>
            </div>

            <!-- Note -->
            <div class="form-group full-width">
                <label class="form-label">
                    <i class="fas fa-sticky-note"></i> หมายเหตุ
                </label>
                <textarea name="note" 
                          class="form-control @error('note') is-invalid @enderror"
                          rows="3"
                          maxlength="500"
                          placeholder="รายละเอียดเพิ่มเติม (ถ้ามี)">{{ old('note') }}</textarea>
                @error('note')
                    <span class="invalid-feedback">{{ $message }}</span>
                @enderror
                <small class="form-hint">
                    <span id="charCount">0</span>/500 ตัวอักษร
                </small>
            </div>

            <!-- Recurring -->
            <div class="form-group full-width">
                <div class="recurring-section">
                    <label class="checkbox-label">
                        <input type="checkbox" 
                               name="is_recurring" 
                               value="1"
                               id="recurringCheck"
                               {{ old('is_recurring') ? 'checked' : '' }}>
                        <span class="checkbox-custom"></span>
                        <span class="checkbox-text">
                            <i class="fas fa-sync"></i>
                            รายการซ้ำ (สร้างรายการล่วงหน้า)
                        </span>
                    </label>
                    
                    <div id="recurringOptions" class="recurring-options" style="display: {{ old('is_recurring') ? 'block' : 'none' }};">
                        <div class="form-group">
                            <label class="form-label">
                                <i class="fas fa-clock"></i> ความถี่
                            </label>
                            <select name="recurring_type" class="form-control">
                                <option value="daily" {{ old('recurring_type') == 'daily' ? 'selected' : '' }}>
                                    ทุกวัน
                                </option>
                                <option value="weekly" {{ old('recurring_type') == 'weekly' ? 'selected' : '' }}>
                                    ทุกสัปดาห์
                                </option>
                                <option value="monthly" {{ old('recurring_type') == 'monthly' ? 'selected' : '' }}>
                                    ทุกเดือน
                                </option>
                                <option value="yearly" {{ old('recurring_type') == 'yearly' ? 'selected' : '' }}>
                                    ทุกปี
                                </option>
                            </select>
                            <small class="form-hint">
                                <i class="fas fa-info-circle"></i>
                                ระบบจะสร้างรายการล่วงหน้า 3 เดือน
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-actions">
            <button type="submit" class="btn btn-primary" id="submitBtn">
                <i class="fas fa-save"></i>
                บันทึกรายการ
            </button>
            <button type="button" class="btn btn-secondary" onclick="saveDraft()">
                <i class="fas fa-file-alt"></i>
                บันทึกร่าง
            </button>
            <a href="{{ route('finance.records.index') }}" class="btn btn-outline">
                <i class="fas fa-times"></i>
                ยกเลิก
            </a>
        </div>
    </form>

    <!-- Category Preview -->
    <div class="category-preview" data-aos="fade-up">
        <h3 class="preview-title">
            <i class="fas fa-th-large"></i>
            หมวดหมู่ที่มี
        </h3>
        <div id="categoryList" class="category-list">
            <!-- Categories will be loaded here -->
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="quick-stats" data-aos="fade-up">
        <h3 class="stats-title">
            <i class="fas fa-chart-line"></i>
            สถิติเดือนนี้
        </h3>
        <div class="stats-row">
            <div class="stat-item income">
                <i class="fas fa-arrow-up"></i>
                <div>
                    <small>รายรับ</small>
                    <strong>฿{{ number_format(0, 2) }}</strong>
                </div>
            </div>
            <div class="stat-item expense">
                <i class="fas fa-arrow-down"></i>
                <div>
                    <small>รายจ่าย</small>
                    <strong>฿{{ number_format(0, 2) }}</strong>
                </div>
            </div>
            <div class="stat-item balance">
                <i class="fas fa-balance-scale"></i>
                <div>
                    <small>คงเหลือ</small>
                    <strong>฿{{ number_format(0, 2) }}</strong>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css">
<style>
:root {
    --primary: #4f46e5;
    --primary-light: #6366f1;
    --success: #10b981;
    --danger: #ef4444;
    --gray-100: #f9fafb;
    --gray-200: #f3f4f6;
    --gray-300: #e5e7eb;
    --gray-500: #6b7280;
    --gray-700: #374151;
    --gray-900: #111827;
    --radius: 8px;
    --transition: all 0.2s ease-in-out;
}

/* ให้ layout หลักเต็มจอ */
html, body {
    height: 100%;
    margin: 0;
    background: var(--gray-100);
}

/* กำหนด container ให้ยืดเต็ม content */
.finance-form-container {
    width: 100%;
    min-height: calc(100vh - 80px); /* 80px = ความสูง header ถ้ามี */
    margin: 0;
    border-radius: 0;
    padding: 2rem;
    box-shadow: none;
    background: #fff;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

/* ทำให้ฟอร์มกินพื้นที่ได้สมดุล */
.finance-form {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* ส่วน Preview & Stats */
.category-preview,
.quick-stats {
    margin-top: auto; /* ดันไปข้างล่าง */
}


/* Header */
.form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
}
.form-title {
    font-size: 1.6rem;
    display: flex;
    gap: .5rem;
    color: var(--gray-900);
}
.btn-back {
    text-decoration: none;
    color: var(--gray-700);
    background: var(--gray-200);
    padding: .5rem 1rem;
    border-radius: var(--radius);
    font-size: .9rem;
    transition: var(--transition);
}
.btn-back:hover { background: var(--gray-300); }

/* Type Selector */
.type-selector {
    display: flex;
    gap: 1rem;
    margin-bottom: 2rem;
    flex-wrap: wrap;
}
.type-option {
    flex: 1;
}
.type-option input { display: none; }
.type-card {
    border: 2px solid var(--gray-200);
    border-radius: var(--radius);
    padding: 1.2rem;
    text-align: center;
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    flex-direction: column;
    gap: .3rem;
}
.type-card i { font-size: 2rem; }
.type-card.income { color: var(--success); }
.type-card.expense { color: var(--danger); }
.type-option input:checked + .type-card {
    border-color: var(--primary);
    background: var(--gray-100);
}

/* Form Grid */
.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 1.5rem;
}
.form-group.full-width { grid-column: span 2; }

/* Labels */
.form-label {
    font-weight: 600;
    color: var(--gray-700);
    display: flex;
    align-items: center;
    gap: .3rem;
    margin-bottom: .4rem;
}
.required { color: var(--danger); }

/* Inputs */
.form-control {
    width: 100%;
    padding: .6rem .8rem;
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: .95rem;
    transition: var(--transition);
}
.form-control:focus {
    border-color: var(--primary);
    outline: none;
}
textarea.form-control { resize: vertical; }

/* Input Group */
.input-group {
    display: flex;
    align-items: center;
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    overflow: hidden;
}
.input-addon {
    background: var(--gray-100);
    padding: .6rem .8rem;
    font-weight: 600;
    color: var(--gray-700);
}
.input-group .form-control {
    border: none;
    padding-left: .5rem;
}

/* Hints & Errors */
.form-hint { font-size: .8rem; color: var(--gray-500); }
.invalid-feedback { color: var(--danger); font-size: .8rem; margin-top: .3rem; }

/* Recurring */
.recurring-section {
    background: var(--gray-100);
    padding: 1rem;
    border-radius: var(--radius);
}
.checkbox-label {
    display: flex;
    align-items: center;
    gap: .5rem;
    cursor: pointer;
}
.checkbox-label input { display: none; }
.checkbox-custom {
    width: 18px; height: 18px;
    border: 2px solid var(--gray-300);
    border-radius: 4px;
    display: inline-block;
}
.checkbox-label input:checked + .checkbox-custom {
    background: var(--primary);
    border-color: var(--primary);
}
.checkbox-text { font-size: .95rem; color: var(--gray-700); }

/* Form Actions */
.form-actions {
    margin-top: 2rem;
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}
.btn {
    display: inline-flex;
    align-items: center;
    gap: .4rem;
    padding: .6rem 1.2rem;
    border-radius: var(--radius);
    font-size: .95rem;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
    border: none;
    text-decoration: none;
    justify-content: center;
}
.btn-primary { background: var(--primary); color: #fff; }
.btn-primary:hover { background: var(--primary-light); }
.btn-secondary { background: var(--gray-200); color: var(--gray-700); }
.btn-outline { border: 1px solid var(--gray-300); background: #fff; color: var(--gray-700); }
.btn-outline:hover { background: var(--gray-100); }

/* Category Preview */
.category-preview, .quick-stats {
    margin-top: 2.5rem;
    padding: 1.2rem;
    background: var(--gray-100);
    border-radius: var(--radius);
}
.preview-title, .stats-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: .5rem;
    color: var(--gray-700);
}
.category-list {
    display: flex;
    flex-wrap: wrap;
    gap: .8rem;
}
.category-item {
    background: #fff;
    padding: .6rem 1rem;
    border-radius: var(--radius);
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    gap: .4rem;
    font-size: .9rem;
    border-left: 4px solid var(--cat-color, var(--gray-300));
}

/* Quick Stats */
.stats-row {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    flex-wrap: wrap;
}
.stat-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: .6rem;
    background: #fff;
    padding: .8rem;
    border-radius: var(--radius);
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.stat-item i { font-size: 1.5rem; }
.stat-item.income i { color: var(--success); }
.stat-item.expense i { color: var(--danger); }
.stat-item.balance i { color: var(--primary); }
.stat-item small { color: var(--gray-500); display: block; }

/* Responsive: Mobile as App-like */
@media (max-width: 768px) {
    .finance-form-container {
        padding: 1rem;
        border-radius: 0;
        box-shadow: none;
    }
    .form-grid {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    .form-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }
    .type-selector { flex-direction: column; }
    .form-actions { flex-direction: column; }
    .stats-row { flex-direction: column; }
    .category-list { flex-direction: column; }
}

/* ----- Swipeable (Mobile) ----- */
@media (max-width: 768px) {
    /* Type Selector */
    .type-selector {
        display: flex;
        overflow-x: auto;
        gap: 1rem;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
        padding-bottom: .5rem;
    }
    .type-selector::-webkit-scrollbar { display: none; }
    .type-option {
        flex: 0 0 75%;
    }

    /* Quick Stats */
    .stats-row {
        display: flex;
        overflow-x: auto;
        gap: 1rem;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
        padding-bottom: .5rem;
    }
    .stats-row::-webkit-scrollbar { display: none; }
    .stat-item {
        flex: 0 0 80%;
    }
}

</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
<script>
function enableSwipeScroll(containerSelector) {
    const container = document.querySelector(containerSelector);
    if (!container) return;

    let isDown = false;
    let startX;
    let scrollLeft;

    container.addEventListener('mousedown', e => {
        isDown = true;
        startX = e.pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
    });
    container.addEventListener('mouseleave', () => { isDown = false; });
    container.addEventListener('mouseup', () => { isDown = false; });
    container.addEventListener('mousemove', e => {
        if (!isDown) return;
        e.preventDefault();
        const x = e.pageX - container.offsetLeft;
        const walk = (x - startX) * 1; // ความไวในการลาก
        container.scrollLeft = scrollLeft - walk;
    });
}

// ใช้กับทั้งสองส่วน
document.addEventListener('DOMContentLoaded', () => {
    enableSwipeScroll('.type-selector');
    enableSwipeScroll('.stats-row');
});
</script>

<script>
// Initialize AOS
AOS.init({
    duration: 600,
    once: true
});

// Form elements
const form = document.getElementById('recordForm');
const typeInputs = document.querySelectorAll('input[name="type"]');
const categorySelect = document.getElementById('categorySelect');
const recurringCheck = document.getElementById('recurringCheck');
const recurringOptions = document.getElementById('recurringOptions');
const noteTextarea = document.querySelector('textarea[name="note"]');
const charCount = document.getElementById('charCount');
const amountInput = document.querySelector('.amount-input');

// Load categories based on type
function loadCategories(type) {
    if (!type) return;
    
    fetch(`{{ route('finance.records.categories') }}?type=${type}`)
        .then(response => response.json())
        .then(categories => {
            categorySelect.innerHTML = '<option value="">-- เลือกหมวดหมู่ --</option>';
            categories.forEach(cat => {
                const option = document.createElement('option');
                option.value = cat.slug;
                option.textContent = cat.name;
                categorySelect.appendChild(option);
            });
            
            updateCategoryPreview(categories);
        })
        .catch(error => {
            console.error('Error loading categories:', error);
            Swal.fire('เกิดข้อผิดพลาด', 'ไม่สามารถโหลดหมวดหมู่ได้', 'error');
        });
}

// Update category preview
function updateCategoryPreview(categories) {
    const categoryList = document.getElementById('categoryList');
    categoryList.innerHTML = '';
    
    if (categories.length === 0) {
        categoryList.innerHTML = '<p class="no-categories">ไม่มีหมวดหมู่</p>';
        return;
    }
    
    categories.forEach(cat => {
        const item = document.createElement('div');
        item.className = 'category-item';
        item.style.setProperty('--cat-color', cat.color);
        item.innerHTML = `
            <i class="fas ${cat.icon}"></i>
            <span>${cat.name}</span>
        `;
        categoryList.appendChild(item);
    });
}

// Initialize type selector
typeInputs.forEach(input => {
    input.addEventListener('change', function() {
        loadCategories(this.value);
    });
});

// Initialize with selected type
const selectedType = document.querySelector('input[name="type"]:checked');
if (selectedType) {
    loadCategories(selectedType.value);
}

// Recurring checkbox
recurringCheck?.addEventListener('change', function() {
    recurringOptions.style.display = this.checked ? 'block' : 'none';
    if (this.checked) {
        recurringOptions.classList.add('animate-slideDown');
    }
});

// Character counter
noteTextarea?.addEventListener('input', function() {
    const length = this.value.length;
    charCount.textContent = length;
    
    if (length > 400) {
        charCount.style.color = '#ef4444';
    } else if (length > 300) {
        charCount.style.color = '#f59e0b';
    } else {
        charCount.style.color = '#6b7280';
    }
});

// Amount input formatting
amountInput?.addEventListener('input', function() {
    // Remove non-numeric except decimal point
    this.value = this.value.replace(/[^0-9.]/g, '');
    
    // Ensure only one decimal point
    const parts = this.value.split('.');
    if (parts.length > 2) {
        this.value = parts[0] + '.' + parts.slice(1).join('');
    }
    
    // Limit to 2 decimal places
    if (parts[1] && parts[1].length > 2) {
        this.value = parts[0] + '.' + parts[1].substring(0, 2);
    }
});

// Format amount on blur
amountInput?.addEventListener('blur', function() {
    if (this.value && !isNaN(this.value)) {
        const value = parseFloat(this.value);
        this.value = value.toFixed(2);
    }
});

// Form validation
form.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const type = document.querySelector('input[name="type"]:checked');
    const category = categorySelect.value;
    const amount = amountInput.value;
    const date = document.querySelector('input[name="record_date"]').value;
    
    // Validate
    if (!type) {
        Swal.fire('กรุณาเลือกประเภท', 'เลือกว่าเป็นรายรับหรือรายจ่าย', 'warning');
        return;
    }
    
    if (!category) {
        Swal.fire('กรุณาเลือกหมวดหมู่', 'เลือกหมวดหมู่ของรายการ', 'warning');
        categorySelect.focus();
        return;
    }
    
    if (!amount || parseFloat(amount) <= 0) {
        Swal.fire('กรุณาระบุจำนวนเงิน', 'จำนวนเงินต้องมากกว่า 0', 'warning');
        amountInput.focus();
        return;
    }
    
    if (!date) {
        Swal.fire('กรุณาเลือกวันที่', 'เลือกวันที่ของรายการ', 'warning');
        return;
    }
    
    // Show loading
    Swal.fire({
        title: 'กำลังบันทึก...',
        text: 'กรุณารอสักครู่',
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Submit form
    this.submit();
});

// Save draft
function saveDraft() {
    const formData = {
        type: document.querySelector('input[name="type"]:checked')?.value,
        date: document.querySelector('input[name="record_date"]').value,
        category: categorySelect.value,
        amount: amountInput.value,
        note: noteTextarea.value,
        is_recurring: recurringCheck.checked,
        recurring_type: document.querySelector('select[name="recurring_type"]').value
    };
    
    localStorage.setItem('finance_record_draft', JSON.stringify(formData));
    
    Swal.fire({
        icon: 'success',
        title: 'บันทึกร่างเรียบร้อย',
        text: 'ข้อมูลถูกบันทึกไว้ชั่วคราว',
        timer: 1500,
        showConfirmButton: false
    });
}

// Load draft on page load
window.addEventListener('DOMContentLoaded', function() {
    const draft = localStorage.getItem('finance_record_draft');
    if (draft && !{{ old('type') ? 'true' : 'false' }}) {
        Swal.fire({
            title: 'พบข้อมูลที่บันทึกไว้',
            text: 'ต้องการโหลดข้อมูลที่บันทึกไว้หรือไม่?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'โหลด',
            cancelButtonText: 'ไม่'
        }).then((result) => {
            if (result.isConfirmed) {
                const data = JSON.parse(draft);
                
                // Load draft data
                if (data.type) {
                    document.querySelector(`input[name="type"][value="${data.type}"]`).checked = true;
                    loadCategories(data.type);
                }
                if (data.date) {
                    document.querySelector('input[name="record_date"]').value = data.date;
                }
                if (data.category) {
                    setTimeout(() => {
                        categorySelect.value = data.category;
                    }, 500);
                }
                if (data.amount) {
                    amountInput.value = data.amount;
                }
                if (data.note) {
                    noteTextarea.value = data.note;
                    charCount.textContent = data.note.length;
                }
                if (data.is_recurring) {
                    recurringCheck.checked = true;
                    recurringOptions.style.display = 'block';
                }
                if (data.recurring_type) {
                    document.querySelector('select[name="recurring_type"]').value = data.recurring_type;
                }
                
                Swal.fire({
                    icon: 'success',
                    title: 'โหลดข้อมูลเรียบร้อย',
                    timer: 1000,
                    showConfirmButton: false
                });
            }
        });
    }
});

// Clear draft after successful submission
@if(session('success'))
    localStorage.removeItem('finance_record_draft');
@endif

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + S: Save
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        document.getElementById('submitBtn').click();
    }
    
    // Ctrl/Cmd + D: Save draft
    if ((e.ctrlKey || e.metaKey) && e.key === 'd') {
        e.preventDefault();
        saveDraft();
    }
});

// Auto-save draft every 30 seconds
setInterval(function() {
    if (form.checkValidity()) {
        saveDraft();
    }
}, 30000);
</script>
@endpush