@extends('layouts.admin')

@section('page-title', 'Parte B - Accion Correctiva')

@section('content')
<div class="max-w-4xl mx-auto space-y-6">

    {{-- Header --}}
    <div class="flex items-center gap-3">
        <a href="{{ route('reportes.show', $reporte) }}" class="text-gray-400 hover:text-gray-600 transition-colors">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
        </a>
        <div>
            <h2 class="text-xl font-bold text-gray-800">Parte B - {{ $reporte->codigo }}</h2>
            <p class="text-sm text-gray-500">Completar accion correctiva</p>
        </div>
    </div>

    {{-- Resumen Parte A (solo lectura) --}}
    <div class="bg-gray-50 rounded-xl border border-gray-200 p-6">
        <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-4">Resumen de Parte A</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
                <p class="text-xs text-gray-500">Codigo</p>
                <p class="text-sm font-semibold" style="color: #ED6B37;">{{ $reporte->codigo }}</p>
            </div>
            <div>
                <p class="text-xs text-gray-500">Tipo</p>
                <p class="text-sm text-gray-800">{{ $reporte->tipo->nombre ?? 'N/A' }}</p>
            </div>
            <div>
                <p class="text-xs text-gray-500">Lugar</p>
                <p class="text-sm text-gray-800">{{ $reporte->lugar->nombre ?? 'N/A' }}</p>
            </div>
            <div>
                <p class="text-xs text-gray-500">Area</p>
                <p class="text-sm text-gray-800">{{ $reporte->area->nombre ?? 'N/A' }}</p>
            </div>
            <div>
                <p class="text-xs text-gray-500">Riesgo</p>
                @php
                    $riesgoColors = [
                        'bajo' => 'bg-green-100 text-green-800',
                        'medio' => 'bg-yellow-100 text-yellow-800',
                        'alto' => 'bg-orange-100 text-orange-800',
                        'critico' => 'bg-red-100 text-red-800',
                        'crítico' => 'bg-red-100 text-red-800',
                    ];
                    $riesgoNombre = strtolower($reporte->riesgo->nombre ?? '');
                    $riesgoClass = $riesgoColors[$riesgoNombre] ?? 'bg-gray-100 text-gray-800';
                @endphp
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $riesgoClass }}">
                    {{ $reporte->riesgo->nombre ?? 'N/A' }}
                </span>
            </div>
            <div>
                <p class="text-xs text-gray-500">Reportado por</p>
                <p class="text-sm text-gray-800">{{ $reporte->nombre_reportante }}</p>
            </div>
        </div>
        <div class="mt-4">
            <p class="text-xs text-gray-500">Descripcion</p>
            <p class="text-sm text-gray-800 mt-1 line-clamp-3">{{ $reporte->descripcion }}</p>
        </div>
    </div>

    {{-- Formulario Parte B --}}
    <form method="POST" action="{{ route('reportes.parte-b.update', $reporte) }}"
          class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"
          id="parteBForm">
        @csrf
        @method('PUT')

        <div class="px-6 py-4 bg-amber-50 border-b border-amber-100">
            <h3 class="text-lg font-semibold text-amber-800">Accion Correctiva</h3>
        </div>

        <div class="p-6 space-y-6">

            {{-- Accion correctiva --}}
            <div>
                <label for="accion_correctiva" class="block text-sm font-medium text-gray-700 mb-1">
                    Accion Correctiva <span class="text-red-500">*</span>
                </label>
                <textarea name="accion_correctiva" id="accion_correctiva" rows="5" required
                          class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm @error('accion_correctiva') border-red-500 @enderror"
                          placeholder="Describa la accion correctiva a tomar...">{{ old('accion_correctiva', $reporte->accion_correctiva) }}</textarea>
                @error('accion_correctiva')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            {{-- Supervisor --}}
            <div>
                <label for="supervisor_id" class="block text-sm font-medium text-gray-700 mb-1">
                    Supervisor Responsable <span class="text-red-500">*</span>
                </label>
                <select name="supervisor_id" id="supervisor_id" required
                        class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm @error('supervisor_id') border-red-500 @enderror">
                    <option value="">Seleccionar supervisor...</option>
                    @foreach($supervisores as $supervisor)
                        <option value="{{ $supervisor->id }}"
                                {{ old('supervisor_id', $reporte->supervisor_id ?? auth()->id()) == $supervisor->id ? 'selected' : '' }}>
                            {{ $supervisor->nombre_completo }}
                        </option>
                    @endforeach
                </select>
                @error('supervisor_id')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            {{-- Plazo y Estado --}}
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div>
                    <label for="plazo_horas_id" class="block text-sm font-medium text-gray-700 mb-1">
                        Plazo <span class="text-red-500">*</span>
                    </label>
                    <select name="plazo_horas_id" id="plazo_horas_id" required
                            class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm @error('plazo_horas_id') border-red-500 @enderror">
                        <option value="">Seleccionar plazo...</option>
                        @foreach($plazos as $plazo)
                            <option value="{{ $plazo->id }}"
                                    {{ old('plazo_horas_id', $reporte->plazo_horas_id) == $plazo->id ? 'selected' : '' }}>
                                {{ $plazo->nombre }} ({{ $plazo->horas }} horas)
                            </option>
                        @endforeach
                    </select>
                    @error('plazo_horas_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="estado_id" class="block text-sm font-medium text-gray-700 mb-1">
                        Estado <span class="text-red-500">*</span>
                    </label>
                    <select name="estado_id" id="estado_id" required
                            class="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm @error('estado_id') border-red-500 @enderror">
                        <option value="">Seleccionar estado...</option>
                        @foreach($estados as $estado)
                            <option value="{{ $estado->id }}"
                                    {{ old('estado_id', $reporte->estado_id) == $estado->id ? 'selected' : '' }}>
                                {{ $estado->nombre }}
                            </option>
                        @endforeach
                    </select>
                    @error('estado_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            {{-- Firma del supervisor --}}
            <div x-data="{ useStored: {{ $reporte->firma_supervisor_path ? 'true' : 'false' }}, signaturePad: null }"
                 x-init="
                    $nextTick(() => {
                        if ($refs.signatureCanvas) {
                            signaturePad = new SignaturePad($refs.signatureCanvas, {
                                backgroundColor: 'rgb(240, 240, 240)',
                                penColor: 'rgb(0, 51, 153)',
                            });
                            signaturePad.addEventListener('endStroke', () => {
                                document.getElementById('firma_supervisor_live').value = signaturePad.toDataURL();
                            });
                        }
                    });
                 ">
                <label class="block text-sm font-medium text-gray-700 mb-2">Firma del Supervisor</label>

                {{-- Opciones de firma --}}
                @if($reporte->firma_supervisor_path || (auth()->user()->firma_png_path ?? false))
                    <div class="flex items-center gap-4 mb-3">
                        <label class="inline-flex items-center">
                            <input type="radio" name="tipo_firma" value="stored" x-model="useStored"
                                   @click="useStored = true"
                                   style="accent-color: #ED6B37;" class="focus:ring-blue-500"
                                   {{ $reporte->firma_supervisor_path ? 'checked' : '' }}>
                            <span class="ml-2 text-sm text-gray-700">Usar firma guardada</span>
                        </label>
                        <label class="inline-flex items-center">
                            <input type="radio" name="tipo_firma" value="live" x-model="useStored"
                                   @click="useStored = false"
                                   style="accent-color: #ED6B37;" class="focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">Firmar ahora</span>
                        </label>
                    </div>
                @endif

                {{-- Firma almacenada --}}
                <div x-show="useStored" x-cloak>
                    @if($reporte->firma_supervisor_path)
                        <div class="bg-gray-50 border border-gray-200 rounded-lg p-4 inline-block">
                            <img src="{{ Storage::url($reporte->firma_supervisor_path) }}"
                                 alt="Firma del supervisor" class="max-h-24">
                        </div>
                    @elseif(auth()->user()->firma_png_path ?? false)
                        <div class="bg-gray-50 border border-gray-200 rounded-lg p-4 inline-block">
                            <img src="{{ Storage::url(auth()->user()->firma_png_path) }}"
                                 alt="Firma del supervisor" class="max-h-24">
                        </div>
                    @else
                        <p class="text-sm text-gray-500">No hay firma almacenada.</p>
                    @endif
                </div>

                {{-- Firma en vivo --}}
                <div x-show="!useStored" class="space-y-2">
                    <div class="border-2 border-dashed border-gray-300 rounded-lg" style="background-color: #f0f0f0;">
                        <canvas x-ref="signatureCanvas" width="500" height="200"
                                class="w-full rounded-lg cursor-crosshair" style="touch-action: none;"></canvas>
                    </div>
                    <button type="button"
                            @click="signaturePad?.clear(); document.getElementById('firma_supervisor_live').value = '';"
                            class="text-sm text-red-600 hover:text-red-700 font-medium">
                        Limpiar firma
                    </button>
                    <input type="hidden" name="firma_supervisor_live" id="firma_supervisor_live" value="">
                </div>
            </div>
        </div>

        {{-- Boton de envio --}}
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-end gap-3">
            <a href="{{ route('reportes.show', $reporte) }}"
               class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                Cancelar
            </a>
            <button type="submit"
                    class="inline-flex items-center px-6 py-2 text-white text-sm font-semibold rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2"
                    style="background-color: #ED6B37;"
                    onmouseover="this.style.backgroundColor='#D4572B'"
                    onmouseout="this.style.backgroundColor='#ED6B37'">
                <svg class="w-4 h-4 mr-2" 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>
                Guardar Parte B
            </button>
        </div>
    </form>
</div>

{{-- Signature Pad JS --}}
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
@endsection
