@model foundation_system.Models.ViewModels.ExpedienteViewModel
@{
    ViewData["Title"] = "Editar Expediente";
}

@section Styles {
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <style>
        .gender-group {
            display: flex;
            gap: 20px;
            padding: 8px 12px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }
        .gender-option {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }
        .gender-option input {
            cursor: pointer;
        }
        .photo-upload-container {
            position: relative;
            width: 150px;
            height: 150px;
            margin: 0 auto 20px;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid #dee2e6;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .photo-upload-container:hover {
            border-color: #0d6efd;
            opacity: 0.8;
        }
        .photo-upload-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .photo-upload-container .upload-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.5);
            color: white;
            text-align: center;
            padding: 5px 0;
            font-size: 12px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .photo-upload-container:hover .upload-overlay {
            opacity: 1;
        }
        .photo-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            font-size: 60px;
            color: #adb5bd;
        }
    </style>
}

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1">Editar Expediente</h2>
        <p class="text-muted small mb-0">Actualice la información del niño(a): <strong>@Model.Nombres @Model.Apellidos</strong></p>
    </div>
    <a asp-action="Index" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Volver al Listado
    </a>
</div>

<form asp-action="Edit" method="post" id="expedienteForm" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <input type="hidden" asp-for="Id" />
    <div asp-validation-summary="ModelOnly" class="text-danger mb-3"></div>

    <div class="row">
        <!-- Datos Personales -->
        <div class="col-md-8">
            <div class="card-custom mb-4">
                <h5 class="card-title mb-4"><i class="bi bi-person-vcard me-2 text-primary"></i>Datos Personales</h5>
                <div class="row g-3">
                    <div class="col-md-12">
                        <div class="text-center mb-4">
                            <input type="hidden" asp-for="FotoUrl" id="FotoUrl" />
                            <input asp-for="FotoFile" type="file" id="photoInput" style="display: none;" accept="image/*" onchange="previewPhoto(this)" />
                            <div class="photo-upload-container" onclick="document.getElementById('photoInput').click()">
                                <div id="photoPreview">
                                    @if (!string.IsNullOrEmpty(Model.FotoUrl))
                                    {
                                        <img src="@Model.FotoUrl" alt="Foto de perfil" id="previewImg" />
                                    }
                                    else
                                    {
                                        <img src="/Assets/default_avatar.png" alt="Foto de perfil" id="previewImg" />
                                    }
                                </div>
                                <div class="upload-overlay">
                                    <i class="bi bi-camera"></i> Cambiar Foto
                                </div>
                            </div>
                            <p class="text-muted small">Haga clic para cambiar la foto</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label asp-for="Nombres" class="form-label fw-semibold"></label>
                        <input asp-for="Nombres" class="form-control" placeholder="Ej. Juan Alberto" required />
                        <span asp-validation-for="Nombres" class="text-danger small"></span>
                    </div>
                    <div class="col-md-6">
                        <label asp-for="Apellidos" class="form-label fw-semibold"></label>
                        <input asp-for="Apellidos" class="form-control" placeholder="Ej. Pérez García" required />
                        <span asp-validation-for="Apellidos" class="text-danger small"></span>
                    </div>
                    <div class="col-md-6">
                        <label asp-for="FechaNacimiento" class="form-label fw-semibold"></label>
                        <input asp-for="FechaNacimiento" class="form-control" type="date" required />
                        <span asp-validation-for="FechaNacimiento" class="text-danger small"></span>
                    </div>
                    <div class="col-md-6">
                        <label asp-for="Genero" class="form-label fw-semibold"></label>
                        <div class="gender-group">
                            <label class="gender-option">
                                <input type="radio" asp-for="Genero" value="M" required />
                                <span>Masculino</span>
                            </label>
                            <label class="gender-option">
                                <input type="radio" asp-for="Genero" value="F" required />
                                <span>Femenino</span>
                            </label>
                        </div>
                        <span asp-validation-for="Genero" class="text-danger small"></span>
                    </div>
                    <div class="col-md-12">
                        <label asp-for="Direccion" class="form-label fw-semibold"></label>
                        <textarea asp-for="Direccion" class="form-control" rows="2" placeholder="Dirección completa de residencia" required></textarea>
                        <span asp-validation-for="Direccion" class="text-danger small"></span>
                    </div>
                </div>
            </div>

            <!-- Padres / Encargados -->
            <div class="card-custom mb-4">
                <h5 class="card-title mb-4"><i class="bi bi-people me-2 text-info"></i>Padres / Encargados</h5>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">Padre <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="hidden" asp-for="PadreId" id="PadreId" required />
                            <input type="text" id="PadreNombreDisplay" class="form-control" value="@Model.PadreNombre" placeholder="Seleccionar..." readonly />
                            <button type="button" class="btn btn-outline-primary" onclick="openParentModal('PADRE')">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                        <span asp-validation-for="PadreId" class="text-danger small"></span>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">Madre <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="hidden" asp-for="MadreId" id="MadreId" required />
                            <input type="text" id="MadreNombreDisplay" class="form-control" value="@Model.MadreNombre" placeholder="Seleccionar..." readonly />
                            <button type="button" class="btn btn-outline-primary" onclick="openParentModal('MADRE')">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                        <span asp-validation-for="MadreId" class="text-danger small"></span>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">Encargado <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="hidden" asp-for="EncargadoId" id="EncargadoId" required />
                            <input type="text" id="EncargadoNombreDisplay" class="form-control" value="@Model.EncargadoNombre" placeholder="Seleccionar..." readonly />
                            <button type="button" class="btn btn-outline-primary" onclick="openParentModal('ENCARGADO')">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                        <span asp-validation-for="EncargadoId" class="text-danger small"></span>
                    </div>
                </div>
            </div>

            <div class="card-custom">
                <h5 class="card-title mb-4"><i class="bi bi-telephone-outbound me-2 text-danger"></i>Contacto de Emergencia (Opcional)</h5>
                <div class="row g-3">
                    <div class="col-md-7">
                        <label asp-for="ContactoEmergenciaNombre" class="form-label fw-semibold"></label>
                        <input asp-for="ContactoEmergenciaNombre" class="form-control" placeholder="Nombre del responsable" />
                        <span asp-validation-for="ContactoEmergenciaNombre" class="text-danger small"></span>
                    </div>
                    <div class="col-md-5">
                        <label asp-for="ContactoEmergenciaTelefono" class="form-label fw-semibold"></label>
                        <input asp-for="ContactoEmergenciaTelefono" class="form-control" placeholder="Teléfono de contacto" />
                        <span asp-validation-for="ContactoEmergenciaTelefono" class="text-danger small"></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Datos de Inscripción -->
        <div class="col-md-4">
            <div class="card-custom mb-4">
                <h5 class="card-title mb-4"><i class="bi bi-clipboard-check me-2 text-success"></i>Inscripción</h5>
                <div class="row g-3">
                    <div class="col-md-12">
                        <label asp-for="CodigoInscripcion" class="form-label fw-semibold"></label>
                        <input asp-for="CodigoInscripcion" class="form-control fw-bold text-muted" readonly />
                        <span class="text-muted extra-small">El código de expediente no es editable.</span>
                    </div>
                    <div class="col-md-12">
                        <label asp-for="FechaInscripcion" class="form-label fw-semibold"></label>
                        <input asp-for="FechaInscripcion" class="form-control" type="date" required />
                        <span asp-validation-for="FechaInscripcion" class="text-danger small"></span>
                    </div>
                    <div class="col-md-12">
                        <label asp-for="NivelGrado" class="form-label fw-semibold"></label>
                        <select asp-for="NivelGrado" class="form-select" required>
                            <option value="">Seleccione grado...</option>
                            <option value="NoEstudia">No estudia</option>
                            <option value="Parvularia">Parvularia</option>
                            <option value="Primer Ciclo">Primer Ciclo</option>
                            <option value="Segundo Ciclo">Segundo Ciclo</option>
                            <option value="Tercer Ciclo">Tercer Ciclo</option>
                        </select>
                        <span asp-validation-for="NivelGrado" class="text-danger small"></span>
                    </div>
                    <div class="col-md-12">
                        <label asp-for="Estado" class="form-label fw-semibold"></label>
                        <select asp-for="Estado" class="form-select" required>
                            <option value="ACTIVO">Activo</option>
                            <option value="INACTIVO">Inactivo</option>
                            <option value="GRADUADO">Graduado</option>
                        </select>
                        <span asp-validation-for="Estado" class="text-danger small"></span>
                    </div>
                </div>
            </div>

            <div class="card-custom">
                <h5 class="card-title mb-4"><i class="bi bi-heart-pulse me-2 text-warning"></i>Salud (Opcional)</h5>
                <div class="col-md-12">
                    <label asp-for="Alergias" class="form-label fw-semibold"></label>
                    <textarea asp-for="Alergias" class="form-control" rows="3" placeholder="Detalle alergias o condiciones médicas..."></textarea>
                    <span asp-validation-for="Alergias" class="text-danger small"></span>
                </div>
            </div>

            <div class="mt-4 d-grid">
                <button type="submit" class="btn btn-primary-custom btn-lg">
                    <i class="bi bi-check2-circle me-2"></i>Actualizar Expediente
                </button>
            </div>
        </div>
    </div>
</form>

<!-- Modal para Seleccionar/Crear Padre/Madre -->
<div class="modal fade" id="parentModal" tabindex="-1" aria-labelledby="parentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="parentModalLabel">Seleccionar Persona</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-tabs mb-3" id="parentTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="search-tab" data-bs-toggle="tab" data-bs-target="#search-pane" type="button" role="tab">Buscar Existente</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="create-tab" data-bs-toggle="tab" data-bs-target="#create-pane" type="button" role="tab">Crear Nuevo</button>
                    </li>
                </ul>
                <div class="tab-content" id="parentTabsContent">
                    <!-- Tab Buscar -->
                    <div class="tab-pane fade show active" id="search-pane" role="tabpanel">
                        <div class="mb-3">
                            <div class="input-group">
                                <input type="text" id="searchPersonaInput" class="form-control" placeholder="Buscar por nombre o DUI..." />
                                <button class="btn btn-primary" type="button" onclick="searchPersonas()">
                                    <i class="bi bi-search"></i>
                                </button>
                            </div>
                        </div>
                        <div id="searchResults" class="list-group">
                            <!-- Resultados de búsqueda aquí -->
                        </div>
                    </div>
                    <!-- Tab Crear -->
                    <div class="tab-pane fade" id="create-pane" role="tabpanel">
                        <form id="createPersonaForm">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Nombres</label>
                                    <input type="text" name="Nombres" class="form-control" required />
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Apellidos</label>
                                    <input type="text" name="Apellidos" class="form-control" required />
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">DUI</label>
                                    <input type="text" name="Dui" class="form-control" placeholder="00000000-0" />
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Teléfono</label>
                                    <input type="text" name="Telefono" class="form-control" placeholder="0000-0000" />
                                </div>
                                <div class="col-md-12 text-end">
                                    <button type="button" class="btn btn-success" onclick="createPersona()">
                                        <i class="bi bi-plus-circle me-2"></i>Crear y Seleccionar
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    
    <script>
        let currentParentType = '';

        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "right",
                stopOnFocus: true,
                style: {
                    background: type === 'success' ? "#28a745" : "#dc3545",
                }
            }).showToast();
        }

        function openParentModal(type) {
            currentParentType = type;
            let label = 'Seleccionar ';
            if (type === 'PADRE') label += 'Padre';
            else if (type === 'MADRE') label += 'Madre';
            else label += 'Encargado';
            
            document.getElementById('parentModalLabel').innerText = label;
            const modal = new bootstrap.Modal(document.getElementById('parentModal'));
            modal.show();
        }

        async function searchPersonas() {
            const term = document.getElementById('searchPersonaInput').value;
            if (term.length < 3) {
                showToast('Por favor ingrese al menos 3 caracteres', 'error');
                return;
            }

            try {
                const response = await fetch(`/Expediente/SearchPersonas?term=${encodeURIComponent(term)}&type=ENCARGADO`);
                const data = await response.json();
                
                const resultsDiv = document.getElementById('searchResults');
                resultsDiv.innerHTML = '';

                if (data.length === 0) {
                    resultsDiv.innerHTML = '<div class="list-group-item text-muted">No se encontraron resultados</div>';
                    return;
                }

                data.forEach(p => {
                    const btn = document.createElement('button');
                    btn.type = 'button';
                    btn.className = 'list-group-item list-group-item-action';
                    btn.innerText = p.text;
                    btn.onclick = () => selectPersona(p.id, p.text);
                    resultsDiv.appendChild(btn);
                });
            } catch (error) {
                showToast('Error al buscar personas', 'error');
            }
        }

        function selectPersona(id, name) {
            if (currentParentType === 'PADRE') {
                document.getElementById('PadreId').value = id;
                document.getElementById('PadreNombreDisplay').value = name;
            } else if (currentParentType === 'MADRE') {
                document.getElementById('MadreId').value = id;
                document.getElementById('MadreNombreDisplay').value = name;
            } else {
                document.getElementById('EncargadoId').value = id;
                document.getElementById('EncargadoNombreDisplay').value = name;
            }
            
            const modalElement = document.getElementById('parentModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            modal.hide();
            showToast('Persona seleccionada correctamente');
        }

        async function createPersona() {
            const form = document.getElementById('createPersonaForm');
            const formData = new FormData(form);
            const persona = {};
            formData.forEach((value, key) => persona[key] = value);

            if (!persona.Nombres || !persona.Apellidos) {
                showToast('Nombres y Apellidos son requeridos', 'error');
                return;
            }

            try {
                const response = await fetch('/Expediente/CreatePersona', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
                    },
                    body: JSON.stringify(persona)
                });

                const result = await response.json();
                if (result.success) {
                    selectPersona(result.id, result.text);
                    form.reset();
                    showToast('Persona creada y seleccionada');
                } else {
                    showToast(result.message || 'Error al crear la persona', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al crear persona', 'error');
            }
        }

        function previewPhoto(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('previewImg').src = e.target.result;
                };
                reader.readAsDataURL(input.files[0]);
                showToast('Foto seleccionada');
            }
        }

        // Form validation with Toastify
        document.getElementById('expedienteForm').addEventListener('submit', function(e) {
            const form = this;
            if (!form.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
                showToast('Por favor complete todos los campos requeridos', 'error');
            }
            form.classList.add('was-validated');
        });
    </script>
}
