import './style.css';

import {
  ListProfiles,
  Calculate,
  ImportMonthlyXLSX,
  GetImportedTotals,
  GetLastImportInfo,
  ExportPDF
} from './wailsjs/go/app/App';

const app = document.querySelector('#app');

/* ---------- helpers ---------- */

function euro(n) {
  if (typeof n !== 'number' || Number.isNaN(n)) return '';
  return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(n);
}

function numberOrZero(s) {
  const cleaned = String(s ?? '').trim().replace(/\s/g, '').replace(',', '.');
  const n = Number(cleaned);
  return Number.isFinite(n) ? n : 0;
}

function intOrZero(s) {
  const n = parseInt(String(s ?? '').trim(), 10);
  return Number.isFinite(n) ? n : 0;
}

function parseAgentDisplay(display) {
  // "NOM Prenom (123456)" => { nom:"NOM", prenom:"Prenom" }
  const s = String(display || '').trim();
  const withoutMat = s.replace(/\(\s*\d+\s*\)\s*$/, '').trim();
  const parts = withoutMat.split(/\s+/).filter(Boolean);
  if (parts.length === 0) return { nom: '', prenom: '' };
  if (parts.length === 1) return { nom: parts[0], prenom: '' };
  return { nom: parts[0], prenom: parts.slice(1).join(' ') };
}

function sectionDetails(sectionKey, title, status, isOpen, innerHTML) {
  return `
    <details class="section" data-section="${sectionKey}" ${isOpen ? 'open' : ''}>
      <summary>
        <span class="section-title">
          ${title}
          <span class="section-status">— ${status}</span>
        </span>
        <span class="chevron" aria-hidden="true"></span>
      </summary>
      <div class="section-body">
        ${innerHTML}
      </div>
    </details>
  `;
}

function autoSelectProfileForMatricule(state, matricule) {
  if (!matricule) {
    state.profileId = '';
    return;
  }
  const match = state.profiles.find(p => String(p.matricule || '') === String(matricule));
  if (match) {
    state.profileId = match.id;
    return;
  }
  // fallback
  const hasTest = state.profiles.some(p => p.id === 'test');
  state.profileId = hasTest ? 'test' : '';
}

/* ---------- auto-load + auto-calc (v0.8) ---------- */

async function recalcNow(state) {
  // Recalcule uniquement si profil OK
  if (!state.profileId) {
    state.rows = [];
    state.total = 0;
    state.error = "Sélectionne un profil (ou choisis un agent pour auto-match).";
    return;
  }
  state.error = '';

  const res = await Calculate({
    profileId: state.profileId,
    q456: numberOrZero(state.q456),
    q458: numberOrZero(state.q458),
    q459: numberOrZero(state.q459),
    q471: numberOrZero(state.q471),
    nbDimFerie: intOrZero(state.nbDimFerie),
  });

  state.rows = res.lines || [];
  state.total = res.total || 0;
  state.sections.details = true;
}

async function loadSelectedAgentIntoForm(state) {
  if (!state.selectedMatricule) return;

  const t = await GetImportedTotals(state.selectedMatricule);

  state.q456 = String(t.q456 ?? 0);
  state.q458 = String(t.q458 ?? 0);
  state.q459 = String(t.q459 ?? 0);
  state.q471 = String(t.q471 ?? 0);
  state.nbDimFerie = String(t.nbDimFerie ?? 0);

  const agent = state.importedAgents.find(a => a.matricule === state.selectedMatricule);
  if (agent) {
    const { nom, prenom } = parseAgentDisplay(agent.display);
    state.nom = nom;
    state.prenom = prenom;
    state.matricule = state.selectedMatricule;
  } else {
    state.matricule = state.selectedMatricule;
  }
}

async function onAgentChanged(state) {
  // 1) Auto profil (match matricule → sinon test)
  autoSelectProfileForMatricule(state, state.selectedMatricule);

  // 2) Auto load valeurs (si import présent)
  if (state.selectedMatricule) {
    await loadSelectedAgentIntoForm(state);
  } else {
    // reset si aucun agent
    state.profileId = '';
    state.q456 = state.q458 = state.q459 = state.q471 = '0';
    state.nbDimFerie = '0';
    state.rows = [];
    state.total = 0;
    state.error = '';
  }

  // 3) Auto calc
  if (state.selectedMatricule && state.profileId) {
    await recalcNow(state);
  } else {
    state.rows = [];
    state.total = 0;
  }
}

async function onProfileChanged(state) {
  // Recalcul “à chaud” si on a déjà des valeurs
  if (state.selectedMatricule && state.profileId) {
    await recalcNow(state);
  } else {
    state.rows = [];
    state.total = 0;
  }
}

/* ---------- UI state ---------- */

function computeStatuses(state) {
  let importStatus = 'non importé';
  if (state.importedAgents.length > 0) {
    if (state.selectedMatricule) {
      const agent = state.importedAgents.find(a => a.matricule === state.selectedMatricule);
      importStatus = agent ? `agent : ${agent.display}` : `agent : ${state.selectedMatricule}`;
    } else {
      importStatus = `${state.importedAgents.length} agents chargés`;
    }
  }

  const currentProfile = state.profiles.find(p => p.id === state.profileId);
  const dim = intOrZero(state.nbDimFerie);
  const profileStatus = currentProfile
    ? `${currentProfile.label} • Dim/JF : ${dim}`
    : 'non sélectionné';

  const values = [
    numberOrZero(state.q456),
    numberOrZero(state.q458),
    numberOrZero(state.q459),
    numberOrZero(state.q471)
  ];
  const filled = values.filter(v => v !== 0).length;
  const inputsStatus = filled === 0 ? 'vides' : `${filled} valeur${filled > 1 ? 's' : ''}`;

  const detailsStatus =
    state.rows.length === 0
      ? 'non calculé'
      : `${state.rows.length} ligne${state.rows.length > 1 ? 's' : ''} • total : ${euro(state.total)}`;

  return { importStatus, profileStatus, inputsStatus, detailsStatus };
}

/* ---------- render ---------- */

function render(state) {
  const st = computeStatuses(state);

  app.innerHTML = `
  <div class="container">

    <div class="card header-card">
      <div class="header-top">
        <div>
          <h2>Paychek - Outil de calcul de rémunération d'astreintes</h2>
        </div>

        <div class="header-actions">
          <button id="toggleAll">Tout afficher</button>
        </div>
      </div>
    </div>

    <div class="card">

      ${sectionDetails(
        'import',
        'Import Excel',
        st.importStatus,
        state.sections.import,
        `
          <button id="importXlsx" class="primary">Importer fichier Excel (.xlsx)</button>

          <div class="row" style="margin-top:12px;">
            <div>
              <label>Agent (Nom Prénom / Matricule)</label>
              <select id="agentSelect">
                <option value="">— Choisir —</option>
                ${state.importedAgents.map(a => `
                  <option value="${a.matricule}" ${a.matricule === state.selectedMatricule ? 'selected' : ''}>
                    ${a.display}
                  </option>
                `).join('')}
              </select>
            </div>
          </div>

          <div style="margin-top:12px; display:flex; gap:10px;">
            <button id="loadAgent">Recharger les valeurs</button>
            <button id="clearAgent">Effacer</button>
          </div>

          ${state.importError ? `<div class="error">${state.importError}</div>` : ''}
        `
      )}

      ${sectionDetails(
        'profile',
        'Profil',
        st.profileStatus,
        state.sections.profile,
        `
          <div class="row">
            <div>
              <label>Profil</label>
              <select id="profile"></select>
            </div>
            <div>
              <label>Nombre de dimanches / jours fériés (forfait 120 €/jour)</label>
              <input id="nbDimFerie" inputmode="numeric" value="${state.nbDimFerie}">
            </div>
          </div>
        `
      )}

      ${sectionDetails(
        'inputs',
        'Interventions (heures)',
        st.inputsStatus,
        state.sections.inputs,
        `
          <div class="row">
            <div>
              <label>456 — Jour</label>
              <input id="q456" value="${state.q456}">
            </div>
            <div>
              <label>458 — Dimanche / férié</label>
              <input id="q458" value="${state.q458}">
            </div>
          </div>

          <div class="row">
            <div>
              <label>459 — Nuit</label>
              <input id="q459" value="${state.q459}">
            </div>
            <div>
              <label>471 — Total heures astreinte</label>
              <input id="q471" value="${state.q471}">
            </div>
          </div>

          <button id="calc" class="primary" style="margin-top:12px;">Calculer</button>
          ${state.error ? `<div class="error">${state.error}</div>` : ''}
        `
      )}

      ${sectionDetails(
        'details',
        'Détail',
        st.detailsStatus,
        state.sections.details,
        `
          <table>
            <thead>
              <tr>
                <th>Code</th>
                <th>Libellé</th>
                <th class="right">Base</th>
                <th class="right">Quantité</th>
                <th class="right">Total</th>
              </tr>
            </thead>
            <tbody>
              ${state.rows.map(r => `
                <tr>
                  <td>${r.code}</td>
                  <td>${r.label}</td>
                  <td class="right">${Number(r.rate).toFixed(2)}</td>
                  <td class="right">${Number(r.quantity).toFixed(2)} ${r.unit}</td>
                  <td class="right">${euro(r.amount)}</td>
                </tr>
              `).join('')}
            </tbody>
            <tfoot>
              <tr>
                <td colspan="4" class="right total">TOTAL BRUT</td>
                <td class="right total">${euro(state.total)}</td>
              </tr>
            </tfoot>
          </table>
        `
      )}

    </div>

    <div class="export-bar">
      <button id="exportPdf" class="primary">Exporter en PDF</button>
    </div>

  </div>
  `;

  /* ---------- section state ---------- */

  document.querySelectorAll('details.section[data-section]').forEach(d => {
    d.ontoggle = () => {
      const key = d.getAttribute('data-section');
      state.sections[key] = d.open;
    };
  });

const toggleBtn = document.getElementById('toggleAll');
if (toggleBtn) {
  toggleBtn.onclick = () => {
    const sections = document.querySelectorAll('details');
    const allOpen = Array.from(sections).every(d => d.open);

    sections.forEach(d => {
      d.open = !allOpen;
    });

    toggleBtn.textContent = allOpen
      ? 'Tout afficher'
      : 'Tout masquer';
    const toggleAllBtn = document.getElementById('toggleAll');
  if (toggleAllBtn) {
    const sections = document.querySelectorAll('details');
    const allOpen =
      sections.length > 0 &&
      Array.from(sections).every(d => d.open);

    toggleAllBtn.textContent = allOpen
      ? 'Tout masquer'
      : 'Tout afficher';
  }
};
}

  /* ---------- profile ---------- */

  const profileSel = document.getElementById('profile');
  profileSel.innerHTML = `
    <option value="">— Choisir —</option>
    ${state.profiles.map(p =>
      `<option value="${p.id}" ${p.id === state.profileId ? 'selected' : ''}>${p.label}</option>`
    ).join('')}
  `;

  profileSel.onchange = async (e) => {
    state.profileId = e.target.value;
    try {
      await onProfileChanged(state);   // ✅ auto-calc “à chaud”
      render(state);
    } catch (err) {
      state.error = String(err);
      render(state);
    }
  };

  /* ---------- import ---------- */

document.getElementById('importXlsx').onclick = async () => {
  try {
    state.importedAgents = await ImportMonthlyXLSX() || [];
    state.importError = '';

    // 🔧 Récupère le mois normalisé détecté par le backend (utilisé ensuite par l'export PDF)
    try {
      const info = await GetLastImportInfo();
      if (info && info.yearMonth) {
        state.yearMonth = info.yearMonth;
      }
    } catch (_) {
      // Ne pas bloquer l'import si l'info n'est pas dispo
    }

    // Si un agent est déjà sélectionné, on re-joue la logique (profil + load + calc)
    if (state.selectedMatricule) {
      await onAgentChanged(state);
    }
    render(state);
  } catch (e) {
    state.importError = String(e);
    render(state);
  }
};

  document.getElementById('agentSelect').onchange = async (e) => {
    state.selectedMatricule = e.target.value;
    try {
      await onAgentChanged(state);     // ✅ auto profil + auto load + auto calc
      render(state);
    } catch (err) {
      state.error = String(err);
      render(state);
    }
  };

  document.getElementById('loadAgent').onclick = async () => {
    if (!state.selectedMatricule) return;
    try {
      await loadSelectedAgentIntoForm(state);
      if (state.profileId) {
        await recalcNow(state);        // ✅ rechargement => recalcul
      }
      render(state);
    } catch (e) {
      state.error = String(e);
      render(state);
    }
  };

  document.getElementById('clearAgent').onclick = () => {
    state.selectedMatricule = '';
    state.profileId = '';
    state.q456 = state.q458 = state.q459 = state.q471 = '0';
    state.nbDimFerie = '0';
    state.rows = [];
    state.total = 0;
    state.error = '';
    render(state);
  };

  /* ---------- manual calculation button ---------- */

  document.getElementById('calc').onclick = async () => {
    try {
      await recalcNow(state);
      render(state);
    } catch (e) {
      state.error = String(e);
      render(state);
    }
  };

  /* ---------- export ---------- */

  document.getElementById('exportPdf').onclick = async () => {
    try {
      if (!state.profileId) {
        alert("Sélectionne un profil (ou choisis un agent pour auto-match).");
        return;
      }
      await ExportPDF({
        meta: {
          yearMonth: state.yearMonth,
          nom: state.nom,
          prenom: state.prenom,
          matricule: state.matricule
        },
        request: {
          profileId: state.profileId,
          q456: numberOrZero(state.q456),
          q458: numberOrZero(state.q458),
          q459: numberOrZero(state.q459),
          q471: numberOrZero(state.q471),
          nbDimFerie: intOrZero(state.nbDimFerie),
        }
      });
    } catch (e) {
      alert(String(e));
    }
  };
}

/* ---------- boot ---------- */

async function boot() {
  const state = {
    profiles: [],
    profileId: '',

    q456: '0', q458: '0', q459: '0', q471: '0',
    nbDimFerie: '0',

    rows: [], total: 0, error: '',

    importedAgents: [], selectedMatricule: '', importError: '',

    yearMonth: '', nom: '', prenom: '', matricule: '',

    sections: { import: true, profile: false, inputs: false, details: false }
  };

  state.profiles = await ListProfiles();
  render(state);
}

boot();
