@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">
            <a href="{{ route('dev-tools.flow-tester.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>
            <button onclick="runFlow({{ $flow->id }})"
                    class="bg-green-600 hover:bg-green-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="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                실행
            </button>
        </div>
    </div>

    @if(session('success'))
        <div class="mb-6 px-4 py-3 bg-green-100 border border-green-400 text-green-700 rounded-lg">
            {{ session('success') }}
        </div>
    @endif

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

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 기본 정보 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-sm p-6">
                    <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"
                                   value="{{ old('name', $flow->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"
                                   value="{{ old('category', $flow->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="item-master, auth, bom 등">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                            <textarea name="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', $flow->description) }}</textarea>
                        </div>

                        <div class="flex items-center gap-2">
                            <input type="checkbox"
                                   name="is_active"
                                   value="1"
                                   id="is_active"
                                   {{ old('is_active', $flow->is_active) ? 'checked' : '' }}
                                   class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                            <label for="is_active" class="text-sm text-gray-700">활성화</label>
                        </div>
                    </div>
                </div>

                <!-- 검증 결과 -->
                <div id="validation-result" class="mt-4 bg-white rounded-lg shadow-sm p-4 hidden">
                    <div id="validation-success" class="hidden text-green-600 flex items-center gap-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="M5 13l4 4L19 7" />
                        </svg>
                        <span>JSON 유효 - <span id="step-count">0</span>개 스텝</span>
                    </div>
                    <div id="validation-error" class="hidden text-red-600">
                        <div class="flex items-center gap-2 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="M6 18L18 6M6 6l12 12" />
                            </svg>
                            <span>검증 실패</span>
                        </div>
                        <ul id="error-list" class="text-sm list-disc list-inside"></ul>
                    </div>
                </div>

                <!-- 메타 정보 -->
                <div class="mt-4 bg-white rounded-lg shadow-sm p-4">
                    <h3 class="text-sm font-medium text-gray-500 mb-2">정보</h3>
                    <dl class="text-sm space-y-1">
                        <div class="flex justify-between">
                            <dt class="text-gray-500">생성일</dt>
                            <dd class="text-gray-900">{{ $flow->created_at->format('Y-m-d H:i') }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">수정일</dt>
                            <dd class="text-gray-900">{{ $flow->updated_at->format('Y-m-d H:i') }}</dd>
                        </div>
                        <div class="flex justify-between">
                            <dt class="text-gray-500">스텝 수</dt>
                            <dd class="text-gray-900">{{ $flow->step_count }}개</dd>
                        </div>
                    </dl>
                </div>
            </div>

            <!-- JSON 에디터 -->
            <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="validateJson()"
                                    class="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">
                                검증
                            </button>
                            <button type="button"
                                    onclick="formatJson()"
                                    class="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">
                                포맷
                            </button>
                        </div>
                    </div>

                    <textarea name="flow_definition"
                              id="flow-definition"
                              rows="30"
                              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">{{ old('flow_definition', json_encode($flow->flow_definition, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) }}</textarea>
                    @error('flow_definition')
                        <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                    @enderror
                </div>

                <!-- 제출 버튼 -->
                <div class="mt-6 flex justify-end gap-4">
                    <a href="{{ route('dev-tools.flow-tester.index') }}"
                       class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                        취소
                    </a>
                    <button type="submit"
                            class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
                        저장
                    </button>
                </div>
            </div>
        </div>
    </form>
@endsection

@push('scripts')
<script>
    function formatJson() {
        const textarea = document.getElementById('flow-definition');
        try {
            const json = JSON.parse(textarea.value);
            textarea.value = JSON.stringify(json, null, 2);
        } catch (e) {
            showToast('JSON 파싱 오류: ' + e.message, 'error');
        }
    }

    function validateJson() {
        const textarea = document.getElementById('flow-definition');
        const resultDiv = document.getElementById('validation-result');
        const successDiv = document.getElementById('validation-success');
        const errorDiv = document.getElementById('validation-error');
        const errorList = document.getElementById('error-list');
        const stepCount = document.getElementById('step-count');

        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 => {
            resultDiv.classList.remove('hidden');

            if (data.valid) {
                successDiv.classList.remove('hidden');
                errorDiv.classList.add('hidden');
                stepCount.textContent = data.stepCount;
            } else {
                successDiv.classList.add('hidden');
                errorDiv.classList.remove('hidden');
                errorList.innerHTML = data.errors.map(e => `<li>${e}</li>`).join('');
            }
        })
        .catch(error => {
            showToast('검증 오류: ' + error.message, 'error');
        });
    }

    function runFlow(id) {
        showConfirm('이 플로우를 실행하시겠습니까?', () => {
            fetch(`/dev-tools/flow-tester/${id}/run`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    // 성공 시 리스트 페이지로 이동
                    setTimeout(() => {
                        window.location.href = '{{ route("dev-tools.flow-tester.index") }}';
                    }, 1000);
                } else {
                    showToast('실행 실패: ' + (data.message || '알 수 없는 오류'), 'error');
                    // 실패 시 실행 상세 페이지로 이동
                    if (data.run_id) {
                        setTimeout(() => {
                            window.location.href = `/dev-tools/flow-tester/runs/${data.run_id}`;
                        }, 1500);
                    }
                }
            })
            .catch(error => {
                showToast('오류 발생: ' + error.message, 'error');
            });
        }, { title: '플로우 실행', icon: 'question' });
    }
</script>
@endpush
