import { useState, useEffect, useCallback } from 'react';
import * as dashboardService from '../services/grDashboardService';
import { toast } from 'sonner';

/**
 * Normaliza strings com problemas de encoding (ex: ? no lugar de acentos)
 */
const normalizeString = (str) => {
  if (!str || typeof str !== 'string') return str;
  return str
    .replace(/N\?O/g, 'NÃO')
    .replace(/AN\?LISE/g, 'ANÁLISE')
    .replace(/PEND\?NCIAS/g, 'PENDÊNCIAS')
    .replace(/REVIS\?O/g, 'REVISÃO')
    .replace(/D\?VIDA/g, 'DÚVIDA')
    .replace(/CONTRAT\?RIA/g, 'CONTRATÁRIA')
    .replace(/LOG\?STICA/g, 'LOGÍSTICA')
    .replace(/AN\?NCIO/g, 'ANÚNCIO');
};

const normalizeData = (data) => {
  if (Array.isArray(data)) {
    return data.map(item => {
      const newItem = { ...item };
      Object.keys(newItem).forEach(key => {
        if (typeof newItem[key] === 'string') {
          newItem[key] = normalizeString(newItem[key]);
        }
      });
      return newItem;
    });
  }
  if (data && typeof data === 'object') {
    const newData = { ...data };
    Object.keys(newData).forEach(key => {
      if (typeof newData[key] === 'string') {
        newData[key] = normalizeString(newData[key]);
      }
    });
    return newData;
  }
  return data;
};

export const useGrDashboard = () => {
  const [filters, setFilters] = useState({
    mes: new Date().getMonth() + 1,
    ano: new Date().getFullYear(),
    modo: 'mensal' // 'mensal' ou 'anual'
  });

  const [data, setData] = useState({
    // Registros
    resumo: null,
    baseEst: [],
    coordenadorEst: [],
    despachanteEst: [],
    baseCoordenadorEst: [],
    globalStatusEst: [],
    // Contratos
    statusContratos: [],
    producaoBaseContratos: [],
    coordenadorStatusAssinatura: [],
    despachanteContratos: []
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = {
        ano: filters.ano,
        ...(filters.modo === 'mensal' && { mes: filters.mes })
      };

      const [
        resumo,
        baseEst,
        coordenadorEst,
        despachanteEst,
        baseCoordenadorEst,
        globalStatusEst,
        statusContratos,
        producaoBaseContratos,
        coordenadorStatusAssinatura,
        despachanteContratos
      ] = await Promise.all([
        dashboardService.getResumo(params),
        dashboardService.getBaseStatistics(params),
        dashboardService.getCoordenadorStatistics(params),
        dashboardService.getDespachanteStatistics(params),
        dashboardService.getBaseCoordenadorStatistics(params),
        dashboardService.getGlobalStatusStatistics(params),
        dashboardService.getGlobalStatusContratos(params),
        dashboardService.getProducaoBaseContratos(params),
        dashboardService.getCoordenadorStatusAssinatura(params),
        dashboardService.getDespachanteContratos(params)
      ]);

      setData({
        resumo: normalizeData(resumo),
        baseEst: normalizeData(Array.isArray(baseEst) ? baseEst : []),
        coordenadorEst: normalizeData(Array.isArray(coordenadorEst) ? coordenadorEst : []),
        despachanteEst: normalizeData(Array.isArray(despachanteEst) ? despachanteEst : []),
        baseCoordenadorEst: normalizeData(Array.isArray(baseCoordenadorEst) ? baseCoordenadorEst : []),
        globalStatusEst: normalizeData(Array.isArray(globalStatusEst) ? globalStatusEst : []),
        statusContratos: normalizeData(Array.isArray(statusContratos) ? statusContratos : []),
        producaoBaseContratos: normalizeData(Array.isArray(producaoBaseContratos) ? producaoBaseContratos : []),
        coordenadorStatusAssinatura: normalizeData(Array.isArray(coordenadorStatusAssinatura) ? coordenadorStatusAssinatura : []),
        despachanteContratos: normalizeData(Array.isArray(despachanteContratos) ? despachanteContratos : [])
      });
    } catch (err) {
      console.error('Error fetching dashboard data:', err);
      setError(err);
      toast.error('Erro ao carregar dados do dashboard');
    } finally {
      setLoading(false);
    }
  }, [filters]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return {
    data,
    loading,
    error,
    filters,
    setFilters,
    refresh: fetchData
  };
};
