import { createIncident, createIncidentFormData } from '../api.js';

export async function renderDeclareIncident(root, { client, onSuccess }) {
  root.innerHTML = `
    <section class="screen-stack">
      <div class="public-section-card public-section-card-hero">
        <div class="public-section-head stacked">
          <div>
            <span class="public-hero-pill">Déclaration client</span>
            <h2>Nouvel incident e-Intervention</h2>
            <p>Ajoutez votre description, joignez plusieurs photos et laissez un commentaire par photo.</p>
          </div>
          <div class="public-inline-note">
            <i class="fas fa-location-dot"></i>
            Votre position actuelle sera transmise si disponible. Votre domicile enregistré complète automatiquement le dossier FTTH.
          </div>
        </div>
      </div>

      <div class="alert alert-danger" id="incidentError" hidden></div>
      <div class="alert alert-success" id="incidentSuccess" hidden></div>

      <form id="incidentForm" class="public-form-panel">
        <div>
          <label class="form-label">Objet</label>
          <input class="form-control" name="subject" value="Incident ${escapeHtml(client?.subscription_number || '')}" required>
        </div>
        <div>
          <label class="form-label">Commentaire client</label>
          <textarea class="form-control" name="description" rows="5" placeholder="Décrivez l'incident, les symptômes observés et l'impact sur le service." required></textarea>
        </div>
        <div class="public-grid-two">
          <div>
            <label class="form-label">Latitude actuelle</label>
            <input class="form-control" name="submitted_lat" id="submittedLat" placeholder="Auto via GPS">
          </div>
          <div>
            <label class="form-label">Longitude actuelle</label>
            <input class="form-control" name="submitted_lng" id="submittedLng" placeholder="Auto via GPS">
          </div>
        </div>
        <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
          <div class="text-body-secondary small">Astuce: utilisez le GPS du téléphone si vous déclarez depuis le site concerné.</div>
          <button class="btn btn-outline-secondary btn-sm" id="btnLocateIncident" type="button">Utiliser ma position actuelle</button>
        </div>
        <div>
          <label class="form-label">Photos de l'incident</label>
          <input class="form-control" id="incidentPhotos" type="file" accept="image/*" multiple>
          <div class="form-text">Vous pouvez joindre plusieurs photos. Un commentaire sera demandé pour chacune.</div>
        </div>
        <div id="photoCommentList" class="screen-stack"></div>
        <button class="btn btn-primary public-cta" type="submit">Envoyer la demande</button>
      </form>
    </section>
  `;

  const errorBox = root.querySelector('#incidentError');
  const successBox = root.querySelector('#incidentSuccess');
  const form = root.querySelector('#incidentForm');
  const photoInput = root.querySelector('#incidentPhotos');
  const photoCommentList = root.querySelector('#photoCommentList');
  const submittedLat = root.querySelector('#submittedLat');
  const submittedLng = root.querySelector('#submittedLng');
  let selectedFiles = [];

  root.querySelector('#btnLocateIncident').addEventListener('click', () => {
    navigator.geolocation.getCurrentPosition((position) => {
      submittedLat.value = String(position.coords.latitude.toFixed(7));
      submittedLng.value = String(position.coords.longitude.toFixed(7));
    }, () => {
      errorBox.hidden = false;
      errorBox.textContent = 'Impossible de récupérer la position actuelle. Vérifiez les autorisations GPS.';
    }, {
      enableHighAccuracy: true,
      timeout: 12000,
    });
  });

  photoInput.addEventListener('change', () => {
    selectedFiles = Array.from(photoInput.files || []).map((file, index) => ({ file, comment: '', key: `${file.name}-${index}` }));
    renderPhotoCommentEditors();
  });

  function renderPhotoCommentEditors() {
    if (!selectedFiles.length) {
      photoCommentList.innerHTML = '';
      return;
    }

    photoCommentList.innerHTML = selectedFiles.map((item, index) => `
      <div class="public-photo-card" data-key="${escapeHtml(item.key)}">
        <div class="public-photo-meta">
          <strong>Photo ${index + 1}</strong>
          <span>${escapeHtml(item.file.name)}</span>
        </div>
        <textarea class="form-control" data-role="photo-comment" data-index="${index}" rows="2" placeholder="Commentaire associé à cette photo"></textarea>
      </div>
    `).join('');

    photoCommentList.querySelectorAll('[data-role="photo-comment"]').forEach((textarea) => {
      textarea.addEventListener('input', (event) => {
        const index = Number(event.currentTarget.dataset.index || 0);
        if (selectedFiles[index]) {
          selectedFiles[index].comment = event.currentTarget.value;
        }
      });
    });
  }

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    errorBox.hidden = true;
    successBox.hidden = true;

    const payload = Object.fromEntries(new FormData(form).entries());
    const formData = createIncidentFormData(payload, selectedFiles);

    try {
      const response = await createIncident(formData);
      if (!response?.ok) {
        throw new Error('incident_failed');
      }
      form.reset();
      selectedFiles = [];
      renderPhotoCommentEditors();
      successBox.hidden = false;
      successBox.textContent = 'Votre déclaration a été transmise au service client. Vous recevrez les notifications de prise en charge dans votre espace.';
      onSuccess?.();
    } catch (error) {
      errorBox.hidden = false;
      errorBox.textContent = error?.status
        ? 'La demande n\'a pas pu être transmise. Vérifiez les champs du formulaire.'
        : 'Serveur e-Intervention injoignable. Vérifiez le réseau de l\'appareil.';
    }
  });
}

function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#039;');
}
