@extends('layouts.app')

@section('title', '새 플로우 생성')

@section('content')
    <!-- 페이지 헤더 -->
    <div class="flex justify-between items-center mb-6">
        <div class="flex items-center gap-4">
            <a href="{{ route('dev-tools.flow-tester.index') }}"
               class="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
            </a>
            <h1 class="text-2xl font-bold text-gray-800">새 플로우 생성</h1>
        </div>
        <div class="flex gap-2">
            <button onclick="GuideModal.open()"
                    class="bg-gray-100 hover:bg-gray-200 text-gray-700 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="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                JSON 가이드
            </button>
            <button onclick="ExamplesModal.open()"
                    class="bg-purple-100 hover:bg-purple-200 text-purple-700 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="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 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                </svg>
                예제 플로우
            </button>
        </div>
    </div>

    <!-- 안내 배너 -->
    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
        <div class="flex items-start gap-3">
            <svg class="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div>
                <p class="text-sm text-blue-800 font-medium">JSON만 붙여넣으세요!</p>
                <p class="text-sm text-blue-700 mt-1">
                    AI가 생성한 JSON을 붙여넣고 <strong>"검증 및 추출"</strong> 버튼을 누르면
                    이름, 카테고리, 설명이 자동으로 채워집니다.
                </p>
            </div>
        </div>
    </div>

    <form action="{{ route('dev-tools.flow-tester.store') }}" method="POST" id="flow-form">
        @csrf

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- JSON 에디터 (왼쪽 2/3) -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-lg shadow-sm p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-lg font-semibold text-gray-800">플로우 JSON</h2>
                        <div class="flex gap-2">
                            <button type="button"
                                    onclick="formatJson()"
                                    class="px-3 py-1.5 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">
                                포맷
                            </button>
                            <button type="button"
                                    onclick="validateAndExtract()"
                                    class="px-4 py-1.5 text-sm bg-blue-600 hover:bg-blue-700 text-white 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                검증 및 추출
                            </button>
                        </div>
                    </div>

                    <textarea name="flow_definition"
                              id="flow-definition"
                              rows="28"
                              required
                              class="w-full px-4 py-3 font-mono text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 @error('flow_definition') border-red-500 @enderror"
                              placeholder="AI가 생성한 JSON을 여기에 붙여넣으세요...">{{ old('flow_definition') }}</textarea>
                    @error('flow_definition')
                        <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- 메타 정보 패널 (오른쪽 1/3) -->
            <div class="lg:col-span-1 space-y-4">
                <!-- 검증 상태 -->
                <div id="validation-status" class="bg-white rounded-lg shadow-sm p-4">
                    <div class="flex items-center gap-3 text-gray-500">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span class="text-sm">JSON을 붙여넣고 검증하세요</span>
                    </div>
                </div>

                <!-- 추출된 정보 -->
                <div id="extracted-info" class="bg-white rounded-lg shadow-sm p-6 hidden">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">추출된 정보</h2>

                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">이름 *</label>
                            <input type="text"
                                   name="name"
                                   id="extracted-name"
                                   value="{{ old('name') }}"
                                   required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 @error('name') border-red-500 @enderror"
                                   placeholder="플로우 이름">
                            @error('name')
                                <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                            @enderror
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">카테고리</label>
                            <input type="text"
                                   name="category"
                                   id="extracted-category"
                                   value="{{ old('category') }}"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                   placeholder="자동 추출됨">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                            <textarea name="description"
                                      id="extracted-description"
                                      rows="3"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                      placeholder="자동 추출됨">{{ old('description') }}</textarea>
                        </div>

                        <!-- 추가 정보 표시 -->
                        <div id="extra-info" class="pt-3 border-t border-gray-200 text-sm text-gray-600 space-y-1">
                            <div class="flex justify-between">
                                <span>버전:</span>
                                <span id="info-version" class="font-medium">-</span>
                            </div>
                            <div class="flex justify-between">
                                <span>스텝 수:</span>
                                <span id="info-steps" class="font-medium">-</span>
                            </div>
                            <div class="flex justify-between">
                                <span>태그:</span>
                                <span id="info-tags" class="font-medium">-</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 검증 실패 시 에러 표시 -->
                <div id="validation-errors" class="bg-red-50 border border-red-200 rounded-lg p-4 hidden">
                    <div class="flex items-center gap-2 text-red-700 mb-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span class="font-medium">검증 실패</span>
                    </div>
                    <ul id="error-list" class="text-sm text-red-600 list-disc list-inside space-y-1"></ul>
                </div>

                <!-- 저장 버튼 -->
                <div class="flex gap-3">
                    <a href="{{ route('dev-tools.flow-tester.index') }}"
                       class="flex-1 px-4 py-2 border border-gray-300 text-gray-700 text-center rounded-lg hover:bg-gray-50 transition">
                        취소
                    </a>
                    <button type="submit"
                            id="submit-btn"
                            disabled
                            class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white rounded-lg transition">
                        저장
                    </button>
                </div>
            </div>
        </div>
    </form>

    {{-- 모달 포함 --}}
    @include('dev-tools.flow-tester.partials.guide-modal')
    @include('dev-tools.flow-tester.partials.example-flows')
@endsection

@push('scripts')
<script>
    let isValidated = false;

    function formatJson() {
        const textarea = document.getElementById('flow-definition');
        try {
            const json = JSON.parse(textarea.value);
            textarea.value = JSON.stringify(json, null, 2);
        } catch (e) {
            showError(['JSON 파싱 오류: ' + e.message]);
        }
    }

    function validateAndExtract() {
        const textarea = document.getElementById('flow-definition');
        const statusDiv = document.getElementById('validation-status');
        const extractedDiv = document.getElementById('extracted-info');
        const errorsDiv = document.getElementById('validation-errors');
        const submitBtn = document.getElementById('submit-btn');

        // 로딩 상태
        statusDiv.innerHTML = `
            <div class="flex items-center gap-3 text-blue-600">
                <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span class="text-sm">검증 중...</span>
            </div>
        `;

        fetch('{{ route("dev-tools.flow-tester.validate-json") }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ flow_definition: textarea.value }),
        })
        .then(response => response.json())
        .then(data => {
            if (data.valid) {
                // 성공 상태
                statusDiv.innerHTML = `
                    <div class="flex items-center gap-3 text-green-600">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <span class="text-sm font-medium">JSON 유효 - ${data.stepCount}개 스텝</span>
                    </div>
                `;

                // 추출된 정보 표시
                extractedDiv.classList.remove('hidden');
                errorsDiv.classList.add('hidden');

                const extracted = data.extracted || {};

                // 필드에 값 채우기 (기존 값이 없을 때만)
                const nameInput = document.getElementById('extracted-name');
                const categoryInput = document.getElementById('extracted-category');
                const descInput = document.getElementById('extracted-description');

                if (!nameInput.value && extracted.name) {
                    nameInput.value = extracted.name;
                }
                if (!categoryInput.value && extracted.category) {
                    categoryInput.value = extracted.category;
                }
                if (!descInput.value && extracted.description) {
                    descInput.value = extracted.description;
                }

                // 추가 정보 표시
                document.getElementById('info-version').textContent = extracted.version || '1.0';
                document.getElementById('info-steps').textContent = data.stepCount + '개';
                document.getElementById('info-tags').textContent = extracted.tags?.length
                    ? extracted.tags.join(', ')
                    : '-';

                // 저장 버튼 활성화
                isValidated = true;
                submitBtn.disabled = false;

            } else {
                showError(data.errors || ['알 수 없는 오류']);
            }
        })
        .catch(error => {
            showError(['요청 오류: ' + error.message]);
        });
    }

    function showError(errors) {
        const statusDiv = document.getElementById('validation-status');
        const extractedDiv = document.getElementById('extracted-info');
        const errorsDiv = document.getElementById('validation-errors');
        const errorList = document.getElementById('error-list');
        const submitBtn = document.getElementById('submit-btn');

        statusDiv.innerHTML = `
            <div class="flex items-center gap-3 text-red-600">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span class="text-sm font-medium">검증 실패</span>
            </div>
        `;

        extractedDiv.classList.add('hidden');
        errorsDiv.classList.remove('hidden');
        errorList.innerHTML = errors.map(e => `<li>${e}</li>`).join('');

        isValidated = false;
        submitBtn.disabled = true;
    }

    // 폼 제출 전 검증
    document.getElementById('flow-form').addEventListener('submit', function(e) {
        const nameInput = document.getElementById('extracted-name');

        if (!isValidated) {
            e.preventDefault();
            showToast('먼저 JSON을 검증해주세요.', 'warning');
            return;
        }

        if (!nameInput.value.trim()) {
            e.preventDefault();
            showToast('이름을 입력해주세요.', 'warning');
            nameInput.focus();
            return;
        }
    });

    // JSON 변경 시 검증 상태 초기화
    document.getElementById('flow-definition').addEventListener('input', function() {
        if (isValidated) {
            isValidated = false;
            document.getElementById('submit-btn').disabled = true;
            document.getElementById('validation-status').innerHTML = `
                <div class="flex items-center gap-3 text-yellow-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                    </svg>
                    <span class="text-sm">JSON이 변경됨 - 다시 검증하세요</span>
                </div>
            `;
        }
    });
</script>
@endpush
