@extends('layouts.app')

@section('title', '문서양식 관리')

@section('content')
    <!-- 페이지 헤더 -->
    <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4 mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">문서양식 관리</h1>
            <p class="text-sm text-gray-500 mt-1 hidden sm:block">
                검사 성적서, 작업지시서 등 문서 양식을 관리합니다.
            </p>
        </div>
        <div class="flex flex-wrap items-center gap-2 sm:gap-3">
            <a href="{{ route('document-templates.create') }}"
               class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                </svg>
                새 양식
            </a>
        </div>
    </div>

    <!-- 필터 영역 -->
    <x-filter-collapsible id="filterForm">
        <form id="filterForm" class="flex flex-wrap gap-2 sm:gap-4">
            <input type="hidden" name="per_page" id="perPageInput" value="10">
            <input type="hidden" name="page" id="pageInput" value="1">

            <!-- 검색 -->
            <div class="flex-1 min-w-0 w-full sm:w-auto">
                <input type="text"
                       name="search"
                       placeholder="양식명, 제목, 분류로 검색..."
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 카테고리 필터 -->
            <div class="w-full sm:w-40">
                <select name="category" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체 분류</option>
                    @foreach($categories as $category)
                        <option value="{{ $category['code'] }}">{{ $category['name'] }}</option>
                    @endforeach
                </select>
            </div>

            <!-- 활성 상태 필터 -->
            <div class="w-full sm:w-32">
                <select name="is_active" id="isActiveFilter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체 상태</option>
                    <option value="1">활성</option>
                    <option value="0">비활성</option>
                    @if(auth()->user()?->is_super_admin)
                        <option value="TRASHED">🗑 휴지통</option>
                    @endif
                </select>
            </div>
            <input type="hidden" name="trashed" id="trashedInput" value="">

            <!-- 검색 버튼 -->
            <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition w-full sm:w-auto">
                검색
            </button>
        </form>
    </x-filter-collapsible>

    <!-- 테이블 영역 (HTMX로 로드) -->
    <div id="template-table"
         hx-get="/api/admin/document-templates"
         hx-trigger="load, filterSubmit from:body"
         hx-include="#filterForm"
         hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
         class="bg-white rounded-lg shadow-sm overflow-hidden">
        <!-- 로딩 스피너 -->
        <div class="flex justify-center items-center p-12">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
    </div>
    <!-- 미리보기 모달 (공통 partial) -->
    @include('document-templates.partials.preview-modal')
@endsection

@push('scripts')
<script>
    // 폼 제출 시 HTMX 이벤트 트리거
    (function() {
        let searchDebounceTimer = null;

        function initFilterForm() {
            const filterForm = document.getElementById('filterForm');
            if (filterForm && !filterForm._initialized) {
                filterForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    handleTrashedFilter();
                    htmx.trigger('#template-table', 'filterSubmit');
                });
                filterForm._initialized = true;
            }

            // 검색 input 실시간 필터링 (debounce 300ms)
            const searchInput = filterForm?.querySelector('input[name="search"]');
            if (searchInput && !searchInput._initialized) {
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchDebounceTimer);
                    searchDebounceTimer = setTimeout(function() {
                        handleTrashedFilter();
                        htmx.trigger('#template-table', 'filterSubmit');
                    }, 300);
                });
                searchInput._initialized = true;
            }

            // 휴지통 필터 처리
            const isActiveFilter = document.getElementById('isActiveFilter');
            if (isActiveFilter && !isActiveFilter._initialized) {
                isActiveFilter.addEventListener('change', function() {
                    handleTrashedFilter();
                });
                isActiveFilter._initialized = true;
            }
        }

        function handleTrashedFilter() {
            const isActiveFilter = document.getElementById('isActiveFilter');
            const trashedInput = document.getElementById('trashedInput');
            if (isActiveFilter.value === 'TRASHED') {
                trashedInput.value = '1';
                isActiveFilter.name = '';  // is_active 파라미터 제거
            } else {
                trashedInput.value = '';
                isActiveFilter.name = 'is_active';  // is_active 파라미터 복원
            }
        }

        initFilterForm();
        document.addEventListener('DOMContentLoaded', initFilterForm);
    })();

    // 삭제 확인
    window.confirmDelete = function(id, name) {
        showDeleteConfirm(name, () => {
            fetch(`/api/admin/document-templates/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message || '삭제되었습니다.', 'success');
                    htmx.trigger('#template-table', 'filterSubmit');
                } else {
                    showToast(data.message || '삭제에 실패했습니다.', 'error');
                }
            })
            .catch(error => {
                showToast('삭제 중 오류가 발생했습니다.', 'error');
                console.error('Delete error:', error);
            });
        });
    };

    // 양식 복제
    window.duplicateTemplate = function(id, name) {
        const newName = prompt('복제할 양식 이름을 입력하세요:', name + ' (복사)');
        if (newName === null) return; // 취소

        fetch(`/api/admin/document-templates/${id}/duplicate`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: newName })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(data.message || '복제되었습니다.', 'success');
                htmx.trigger('#template-table', 'filterSubmit');
            } else {
                showToast(data.message || '복제에 실패했습니다.', 'error');
            }
        })
        .catch(error => {
            showToast('복제 중 오류가 발생했습니다.', 'error');
            console.error('Duplicate error:', error);
        });
    };

    // 복원 (슈퍼관리자)
    window.restoreTemplate = function(id, name) {
        showDeleteConfirm(name + '" 복원', () => {
            fetch(`/api/admin/document-templates/${id}/restore`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message || '복원되었습니다.', 'success');
                    htmx.trigger('#template-table', 'filterSubmit');
                } else {
                    showToast(data.message || '복원에 실패했습니다.', 'error');
                }
            })
            .catch(error => {
                showToast('복원 중 오류가 발생했습니다.', 'error');
                console.error('Restore error:', error);
            });
        }, '복원', 'bg-green-600 hover:bg-green-700');
    };

    // 영구삭제 (슈퍼관리자)
    window.forceDeleteTemplate = function(id, name) {
        showDeleteConfirm(name + '" 영구삭제 (복구 불가)', () => {
            fetch(`/api/admin/document-templates/${id}/force`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message || '영구 삭제되었습니다.', 'success');
                    htmx.trigger('#template-table', 'filterSubmit');
                } else {
                    showToast(data.message || '영구 삭제에 실패했습니다.', 'error');
                }
            })
            .catch(error => {
                showToast('영구 삭제 중 오류가 발생했습니다.', 'error');
                console.error('Force delete error:', error);
            });
        });
    };

    // 미리보기 (공통 buildDocumentPreviewHtml 사용)
    window.previewTemplate = function(id) {
        const modal = document.getElementById('preview-modal');
        const content = document.getElementById('preview-content');
        content.innerHTML = '<div class="flex justify-center items-center p-12"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div></div>';
        modal.classList.remove('hidden');

        fetch(`/api/admin/document-templates/${id}`, {
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                content.innerHTML = buildDocumentPreviewHtml(data.data);
            } else {
                content.innerHTML = '<p class="text-center text-red-500 py-8">미리보기를 불러올 수 없습니다.</p>';
            }
        })
        .catch(error => {
            console.error('Preview error:', error);
            content.innerHTML = '<p class="text-center text-red-500 py-8">미리보기 로드 중 오류가 발생했습니다.</p>';
        });
    };

    // 활성 토글
    window.toggleActive = function(id, buttonEl) {
        const btn = buttonEl || document.querySelector(`tr[data-template-id="${id}"] button[onclick*="toggleActive"]`);
        if (!btn) return;

        const isCurrentlyActive = btn.classList.contains('bg-blue-500');
        const thumb = btn.querySelector('span');

        // 즉시 UI 토글
        btn.classList.toggle('bg-blue-500', !isCurrentlyActive);
        btn.classList.toggle('bg-gray-400', isCurrentlyActive);
        thumb.classList.toggle('translate-x-3.5', !isCurrentlyActive);
        thumb.classList.toggle('translate-x-0.5', isCurrentlyActive);

        fetch(`/api/admin/document-templates/${id}/toggle-active`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                // 실패 시 롤백
                btn.classList.toggle('bg-blue-500', isCurrentlyActive);
                btn.classList.toggle('bg-gray-400', !isCurrentlyActive);
                thumb.classList.toggle('translate-x-3.5', isCurrentlyActive);
                thumb.classList.toggle('translate-x-0.5', !isCurrentlyActive);
                showToast(data.message || '상태 변경에 실패했습니다.', 'error');
            }
        })
        .catch(error => {
            btn.classList.toggle('bg-blue-500', isCurrentlyActive);
            btn.classList.toggle('bg-gray-400', !isCurrentlyActive);
            thumb.classList.toggle('translate-x-3.5', isCurrentlyActive);
            thumb.classList.toggle('translate-x-0.5', !isCurrentlyActive);
            showToast('상태 변경 중 오류가 발생했습니다.', 'error');
            console.error('Toggle error:', error);
        });
    };
</script>
@endpush
