"use client";

import * as React from "react";
import { DataGrid, GridToolbar, GridColDef, GridFilterModel } from "@mui/x-data-grid";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Download, Filter, X, Search, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import * as XLSX from "xlsx";

interface AnaliticoItem {
  codigo_grupo: string;
  codigo_subgrupo: string;
  codigo_fornecedor: string;
  nome_fornecedor: string;
  id: number;
  codfilial: string;
  recnum: number;
  data_competencia: string;
  data_vencimento: string;
  data_pagamento: string;
  data_caixa: string;
  codigo_conta: string;
  conta: string;
  codigo_centrocusto: string;
  valor: number;
  historico: string;
  historico2: string;
  created_at: string;
  updated_at: string;
  // Campos adicionais do Oracle
  entidade?: string;
  tipo_parceiro?: string;
  valor_previsto?: number;
  valor_confirmado?: number;
  valor_pago?: number;
  numero_lancamento?: number;
  ano_mes_comp?: string;
  codgrupo?: string;
}

interface AnaliticoProps {
  filtros: {
    dataInicio: string;
    dataFim: string;
    centroCusto?: string;
    codigoGrupo?: string;
    codigoSubgrupo?: string;
    codigoConta?: string;
    linhaSelecionada?: string;
  };
}

// Componente de filtro customizado estilo Excel
interface ExcelFilterProps {
  column: GridColDef;
  data: any[];
  onFilterChange: (field: string, values: string[]) => void;
  onSortChange: (field: string, direction: 'asc' | 'desc' | null) => void;
  currentFilter?: string[];
  currentSort?: 'asc' | 'desc' | null;
}

const ExcelFilter: React.FC<ExcelFilterProps> = ({
  column,
  data,
  onFilterChange,
  onSortChange,
  currentFilter = [],
  currentSort = null,
}) => {
  const [isOpen, setIsOpen] = React.useState(false);
  const [searchTerm, setSearchTerm] = React.useState("");
  const [selectedValues, setSelectedValues] = React.useState<string[]>(currentFilter);
  const [selectAll, setSelectAll] = React.useState(false);

  // Obter valores únicos da coluna
  const uniqueValues = React.useMemo(() => {
    const values = data
      .map((row) => {
        const value = row[column.field];
        if (value === null || value === undefined) return "";
        return String(value);
      })
      .filter((value, index, self) => self.indexOf(value) === index && value !== "")
      .sort();

    return values;
  }, [data, column.field]);

  // Filtrar valores baseado na busca
  const filteredValues = React.useMemo(() => {
    if (!searchTerm) return uniqueValues;
    return uniqueValues.filter((value) =>
      value.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [uniqueValues, searchTerm]);

  // Sincronizar estado local com filtros atuais
  React.useEffect(() => {
    setSelectedValues(currentFilter);
  }, [currentFilter]);

  // Verificar se todos estão selecionados
  React.useEffect(() => {
    setSelectAll(selectedValues.length === filteredValues.length && filteredValues.length > 0);
  }, [selectedValues, filteredValues]);

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedValues(filteredValues);
    } else {
      setSelectedValues([]);
    }
  };

  const handleValueToggle = (value: string, checked: boolean) => {
    if (checked) {
      setSelectedValues([...selectedValues, value]);
    } else {
      setSelectedValues(selectedValues.filter((v) => v !== value));
    }
  };

  const handleApply = () => {
    onFilterChange(column.field, selectedValues);
    setIsOpen(false);
  };

  const handleClear = () => {
    setSelectedValues([]);
    setSelectAll(false);
    onFilterChange(column.field, []);
    setIsOpen(false);
  };

  const handleSort = (direction: 'asc' | 'desc') => {
    onSortChange(column.field, direction);
    setIsOpen(false);
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 w-6 p-0 hover:bg-gray-200 rounded-sm"
          onClick={() => setIsOpen(true)}
        >
          <ArrowUpDown className="h-3 w-3 text-gray-600" />
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="text-sm font-medium">
            Filtrar por "{column.headerName}"
          </DialogTitle>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* Opções de ordenação */}
          <div className="space-y-2">
            <div className="text-xs font-medium text-gray-600">Ordenar</div>
            <div className="flex space-x-2">
              <Button
                variant="ghost"
                size="sm"
                className="h-8 text-xs"
                onClick={() => handleSort('asc')}
              >
                <ArrowUp className="h-3 w-3 mr-1" />
                A a Z
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="h-8 text-xs"
                onClick={() => handleSort('desc')}
              >
                <ArrowDown className="h-3 w-3 mr-1" />
                Z a A
              </Button>
            </div>
          </div>

          <div className="border-t pt-2">
            <Button
              variant="ghost"
              size="sm"
              className="h-8 text-xs text-red-600 hover:text-red-700"
              onClick={handleClear}
            >
              <X className="h-3 w-3 mr-1" />
              Limpar Filtro
            </Button>
          </div>

          {/* Barra de pesquisa */}
          <div className="relative">
            <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-400" />
            <Input
              placeholder="Pesquisar"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-8 h-8 text-sm"
            />
          </div>

          {/* Lista de valores com checkboxes */}
          <div className="max-h-60 overflow-y-auto border rounded-md">
            <div className="p-2">
              <div className="flex items-center space-x-2 py-1">
                <Checkbox
                  id="select-all"
                  checked={selectAll}
                  onCheckedChange={handleSelectAll}
                />
                <label htmlFor="select-all" className="text-sm font-medium">
                  (Selecionar Tudo)
                </label>
              </div>
              
              {filteredValues.map((value) => (
                <div key={value} className="flex items-center space-x-2 py-1">
                  <Checkbox
                    id={`value-${value}`}
                    checked={selectedValues.includes(value)}
                    onCheckedChange={(checked: boolean) => handleValueToggle(value, checked)}
                  />
                  <label htmlFor={`value-${value}`} className="text-sm">
                    {value}
                  </label>
                </div>
              ))}
            </div>
          </div>

          {/* Botões de ação */}
          <DialogFooter className="flex space-x-2">
            <Button variant="outline" size="sm" onClick={() => setIsOpen(false)}>
              Cancelar
            </Button>
            <Button size="sm" onClick={handleApply}>
              OK
            </Button>
          </DialogFooter>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default function AnaliticoComponent({ filtros }: AnaliticoProps) {
  const [data, setData] = React.useState<AnaliticoItem[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [globalFilter, setGlobalFilter] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const [columnFilters, setColumnFilters] = React.useState<Record<string, string[]>>({});
  const [columnSorts, setColumnSorts] = React.useState<Record<string, 'asc' | 'desc' | null>>({});
  const [conditions, setConditions] = React.useState([
    { column: "", operator: "contains", value: "" },
  ]);
  
  // Estado para armazenar filtros externos (vindos do teste.tsx)
  const [filtrosExternos, setFiltrosExternos] = React.useState(filtros);

  // Funções para gerenciar filtros customizados
  const handleColumnFilterChange = React.useCallback((field: string, values: string[]) => {
    setColumnFilters(prev => ({
      ...prev,
      [field]: values
    }));
  }, []);

  const handleColumnSortChange = React.useCallback((field: string, direction: 'asc' | 'desc' | null) => {
    setColumnSorts(prev => ({
      ...prev,
      [field]: direction
    }));
  }, []);

  // Função para limpar todos os filtros
  const clearAllFilters = React.useCallback(() => {
    setColumnFilters({});
    setColumnSorts({});
  }, []);

  // Atualizar filtros externos quando os props mudarem
  React.useEffect(() => {
    console.log('🔄 Analítico - useEffect dos filtros chamado');
    console.log('📋 Filtros recebidos via props:', filtros);
    setFiltrosExternos(filtros);
  }, [filtros]);

  const fetchData = React.useCallback(async () => {
    console.log('🔄 Analítico - fetchData chamado');
    console.log('📋 Filtros externos recebidos:', filtrosExternos);
    
    if (!filtrosExternos.dataInicio || !filtrosExternos.dataFim) {
      console.log('⚠️ Sem dataInicio ou dataFim, limpando dados');
      setData([]);
      return;
    }

    setLoading(true);
    try {
      const params = new URLSearchParams();
      
      if (filtrosExternos.dataInicio) {
        params.append('dataInicio', filtrosExternos.dataInicio);
      }
      if (filtrosExternos.dataFim) {
        params.append('dataFim', filtrosExternos.dataFim);
      }
      if (filtrosExternos.centroCusto) {
        params.append('centroCusto', filtrosExternos.centroCusto);
      }
      if (filtrosExternos.codigoGrupo) {
        params.append('codigoGrupo', filtrosExternos.codigoGrupo);
      }
      if (filtrosExternos.codigoConta) {
        params.append('codigoConta', filtrosExternos.codigoConta);
      }

      const url = `/api/analitico-oracle?${params.toString()}`;
      console.log('🌐 Fazendo requisição para:', url);
      
      const response = await fetch(url);
      if (response.ok) {
        const result = await response.json();
        console.log('✅ Resposta da API recebida:', result.length, 'registros');
        console.log('📝 Primeiros 2 registros:', result.slice(0, 2));
        console.log('🔍 Verificando campos específicos:', {
          data_vencimento: result[0]?.data_vencimento,
          data_caixa: result[0]?.data_caixa,
          entidade: result[0]?.entidade,
          valor: result[0]?.valor,
          tipo_valor: typeof result[0]?.valor
        });
        setData(result as AnaliticoItem[]);
      } else {
        console.error("❌ Erro ao buscar dados:", await response.text());
      }
    } catch (error) {
      console.error("❌ Erro ao buscar dados:", error);
    } finally {
      setLoading(false);
    }
  }, [filtrosExternos]);

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

  // Definir colunas do DataGridPro
  const columns = React.useMemo(() => {
    const baseColumns = [
      {
        field: "data_vencimento",
        headerName: "Dt Venc",
        width: 150,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          if (!params.value) return "-";
          try {
            return new Date(params.value).toLocaleDateString("pt-BR");
          } catch (error) {
            return params.value;
          }
        },
      },
      {
        field: "data_caixa",
        headerName: "Dt Caixa",
        width: 130,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          if (!params.value) return "-";
          try {
            return new Date(params.value).toLocaleDateString("pt-BR");
          } catch (error) {
            return params.value;
          }
        },
      },
      {
        field: "entidade",
        headerName: "Entidade",
        width: 100,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => params.value || "-",
      },
      {
        field: "codigo_fornecedor",
        headerName: "Cod.Fornec",
        width: 140,
        sortable: true,
        resizable: true,
      },
      {
        field: "nome_fornecedor",
        headerName: "Fornecedor",
        flex: 1,
        minWidth: 200,
        sortable: true,
        resizable: true,
      },
      {
        field: "codigo_centrocusto",
        headerName: "C Custo",
        width: 130,
        sortable: true,
        resizable: true,
      },
      {
        field: "codigo_conta",
        headerName: "Cod.Conta",
        width: 150,
        sortable: true,
        resizable: true,
      },
      {
        field: "conta",
        headerName: "Conta",
        flex: 1,
        minWidth: 180,
        sortable: true,
        resizable: true,
      },
      {
        field: "valor",
        headerName: "Vl.Realizado",
        type: "number" as const,
        width: 140,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          const value = params.value;
          if (value === null || value === undefined || value === "") return "-";
          const numValue = typeof value === "string" ? parseFloat(value) : Number(value);
          if (isNaN(numValue)) return "-";
          const formatted = new Intl.NumberFormat("pt-BR", {
            style: "currency",
            currency: "BRL",
          }).format(numValue);
          return (
            <span className={numValue < 0 ? "text-red-600" : "text-gray-900"}>
              {formatted}
            </span>
          );
        },
      },
      {
        field: "valor_previsto",
        headerName: "Vl.Previsto",
        type: "number" as const,
        width: 130,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          const value = params.value;
          if (value === null || value === undefined || value === "" || value === 0) return "-";
          const numValue = typeof value === "string" ? parseFloat(value) : Number(value);
          if (isNaN(numValue)) return "-";
          const formatted = new Intl.NumberFormat("pt-BR", {
            style: "currency",
            currency: "BRL",
          }).format(numValue);
          return (
            <span className={numValue < 0 ? "text-red-600" : "text-gray-900"}>
              {formatted}
            </span>
          );
        },
      },
      {
        field: "valor_confirmado",
        headerName: "Vl.Confirmado",
        type: "number" as const,
        width: 140,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          const value = params.value;
          if (value === null || value === undefined || value === "" || value === 0) return "-";
          const numValue = typeof value === "string" ? parseFloat(value) : Number(value);
          if (isNaN(numValue)) return "-";
          const formatted = new Intl.NumberFormat("pt-BR", {
            style: "currency",
            currency: "BRL",
          }).format(numValue);
          return (
            <span className={numValue < 0 ? "text-red-600" : "text-gray-900"}>
              {formatted}
            </span>
          );
        },
      },
      {
        field: "valor_pago",
        headerName: "Vl.Pago",
        type: "number" as const,
        width: 130,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => {
          const value = params.value;
          if (value === null || value === undefined || value === "" || value === 0) return "-";
          const numValue = typeof value === "string" ? parseFloat(value) : Number(value);
          if (isNaN(numValue)) return "-";
          const formatted = new Intl.NumberFormat("pt-BR", {
            style: "currency",
            currency: "BRL",
          }).format(numValue);
          return (
            <span className={numValue < 0 ? "text-red-600" : "text-gray-900"}>
              {formatted}
            </span>
          );
        },
      },
      {
        field: "historico",
        headerName: "Historico",
        flex: 1,
        minWidth: 250,
        sortable: true,
        resizable: true,
      },
      {
        field: "historico2",
        headerName: "Historico 2",
        flex: 1,
        minWidth: 300,
        sortable: true,
        resizable: true,
      },
      {
        field: "numero_lancamento",
        headerName: "Num.Lanc",
        width: 80,
        sortable: true,
        resizable: true,
        renderCell: (params: any) => params.value || "-",
      },
    ];

    // Adicionar renderHeader com filtro Excel para todas as colunas
    return baseColumns.map((col) => ({
      ...col,
      renderHeader: (params: any) => (
        <div className="flex items-center justify-between w-full">
          <span className="text-sm font-medium">{col.headerName}</span>
          <div className="flex items-center">
            <ExcelFilter
              column={col}
              data={data}
              onFilterChange={handleColumnFilterChange}
              onSortChange={handleColumnSortChange}
              currentFilter={columnFilters[col.field] || []}
              currentSort={columnSorts[col.field] || null}
            />
          </div>
        </div>
      ),
    }));
  }, [data, columnFilters, columnSorts, handleColumnFilterChange, handleColumnSortChange]);

  // Filtrar dados baseado nos filtros de coluna
  const filteredData = React.useMemo(() => {
    if (!data || data.length === 0) return data;

    return data.filter((row) => {
      return Object.entries(columnFilters).every(([field, filterValues]) => {
        if (!filterValues || filterValues.length === 0) return true;
        
        const cellValue = (row as any)[field];
        const stringValue = cellValue === null || cellValue === undefined ? "" : String(cellValue);
        
        return filterValues.includes(stringValue);
      });
    }).map((row, index) => ({
      ...row,
      id: `filtered-${row.id || row.recnum || index}` // Garantir ID único e estável
    }));
  }, [data, columnFilters]);

  // Ordenar dados baseado na ordenação de coluna
  const sortedAndFilteredData = React.useMemo(() => {
    if (!filteredData || filteredData.length === 0) return filteredData;

    const sortField = Object.keys(columnSorts).find(field => columnSorts[field] !== null);
    if (!sortField || !columnSorts[sortField]) return filteredData;

    return [...filteredData].sort((a, b) => {
      const aValue = (a as any)[sortField];
      const bValue = (b as any)[sortField];
      
      // Converter para string para comparação
      const aString = aValue === null || aValue === undefined ? "" : String(aValue);
      const bString = bValue === null || bValue === undefined ? "" : String(bValue);
      
      if (columnSorts[sortField] === 'asc') {
        return aString.localeCompare(bString);
      } else {
        return bString.localeCompare(aString);
      }
    });
  }, [filteredData, columnSorts]);

  // Calcular totais das colunas de valores (usando dados filtrados)
  const columnTotals = React.useMemo(() => {
    if (!sortedAndFilteredData || sortedAndFilteredData.length === 0) {
      return {
        valorRealizado: 0,
        valorPrevisto: 0,
        valorConfirmado: 0,
        valorPago: 0,
      };
    }

    const valorRealizado = sortedAndFilteredData.reduce((sum, item) => {
      const valor = typeof item.valor === "string" ? parseFloat(item.valor) : item.valor;
      return sum + (isNaN(valor) ? 0 : valor);
    }, 0);

    const valorPrevisto = sortedAndFilteredData.reduce((sum, item) => {
      const valor = typeof item.valor_previsto === "string" ? parseFloat(item.valor_previsto) : (item.valor_previsto || 0);
      return sum + (isNaN(valor) ? 0 : valor);
    }, 0);

    const valorConfirmado = sortedAndFilteredData.reduce((sum, item) => {
      const valor = typeof item.valor_confirmado === "string" ? parseFloat(item.valor_confirmado) : (item.valor_confirmado || 0);
      return sum + (isNaN(valor) ? 0 : valor);
    }, 0);

    const valorPago = sortedAndFilteredData.reduce((sum, item) => {
      const valor = typeof item.valor_pago === "string" ? parseFloat(item.valor_pago) : (item.valor_pago || 0);
    return sum + (isNaN(valor) ? 0 : valor);
  }, 0);

    return {
      valorRealizado,
      valorPrevisto,
      valorConfirmado,
      valorPago,
    };
  }, [sortedAndFilteredData]);

  // Exportação XLSX
  const exportToExcel = () => {
    if (sortedAndFilteredData.length === 0) return;

    const exportData = sortedAndFilteredData.map((item) => ({
      "Data Competência": item.data_competencia
        ? new Date(item.data_competencia).toLocaleDateString("pt-BR")
        : "-",
      "Data Vencimento": item.data_vencimento
        ? new Date(item.data_vencimento).toLocaleDateString("pt-BR")
        : "-",
      "Data Caixa": item.data_caixa
        ? new Date(item.data_caixa).toLocaleDateString("pt-BR")
        : "-",
      "Código Fornecedor": item.codigo_fornecedor,
      Fornecedor: item.nome_fornecedor,
      "Código Centro Custo": item.codigo_centrocusto,
      "Centro Custo": item.codigo_centrocusto,
      "Código Conta": item.codigo_conta,
      Conta: item.conta,
      Valor: typeof item.valor === "string" ? parseFloat(item.valor) : item.valor,
      Histórico: item.historico,
      "Histórico 2": item.historico2,
      Recnum: item.recnum,
    }));

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(exportData);

    const resumoData = [
      { Métrica: "Total de Registros", Valor: data.length },
      { Métrica: "Valor Total", Valor: columnTotals.valorRealizado },
      { Métrica: "Filtros Aplicados", Valor: "Sim" },
    ];
    const wsResumo = XLSX.utils.json_to_sheet(resumoData);

    XLSX.utils.book_append_sheet(wb, ws, "Dados Analíticos");
    XLSX.utils.book_append_sheet(wb, wsResumo, "Resumo");

    const now = new Date();
    const timestamp = now.toISOString().slice(0, 19).replace(/:/g, "-");
    const fileName = `analitico_${timestamp}.xlsx`;

    XLSX.writeFile(wb, fileName);
  };

  // Aplicar filtros avançados
  const applyFilters = () => {
    // Implementar lógica de filtros avançados se necessário
    setOpen(false);
  };

  const clearFilters = () => {
    setConditions([{ column: "", operator: "contains", value: "" }]);
    setGlobalFilter("");
  };

  return (
    <div className="w-full max-w-none mx-auto p-2">
      {/* Header Section */}
      <div className="mb-2">
        <div className="flex items-center justify-between mb-1">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">
              Análise Analítica{filtros.linhaSelecionada ? ` - ${filtros.linhaSelecionada}` : ""}
            </h1>
            <p className="text-sm text-gray-500">
              Relatório detalhado de transações
            </p>
      </div>

          {/* Filtros Externos Ativos - Centralizado */}
          {(filtrosExternos.dataInicio || filtrosExternos.centroCusto || filtrosExternos.codigoGrupo || filtrosExternos.codigoConta) && (
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
              <span className="text-sm font-medium text-blue-900">Filtros aplicados pela tabela DRE Gerencial:</span>
              <div className="flex flex-wrap gap-2 text-xs text-blue-800">
                {filtrosExternos.dataInicio && filtrosExternos.dataFim && (
                  <span className="px-2 py-1 bg-blue-100 rounded">
                    Período: {filtrosExternos.dataInicio} a {filtrosExternos.dataFim}
              </span>
            )}
                {filtrosExternos.centroCusto && (
                  <span className="px-2 py-1 bg-blue-100 rounded">
                    Centro: {filtrosExternos.centroCusto}
              </span>
            )}
                {filtrosExternos.codigoGrupo && (
                  <span className="px-2 py-1 bg-blue-100 rounded">
                    Grupo: {filtrosExternos.codigoGrupo}
              </span>
            )}
                {filtrosExternos.codigoConta && (
                  <span className="px-2 py-1 bg-blue-100 rounded">
                    Conta: {filtrosExternos.codigoConta}
              </span>
            )}
          </div>
        </div>
          )}
          
          {/* Controls */}
          <div className="flex gap-2 flex-wrap">
            {/* <Input
              placeholder="Filtrar tudo..."
              value={globalFilter ?? ""}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                setGlobalFilter(e.target.value)
              }
              className="w-64 bg-white border-gray-300 focus:border-blue-500 focus:ring-blue-500"
            />
              <Button
              variant="outline"
              onClick={() => setOpen(true)}
              className="bg-white border-gray-300 hover:bg-blue-50 hover:border-blue-300 text-gray-700"
            >
              <Filter className="w-4 h-4 mr-2" />
              Filtros Avançados
            </Button> */}
            {globalFilter && (
              <Button
                variant="outline"
                onClick={clearFilters}
                className="bg-white border-gray-300 hover:bg-red-50 hover:border-red-300 text-gray-700"
              >
                <X className="w-4 h-4 mr-2" />
                Limpar Filtros
              </Button>
            )}
        {data.length > 0 && (
          <div className="flex items-center gap-2">
              <Button
              onClick={clearAllFilters}
              variant="outline"
              size="sm"
              className="flex items-center gap-2 bg-white border-gray-300 hover:bg-red-50 hover:border-red-300 text-gray-700"
            >
              <X className="h-4 w-4" />
              Limpar Filtros
              </Button>
              <Button
            onClick={exportToExcel}
            variant="outline"
            size="sm"
              className="flex items-center gap-2 bg-white border-gray-300 hover:bg-green-50 hover:border-green-300 text-gray-700"
          >
            <Download className="h-4 w-4" />
            Exportar XLSX
              </Button>
            </div>
        )}
            </div>
            </div>

            </div>

      {/* DataGridPro */}
      <Card className="w-full h-[85vh] shadow-lg rounded-2xl">
        <CardContent className="p-4 h-full">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-4">
              <h2 className="text-lg font-semibold">
                Total de Registros: <span className="text-blue-600">{data.length}</span>
              </h2>
              <div className="text-sm text-gray-600">
                Valor Total: <span className={`font-bold ${columnTotals.valorRealizado < 0 ? "text-red-600" : "text-green-600"}`}>
                  {new Intl.NumberFormat("pt-BR", {
                    style: "currency",
                    currency: "BRL",
                  }).format(columnTotals.valorRealizado)}
                </span>
            </div>
          </div>
        </div>

          <div style={{ height: "calc(100% - 2rem)", width: "100%", position: "relative" }}>
            <DataGrid
              key={`datagrid-${sortedAndFilteredData.length}-${Object.keys(columnFilters).length}`}
              rows={sortedAndFilteredData}
              columns={columns}
              loading={loading}
              disableRowSelectionOnClick
              density="compact"
              slots={{ toolbar: GridToolbar }}
              disableColumnMenu={true}
              disableColumnSorting={true}
              hideFooter={true}
              getRowId={(row) => row.id || `row-${row.recnum || Math.random()}`}
              initialState={{
                sorting: { sortModel: [{ field: "data_vencimento", sort: "desc" }] },
              }}
              sx={{
                "& .MuiDataGrid-columnHeaders": {
                  position: "sticky",
                  top: 0,
                  backgroundColor: "#f9fafb",
                  zIndex: 2,
                  borderBottom: "1px solid #e5e7eb",
                },
                "& .MuiDataGrid-cell": { 
                  borderBottom: "1px solid #f0f0f0",
                  fontSize: "0.875rem",
                },
                "& .MuiDataGrid-virtualScroller": { overflowY: "auto" },
                "& .MuiDataGrid-toolbarContainer": {
                  backgroundColor: "#f8fafc",
                  borderBottom: "1px solid #e5e7eb",
                  padding: "8px 16px",
                },
                // Ocultar todos os ícones nativos das colunas
                "& .MuiDataGrid-columnHeaderMenuContainer": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderMenuButton": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderSortIcon": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderSortIconContainer": {
                  display: "none !important",
                },
                "& .MuiDataGrid-iconButtonContainer": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderSeparator": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderSortButton": {
                  display: "none !important",
                },
                // Ocultar qualquer ícone de menu adicional
                "& .MuiDataGrid-menuIcon": {
                  display: "none !important",
                },
                "& .MuiDataGrid-menuIconButton": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderMenuIcon": {
                  display: "none !important",
                },
                "& .MuiDataGrid-columnHeaderMenuIconButton": {
                  display: "none !important",
                },
                "& .MuiDataGrid-menuContainer": {
                  display: "none !important",
                },
                "& .MuiDataGrid-menu": {
                  display: "none !important",
                },
                // Ocultar footer de paginação
                "& .MuiDataGrid-footerContainer": {
                  display: "none !important",
                },
                "& .MuiDataGrid-pagination": {
                  display: "none !important",
                },
                "& .MuiTablePagination-root": {
                  display: "none !important",
                },
                // Garantir que nosso botão customizado apareça
                "& .MuiDataGrid-columnHeaderTitleContainer": {
                  width: "100%",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                },
              }}
            />
            
            {/* Footer com Totalizadores - Posicionado no lugar do footer nativo */}
            {sortedAndFilteredData.length > 0 && (
              <div 
                className="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-2"
                style={{ 
                  height: "48px",
                  display: "flex",
                  alignItems: "center",
                  fontSize: "0.75rem",
                  zIndex: 1
                }}
              >
                <div className="flex items-center w-full">
                  {/* Espaçamento para alinhar com as colunas da tabela */}
                  <div className="w-[150px]"></div> {/* Dt Venc */}
                  <div className="w-[130px]"></div> {/* Dt Caixa */}
                  <div className="w-[100px]"></div> {/* Entidade */}
                  <div className="w-[140px]"></div> {/* Cod.Fornec */}
                  <div className="flex-1"></div> {/* Fornecedor */}
                  <div className="w-[130px]"></div> {/* C Custo */}
                  <div className="w-[150px]"></div> {/* Cod.Conta */}
                  <div className="flex-1"></div> {/* Conta */}
                  
                  {/* Totalizadores das colunas de valor */}
                  <div className={`w-[140px] text-right font-semibold ${columnTotals.valorRealizado < 0 ? 'text-red-600 font-semibold' : 'text-gray-800'}`}>
                    {new Intl.NumberFormat("pt-BR", {
                      style: "currency",
                      currency: "BRL",
                    }).format(columnTotals.valorRealizado)}
                  </div>
                  <div className={`w-[130px] text-right font-semibold ${columnTotals.valorPrevisto < 0 ? 'text-red-600 font-semibold' : 'text-gray-800'}`}>
                    {new Intl.NumberFormat("pt-BR", {
                      style: "currency",
                      currency: "BRL",
                    }).format(columnTotals.valorPrevisto)}
                  </div>
                  <div className={`w-[140px] text-right font-semibold ${columnTotals.valorConfirmado < 0 ? 'text-red-600 font-semibold' : 'text-gray-800'}`}>
                    {new Intl.NumberFormat("pt-BR", {
                      style: "currency",
                      currency: "BRL",
                    }).format(columnTotals.valorConfirmado)}
                  </div>
                  <div className={`w-[130px] text-right font-semibold ${columnTotals.valorPago < 0 ? 'text-red-600 font-semibold' : 'text-gray-800'}`}>
                    {new Intl.NumberFormat("pt-BR", {
                      style: "currency",
                      currency: "BRL",
                    }).format(columnTotals.valorPago)}
                  </div>
                  
                  {/* Espaçamento para o resto */}
                  <div className="flex-1"></div> {/* Historico */}
                  <div className="flex-1"></div> {/* Historico 2 */}
                  <div className="w-[80px]"></div> {/* Num.Lanc */}
                </div>
              </div>
          )}
        </div>
        </CardContent>
      </Card>

      {/* Advanced Filters Dialog */}
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-2xl w-full mx-4 bg-white">
          <DialogHeader className="pb-4">
            <DialogTitle className="text-xl font-semibold text-gray-900">
              Filtros Avançados
            </DialogTitle>
            <p className="text-sm text-gray-600">
              Estes filtros são aplicados sobre os dados já filtrados pela tabela DRE Gerencial.
            </p>
          </DialogHeader>

          <div className="space-y-4 max-h-96 overflow-y-auto bg-white">
            {conditions.map((cond, idx) => (
              <div
                key={idx}
                className="flex gap-2 items-start p-2 bg-gray-50 rounded-lg border border-gray-200"
              >
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Coluna
                  </label>
                  <Select
                    value={cond.column}
                    onValueChange={(v: string) => {
                      const next = [...conditions];
                      next[idx].column = v;
                      setConditions(next);
                    }}
                  >
                    <SelectTrigger className="w-full bg-white border-gray-300">
                      <SelectValue placeholder="Selecione a coluna" />
                    </SelectTrigger>
                    <SelectContent>
                      {columns.map((col: any) => (
                        <SelectItem
                          key={col.field}
                          value={col.field}
                        >
                          {col.headerName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
      </div>

                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Operador
                  </label>
                  <Select
                    value={cond.operator}
                    onValueChange={(v: string) => {
                      const next = [...conditions];
                      next[idx].operator = v;
                      if (v === "empty" || v === "notEmpty")
                        next[idx].value = "";
                      setConditions(next);
                    }}
                  >
                    <SelectTrigger className="w-full bg-white border-gray-300">
                      <SelectValue placeholder="Selecione o operador" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="contains">contém</SelectItem>
                      <SelectItem value="equals">igual a</SelectItem>
                      <SelectItem value="startsWith">começa com</SelectItem>
                      <SelectItem value="endsWith">termina com</SelectItem>
                      <SelectItem value="empty">está vazio</SelectItem>
                      <SelectItem value="notEmpty">não está vazio</SelectItem>
                    </SelectContent>
                  </Select>
            </div>

                {!(cond.operator === "empty" || cond.operator === "notEmpty") && (
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Valor
                    </label>
                    <Input
                      value={cond.value}
                      onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                        const next = [...conditions];
                        next[idx].value = e.target.value;
                        setConditions(next);
                      }}
                      placeholder="Digite o valor"
                      className="w-full bg-white border-gray-300"
                    />
          </div>
                )}

                {conditions.length > 1 && (
                  <div className="flex items-end">
              <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        const next = conditions.filter((_, i) => i !== idx);
                        setConditions(next);
                      }}
                      className="mt-6 text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
                    >
                      ✕
              </Button>
        </div>
      )}
        </div>
            ))}

            <div className="flex justify-center pt-2">
              <Button
                variant="outline"
                onClick={() =>
                  setConditions((prev) => [
                    ...prev,
                    { column: "", operator: "contains", value: "" },
                  ])
                }
                className="flex items-center gap-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 border-blue-200"
              >
                <span className="text-lg">+</span>
                Adicionar condição
              </Button>
            </div>
          </div>

          <DialogFooter className="flex gap-2 pt-3 border-t border-gray-200">
              <Button
              variant="outline"
              onClick={clearFilters}
              className="flex-1 border-gray-300 text-gray-700 hover:bg-gray-50"
            >
              Limpar filtros avançados
              </Button>
              <Button
              onClick={applyFilters}
              className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
              >
              Aplicar filtros
              </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
