import { createContext, useContext, useEffect, useState, useMemo, useCallback } from 'react';
import { api } from '../api.js';
import { useUi } from './UiContext.jsx';

const Ctx = createContext(null);

const MOIS      = ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'];
const MOIS_LONG = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];

export function InteretsChartProvider({ children, netMode, pfuRates, activeView, activeId }) {
  const { chartInterets, chartCapital, chartCashback } = useUi();

  const today        = new Date();
  const currentYear  = today.getFullYear();
  const currentMonth = today.getMonth() + 1;

  // ── État partagé ────────────────────────────────────────────────
  const [annee,           setAnnee]           = useState(currentYear);
  const [inclureInterets, setInclureInterets] = useState(true);
  const [inclureCapital,  setInclureCapital]  = useState(false);
  const [inclureCashback, setInclureCashback] = useState(false);
  const [selectedMonth,   setSelectedMonth]   = useState(null); // 0-11 | null
  const [rawData,         setRawData]         = useState({ rembourses: [], projections: [], annees: [] });

  // ── Mode global (TOUT) ──────────────────────────────────────────
  const [modeGlobal,    setModeGlobal]    = useState(false);
  const [selectedYear,  setSelectedYear]  = useState(null); // year number | null
  const [rawDataGlobal, setRawDataGlobal] = useState({ rembourses: [], projections: [], annees: [] });

  const toggleModeGlobal = useCallback(() => {
    setModeGlobal(prev => {
      if (!prev) setSelectedYear(null); // reset sélection en entrant dans le mode
      return !prev;
    });
  }, []);

  // Filtres reçu / projeté (force reçu si les deux seraient désactivés)
  const [showActual,    setShowActualRaw]    = useState(true);
  const [showProjected, setShowProjected]    = useState(true);
  const setShowActual = useCallback((val) => {
    setShowActualRaw(prev => (val === false || val === prev ? (!prev && !showProjected ? true : val === false ? false : !prev) : val));
  }, [showProjected]);
  const toggleActual    = useCallback(() => setShowActualRaw(prev => (!prev && !showProjected) ? true : !prev), [showProjected]);
  const toggleProjected = useCallback(() => setShowProjected(prev => !prev), []);
  const selectActualOnly    = useCallback(() => { setShowActualRaw(true);  setShowProjected(false); }, []);
  const selectProjectedOnly = useCallback(() => { setShowActualRaw(false); setShowProjected(true);  }, []);
  const setActualProjected  = useCallback((actual, projected) => { setShowActualRaw(actual); setShowProjected(projected); }, []);

  // ── Fetch mensuel ────────────────────────────────────────────────
  useEffect(() => {
    const params = { annee, ...(activeView === 'all' ? { scope: 'all' } : {}) };
    api.get('/dashboard/interets-mensuels', params)
      .then(res => setRawData(res))
      .catch(() => {});
  }, [annee, activeView, activeId]);

  // ── Fetch annuel (global) ────────────────────────────────────────
  useEffect(() => {
    const params = activeView === 'all' ? { scope: 'all' } : {};
    api.get('/dashboard/interets-annuels', params)
      .then(res => setRawDataGlobal(res))
      .catch(() => {});
  }, [activeView, activeId]);

  // Réinitialiser la sélection au changement d'année
  useEffect(() => { setSelectedMonth(null); }, [annee]);

  // ── PFU helper ───────────────────────────────────────────────────
  const getPfuReduction = useCallback((year) => {
    if (!pfuRates?.length) return 0;
    const r = pfuRates.find(r => r.annee === year)
      ?? pfuRates.reduce((best, r) => r.annee > best.annee ? r : best, pfuRates[0]);
    return (r.prelev_sociaux + r.impot_revenu) / 100;
  }, [pfuRates]);

  // ── Calcul mensuel ───────────────────────────────────────────────
  const months = useMemo(() => {
    const reduction = getPfuReduction(annee);
    return Array.from({ length: 12 }, (_, i) => {
      const m       = i + 1;
      const moisStr = `${annee}-${String(m).padStart(2,'0')}`;
      const isCurrent = annee === currentYear && m === currentMonth;
      const isFuture  = annee > currentYear || (annee === currentYear && m > currentMonth);

      const rembData = rawData.rembourses?.find(r => r.mois === moisStr);
      const projData = rawData.projections?.find(p => p.mois === moisStr);

      const rawInterets     = rembData ? (netMode ? (rembData.interets_nets||0) : (rembData.interets_bruts||0)) : 0;
      const rawInteretsProj = projData && (isCurrent||isFuture)
        ? (netMode ? (projData.interets_prevus||0)*(1-reduction) : (projData.interets_prevus||0)) : 0;

      const cashbackAmt    = inclureCashback ? (rembData?.cashback||0)   : 0;
      const capitalAmt     = inclureCapital  ? (rembData?.capital||0)    : 0;
      const interetsAmt    = inclureInterets ? rawInterets               : 0;
      const capitalProjAmt = inclureCapital && projData && (isCurrent||isFuture) ? (projData.capital_prevu||0) : 0;
      const interetsProjAmt= inclureInterets ? rawInteretsProj           : 0;

      return {
        m, idx: i,
        label: MOIS[i], labelLong: MOIS_LONG[i],
        actual:    capitalAmt + cashbackAmt + interetsAmt,
        projected: capitalProjAmt + interetsProjAmt,
        total:     capitalAmt + cashbackAmt + interetsAmt + capitalProjAmt + interetsProjAmt,
        isCurrentMonth: isCurrent, isFuture,
        cashbackAmt, capitalAmt, interetsAmt, capitalProjAmt, interetsProjAmt,
      };
    });
  }, [rawData, netMode, getPfuReduction, annee, currentYear, currentMonth,
      inclureInterets, inclureCapital, inclureCashback]);

  const annualTotal  = useMemo(() => months.reduce((s, m) => s + m.total, 0), [months]);
  const availableYears = rawData.annees ?? [];

  // ── Calcul annuel (mode global) ──────────────────────────────────
  const years = useMemo(() => {
    // Collecter toutes les années connues (rembourses + projections + annees)
    const allKnown = new Set([
      ...(rawDataGlobal.annees ?? []),
      ...(rawDataGlobal.rembourses ?? []).map(r => r.annee),
      ...(rawDataGlobal.projections ?? []).map(p => p.annee),
    ]);
    // Toujours inclure l'année courante
    allKnown.add(currentYear);

    const allSorted = [...allKnown].map(Number).sort((a, b) => a - b);

    // Algorithme de fenêtrage
    const pastYears   = allSorted.filter(y => y < currentYear);
    const futureYears = allSorted.filter(y => y > currentYear);
    const pastCount   = Math.min(pastYears.length, 8); // currentYear en position max 9
    const pastSlice   = pastYears.slice(-pastCount);
    const usedSlots   = pastCount + 1; // +1 for currentYear
    const projCount   = Math.max(3, 12 - usedSlots);
    const futureSlice = futureYears.slice(0, projCount);
    const visibleYears = [...pastSlice, currentYear, ...futureSlice];

    return visibleYears.map(y => {
      const isCurrent = y === currentYear;
      const isFuture  = y > currentYear;
      const reduction = getPfuReduction(y);

      const rembData = rawDataGlobal.rembourses?.find(r => Number(r.annee) === y);
      const projData = rawDataGlobal.projections?.find(p => Number(p.annee) === y);

      const rawInterets     = rembData ? (netMode ? (rembData.interets_nets||0) : (rembData.interets_bruts||0)) : 0;
      const rawInteretsProj = projData
        ? (netMode ? (projData.interets_prevus||0)*(1-reduction) : (projData.interets_prevus||0)) : 0;

      const cashbackAmt     = inclureCashback ? (rembData?.cashback||0)        : 0;
      const capitalAmt      = inclureCapital  ? (rembData?.capital||0)         : 0;
      const interetsAmt     = inclureInterets ? rawInterets                    : 0;
      const capitalProjAmt  = inclureCapital  ? (projData?.capital_prevu||0)   : 0;
      const interetsProjAmt = inclureInterets ? rawInteretsProj                : 0;

      return {
        y,
        label: String(y),
        isCurrent, isFuture,
        actual:    capitalAmt + cashbackAmt + interetsAmt,
        projected: capitalProjAmt + interetsProjAmt,
        total:     capitalAmt + cashbackAmt + interetsAmt + capitalProjAmt + interetsProjAmt,
        cashbackAmt, capitalAmt, interetsAmt, capitalProjAmt, interetsProjAmt,
      };
    });
  }, [rawDataGlobal, netMode, getPfuReduction, currentYear,
      inclureInterets, inclureCapital, inclureCashback]);

  const globalTotal = useMemo(() => years.reduce((s, y) => s + y.total, 0), [years]);

  return (
    <Ctx.Provider value={{
      // Année
      annee, setAnnee, availableYears,
      // Toggles types
      inclureInterets, setInclureInterets,
      inclureCapital,  setInclureCapital,
      inclureCashback, setInclureCashback,
      // Mois sélectionné (liaison bar ↔ donut)
      selectedMonth, setSelectedMonth,
      // Filtres reçu / projeté
      showActual, toggleActual,
      showProjected, toggleProjected,
      selectActualOnly, selectProjectedOnly, setActualProjected,
      // Mode global (TOUT)
      modeGlobal, toggleModeGlobal,
      selectedYear, setSelectedYear,
      years, globalTotal,
      // Données
      months, annualTotal,
      rawData, rawDataGlobal,
      currentYear, currentMonth,
      // Affichage
      netMode,
      // Couleurs palette
      chartInterets, chartCapital, chartCashback,
    }}>
      {children}
    </Ctx.Provider>
  );
}

export const useInteretsChart = () => useContext(Ctx);
