import { useState, useEffect, useCallback } from 'react'
import { 
  Wallet, 
  TrendingUp, 
  TrendingDown, 
  Clock, 
  FileText, 
  Building2, 
  CheckCircle2,
  AlertCircle,
  ArrowUpRight,
  Loader2,
  Leaf,
  Shield,
  Search,
  X,
  Filter
} from 'lucide-react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line } from 'recharts'
import api from '../services/api'
import { User, DashboardIndicadores } from '../types'
import Modal from '../components/Modal'

interface StatsCard {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  color: string;
  statusKey: string;
}

type DashTab = 'geral' | 'esg'

export default function Dashboard() {
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState<DashboardIndicadores | null>(null)
  const [user, setUser] = useState<User | null>(null)
  const [activeTab, setActiveTab] = useState<DashTab>('geral')
  const [esgData, setEsgData] = useState<any>(null)
  const [esgLoading, setEsgLoading] = useState(false)

  // Chart filter state
  const [chartFilter, setChartFilter] = useState<'todos' | 'centro_custo' | 'categoria'>('todos')
  const [chartFilterId, setChartFilterId] = useState('')
  const [chartData, setChartData] = useState<any[]>([])
  const [centrosCusto, setCentrosCusto] = useState<{id:string;nome:string}[]>([])
  const [categorias, setCategorias] = useState<{id:string;nome:string}[]>([])

  // Category chart data (from backend)
  const [categoryData, setCategoryData] = useState<any[]>([])

  // Card drill-down modal
  const [drillModal, setDrillModal] = useState(false)
  const [drillTitle, setDrillTitle] = useState('')
  const [drillData, setDrillData] = useState<any[]>([])
  const [drillLoading, setDrillLoading] = useState(false)

  // Search
  const [searchTerm, setSearchTerm] = useState('')
  const [searchResults, setSearchResults] = useState<any>(null)
  const [searchLoading, setSearchLoading] = useState(false)

  useEffect(() => {
    const userData = localStorage.getItem('user')
    if (userData) setUser(JSON.parse(userData))
    fetchDashboard()
    fetchLookups()
    fetchCategoryData()
  }, [])

  useEffect(() => {
    if (activeTab === 'esg' && !esgData) fetchEsg()
  }, [activeTab])

  useEffect(() => {
    fetchChartData()
  }, [chartFilter, chartFilterId])

  const fetchDashboard = async () => {
    try {
      const { data } = await api.get('/dashboard/indicadores')
      setStats(data)
    } catch (err) {
      console.error('Error fetching dashboard:', err)
    } finally {
      setLoading(false)
    }
  }

  const fetchLookups = async () => {
    try {
      const [catRes, ccRes] = await Promise.all([
        api.get('/categorias').catch(() => ({ data: [] })),
        api.get('/centros-custo').catch(() => ({ data: [] })),
      ])
      setCategorias((catRes.data || []).map((c: any) => ({ id: c.id, nome: c.nome })))
      setCentrosCusto((ccRes.data || []).map((c: any) => ({ id: c.id, nome: c.nome })))
    } catch {}
  }

  const fetchChartData = async () => {
    try {
      const params: any = { ano: 2026 }
      if (chartFilter === 'centro_custo' && chartFilterId) params.centro_custo_id = chartFilterId
      if (chartFilter === 'categoria' && chartFilterId) params.categoria_id = chartFilterId
      const { data } = await api.get('/dashboard/consumo-orcamento', { params })
      setChartData(data)
    } catch (err) {
      console.error('Error fetching chart data:', err)
    }
  }

  const fetchCategoryData = async () => {
    try {
      const { data } = await api.get('/dashboard/categorias-quantidade')
      setCategoryData(data)
    } catch (err) {
      console.error('Error fetching category data:', err)
    }
  }

  const fetchEsg = async () => {
    setEsgLoading(true)
    try {
      const { data } = await api.get('/dashboard/esg')
      setEsgData(data)
    } catch (err) {
      console.error('Error fetching ESG:', err)
    } finally {
      setEsgLoading(false)
    }
  }

  const handleCardClick = async (statusKey: string, title: string) => {
    setDrillTitle(title)
    setDrillModal(true)
    setDrillLoading(true)
    try {
      const { data } = await api.get('/dashboard/demandas-detalhe', { params: { status: statusKey } })
      setDrillData(data)
    } catch (err) {
      console.error('Error fetching drill-down:', err)
      setDrillData([])
    } finally {
      setDrillLoading(false)
    }
  }

  const handleSearch = useCallback(async (term: string) => {
    if (term.trim().length < 2) {
      setSearchResults(null)
      return
    }
    setSearchLoading(true)
    try {
      const { data } = await api.get('/dashboard/busca', { params: { q: term } })
      setSearchResults(data)
    } catch {
      setSearchResults(null)
    } finally {
      setSearchLoading(false)
    }
  }, [])

  useEffect(() => {
    const timer = setTimeout(() => handleSearch(searchTerm), 400)
    return () => clearTimeout(timer)
  }, [searchTerm, handleSearch])

  const formatCurrency = (v: number) => new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v || 0)

  const statsCards: StatsCard[] = [
    { title: 'Demandas Abertas', value: stats?.demandas_abertas ?? 0, icon: <FileText className="w-6 h-6" />, color: 'from-primary to-accent', statusKey: 'abertas' },
    { title: 'Em Cotação', value: stats?.em_cotacao ?? 0, icon: <Wallet className="w-6 h-6" />, color: 'from-secondary to-secondary-light', statusKey: 'em_cotacao' },
    { title: 'Em Aprovação', value: stats?.em_aprovacao ?? 0, icon: <Clock className="w-6 h-6" />, color: 'from-amber-500 to-orange-500', statusKey: 'em_aprovacao' },
    { title: 'OS Ativas', value: stats?.os_ativas ?? 0, icon: <TrendingUp className="w-6 h-6" />, color: 'from-green-500 to-emerald-500', statusKey: 'concluidas' },
  ]

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    )
  }

  const manutencaoPieData = esgData ? [
    { name: 'Preventiva', value: esgData.total_preventivas, color: '#1A7A4C' },
    { name: 'Corretiva', value: esgData.total_corretivas, color: '#FF8F00' },
    { name: 'Emergencial', value: esgData.total_emergenciais, color: '#E53935' },
  ] : []

  const filterOptions = chartFilter === 'centro_custo' ? centrosCusto : chartFilter === 'categoria' ? categorias : []

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Welcome header + Search */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-text">
            Olá, {user?.nome?.split(' ')[0] || 'Usuário'}! 👋
          </h1>
          <p className="text-gray mt-1">Aqui está o resumo das suas operações de facilities.</p>
        </div>
        <div className="relative w-full sm:w-80">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-light" />
          <input
            type="text"
            placeholder="Buscar demandas..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="input-field pl-10 pr-8 !py-2 text-sm"
          />
          {searchTerm && (
            <button onClick={() => { setSearchTerm(''); setSearchResults(null) }} className="absolute right-3 top-1/2 -translate-y-1/2">
              <X className="w-4 h-4 text-gray" />
            </button>
          )}
          {/* Search Results Dropdown */}
          {searchResults && (
            <div className="absolute top-full mt-1 left-0 right-0 bg-white rounded-xl shadow-xl border border-border z-50 max-h-80 overflow-y-auto">
              {searchResults.demandas?.length > 0 ? (
                <div className="p-2">
                  <p className="text-xs text-gray px-2 py-1 font-semibold">Demandas</p>
                  {searchResults.demandas.map((d: any) => (
                    <div key={d.id} className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50 cursor-pointer">
                      <FileText className="w-4 h-4 text-primary flex-shrink-0" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-text truncate">{d.numero ? `#${d.numero} - ` : ''}{d.titulo}</p>
                        <p className="text-xs text-gray">{d.categoria} · {d.status}</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="p-4 text-center text-sm text-gray">Nenhum resultado encontrado</div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 p-1 rounded-xl">
        <button onClick={() => setActiveTab('geral')}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${activeTab === 'geral' ? 'bg-white text-primary shadow-sm' : 'text-gray hover:text-text'}`}>
          <TrendingUp className="w-4 h-4" /> Geral
        </button>
        <button onClick={() => setActiveTab('esg')}
          className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${activeTab === 'esg' ? 'bg-white shadow-sm' : 'text-gray hover:text-text'}`}
          style={activeTab === 'esg' ? { color: '#1A7A4C' } : {}}>
          <Leaf className="w-4 h-4" /> ESG
        </button>
      </div>

      {activeTab === 'geral' ? (
        <>
          {/* Stats Cards - clickable */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
            {statsCards.map((card, index) => (
              <div
                key={index}
                className="card group hover:shadow-lg transition-all duration-300 cursor-pointer"
                onClick={() => handleCardClick(card.statusKey, card.title)}
              >
                <div className="flex items-start justify-between mb-4">
                  <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${card.color} flex items-center justify-center text-white shadow-lg`}>
                    {card.icon}
                  </div>
                  <ArrowUpRight className="w-4 h-4 text-gray-light opacity-0 group-hover:opacity-100 transition-opacity" />
                </div>
                <p className="text-gray text-sm mb-1">{card.title}</p>
                <p className="text-2xl sm:text-3xl font-bold text-text">{card.value}</p>
              </div>
            ))}
          </div>

          {/* Charts Row */}
          <div className="grid lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 card">
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-6 gap-3">
                <div>
                  <h2 className="text-lg font-semibold text-text">Orçamento vs Realizado</h2>
                  <p className="text-sm text-gray">Comparativo mensal</p>
                </div>
                {/* Filter Controls */}
                <div className="flex items-center gap-2">
                  <Filter className="w-4 h-4 text-gray" />
                  <select
                    value={chartFilter}
                    onChange={(e) => { setChartFilter(e.target.value as any); setChartFilterId('') }}
                    className="input-field !py-1.5 !px-3 text-sm w-auto"
                  >
                    <option value="todos">Todos</option>
                    <option value="centro_custo">Centro de Custo</option>
                    <option value="categoria">Categoria</option>
                  </select>
                  {chartFilter !== 'todos' && (
                    <select
                      value={chartFilterId}
                      onChange={(e) => setChartFilterId(e.target.value)}
                      className="input-field !py-1.5 !px-3 text-sm w-auto max-w-[180px]"
                    >
                      <option value="">Selecione...</option>
                      {filterOptions.map(o => <option key={o.id} value={o.id}>{o.nome}</option>)}
                    </select>
                  )}
                </div>
              </div>
              <div className="h-72">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={chartData} barGap={8}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#E0E0E0" vertical={false} />
                    <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#757575', fontSize: 12 }} />
                    <YAxis axisLine={false} tickLine={false} tick={{ fill: '#757575', fontSize: 12 }} />
                    <Tooltip contentStyle={{ backgroundColor: '#fff', border: '1px solid #E0E0E0', borderRadius: '12px', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)' }}
                      formatter={(value: number) => formatCurrency(value)} />
                    <Bar dataKey="planejado" fill="#1A237E" radius={[4, 4, 0, 0]} name="Planejado" />
                    <Bar dataKey="realizado" fill="#E65100" radius={[4, 4, 0, 0]} name="Realizado" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
            <div className="card">
              <div className="mb-6">
                <h2 className="text-lg font-semibold text-text">Por Categoria</h2>
                <p className="text-sm text-gray">Quantidade de demandas</p>
              </div>
              <div className="h-60">
                {categoryData.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={categoryData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={4} dataKey="value" label={({ name, value }) => `${value}`}>
                        {categoryData.map((entry: any, index: number) => (<Cell key={`cell-${index}`} fill={entry.color} />))}
                      </Pie>
                      <Legend verticalAlign="bottom" iconType="circle" iconSize={8} formatter={(value) => <span className="text-sm text-gray">{value}</span>} />
                      <Tooltip formatter={(value: number, name: string) => [`${value} demandas`, name]} />
                    </PieChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="flex items-center justify-center h-full text-gray text-sm">Sem dados</div>
                )}
              </div>
            </div>
          </div>

          {/* Quick Stats & Activity */}
          <div className="grid lg:grid-cols-3 gap-6">
            <div className="card">
              <h2 className="text-lg font-semibold text-text mb-4">Resumo Rápido</h2>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-3 bg-card rounded-xl">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center"><FileText className="w-5 h-5 text-blue-600" /></div>
                    <span className="font-medium text-text">Demandas Abertas</span>
                  </div>
                  <span className="text-xl font-bold text-text">{stats?.demandas_abertas ?? 0}</span>
                </div>
                <div className="flex items-center justify-between p-3 bg-card rounded-xl">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-lg bg-amber-100 flex items-center justify-center"><AlertCircle className="w-5 h-5 text-amber-600" /></div>
                    <span className="font-medium text-text">Pendentes</span>
                  </div>
                  <span className="text-xl font-bold text-text">{stats?.pendentes ?? 0}</span>
                </div>
                <div className="flex items-center justify-between p-3 bg-card rounded-xl">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-lg bg-red-100 flex items-center justify-center"><AlertCircle className="w-5 h-5 text-red-600" /></div>
                    <span className="font-medium text-text">Alertas</span>
                  </div>
                  <span className="text-xl font-bold text-text">{stats?.alertas ?? 0}</span>
                </div>
              </div>
            </div>
            <div className="lg:col-span-2 card">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-semibold text-text">Atividade Recente</h2>
              </div>
              <div className="space-y-4 text-center py-8 text-gray text-sm">
                <Clock className="w-10 h-10 mx-auto text-gray-300" />
                <p>Atividades recentes aparecerão aqui.</p>
              </div>
            </div>
          </div>
        </>
      ) : (
        /* ESG Tab */
        esgLoading ? (
          <div className="flex items-center justify-center h-48"><Loader2 className="w-8 h-8 animate-spin" style={{ color: '#1A7A4C' }} /></div>
        ) : esgData ? (
          <>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="card border-l-4" style={{ borderLeftColor: '#1A7A4C' }}>
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{ backgroundColor: '#1A7A4C20' }}>
                    <Leaf className="w-5 h-5" style={{ color: '#1A7A4C' }} />
                  </div>
                  <div>
                    <p className="text-sm text-gray">Preventivas</p>
                    <p className="text-2xl font-bold" style={{ color: '#1A7A4C' }}>{esgData.pct_preventivas}%</p>
                    <p className="text-xs text-gray">{esgData.total_preventivas} demandas</p>
                  </div>
                </div>
              </div>
              <div className="card border-l-4 border-l-amber-500">
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg bg-amber-50 flex items-center justify-center">
                    <AlertCircle className="w-5 h-5 text-amber-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray">Corretivas</p>
                    <p className="text-2xl font-bold text-amber-600">{esgData.pct_corretivas}%</p>
                    <p className="text-xs text-gray">{esgData.total_corretivas} demandas</p>
                  </div>
                </div>
              </div>
              <div className="card border-l-4 border-l-red-500">
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center">
                    <AlertCircle className="w-5 h-5 text-red-600" />
                  </div>
                  <div>
                    <p className="text-sm text-gray">Emergenciais</p>
                    <p className="text-2xl font-bold text-red-600">{esgData.pct_emergenciais}%</p>
                    <p className="text-xs text-gray">{esgData.total_emergenciais} demandas</p>
                  </div>
                </div>
              </div>
              <div className="card border-l-4" style={{ borderLeftColor: '#1A7A4C' }}>
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{ backgroundColor: '#1A7A4C20' }}>
                    <Shield className="w-5 h-5" style={{ color: '#1A7A4C' }} />
                  </div>
                  <div>
                    <p className="text-sm text-gray">Fornecedores ESG+</p>
                    <p className="text-2xl font-bold" style={{ color: '#1A7A4C' }}>{esgData.pct_fornecedores_esg_bom}%</p>
                    <p className="text-xs text-gray">{esgData.fornecedores_esg_intermediario_avancado}/{esgData.total_fornecedores}</p>
                  </div>
                </div>
              </div>
            </div>
            <div className="grid lg:grid-cols-2 gap-6">
              <div className="card">
                <h2 className="text-lg font-semibold text-text mb-4">Tipo de Manutenção</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={manutencaoPieData} cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={4} dataKey="value">
                        {manutencaoPieData.map((entry: any, index: number) => (<Cell key={`cell-${index}`} fill={entry.color} />))}
                      </Pie>
                      <Legend verticalAlign="bottom" iconType="circle" iconSize={8} formatter={(value) => <span className="text-sm text-gray">{value}</span>} />
                      <Tooltip />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>
              <div className="card">
                <h2 className="text-lg font-semibold text-text mb-4">Evolução Manutenção Preventiva</h2>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={esgData.evolucao_preventiva}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#E0E0E0" vertical={false} />
                      <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#757575', fontSize: 12 }} />
                      <YAxis axisLine={false} tickLine={false} tick={{ fill: '#757575', fontSize: 12 }} />
                      <Tooltip />
                      <Bar dataKey="preventivas" fill="#1A7A4C" radius={[4, 4, 0, 0]} name="Preventivas" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
            </div>
            <div className="card">
              <div className="flex items-center gap-2 mb-4">
                <AlertCircle className="w-5 h-5 text-red-500" />
                <h2 className="text-lg font-semibold text-text">Demandas com Alto Impacto Ambiental</h2>
                <span className="badge badge-error">{esgData.demandas_alto_impacto_count}</span>
              </div>
              {esgData.demandas_alto_impacto.length === 0 ? (
                <p className="text-gray text-sm">Nenhuma demanda com alto impacto ambiental.</p>
              ) : (
                <div className="space-y-2">
                  {esgData.demandas_alto_impacto.map((d: any) => (
                    <div key={d.id} className="flex items-center gap-3 p-3 rounded-lg bg-red-50">
                      <FileText className="w-5 h-5 text-red-500" />
                      <div className="flex-1">
                        <p className="text-sm font-medium text-text">{d.numero ? `#${d.numero} - ` : ''}{d.titulo}</p>
                      </div>
                      <span className="badge badge-error text-xs">{d.status}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
            {esgData.fornecedores_esg_basico > 0 && (
              <div className="card border-l-4 border-l-amber-500 bg-amber-50">
                <div className="flex items-center gap-3">
                  <AlertCircle className="w-6 h-6 text-amber-600" />
                  <div>
                    <p className="font-semibold text-text">Atenção: Fornecedores ESG Básico</p>
                    <p className="text-sm text-gray">{esgData.fornecedores_esg_basico} fornecedor(es) com classificação ESG Básico.</p>
                  </div>
                </div>
              </div>
            )}
          </>
        ) : (
          <div className="card text-center py-12">
            <Leaf className="w-16 h-16 mx-auto mb-4" style={{ color: '#1A7A4C20' }} />
            <p className="text-gray">Dados ESG não disponíveis.</p>
          </div>
        )
      )}

      {/* Drill-down Modal */}
      {drillModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4" style={{ zIndex: 9999 }}>
          <div className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl animate-fade-in max-h-[85vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-6 border-b border-border bg-gradient-to-r from-primary to-accent rounded-t-2xl">
              <h2 className="text-xl font-semibold text-white">{drillTitle}</h2>
              <button onClick={() => setDrillModal(false)} className="p-2 rounded-lg hover:bg-white/20 text-white">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-6 overflow-y-auto flex-1">
              {drillLoading ? (
                <div className="flex items-center justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-primary" /></div>
              ) : drillData.length === 0 ? (
                <p className="text-center text-gray py-8">Nenhuma demanda encontrada.</p>
              ) : (
                <div className="space-y-3">
                  {drillData.map((d: any) => (
                    <div key={d.id} className="flex items-center gap-4 p-4 rounded-xl border border-border hover:bg-gray-50 transition-colors">
                      <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                        <FileText className="w-5 h-5 text-primary" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-text">{d.numero ? `#${d.numero} - ` : ''}{d.titulo}</p>
                        <div className="flex items-center gap-3 mt-1 text-xs text-gray">
                          <span>{d.categoria}</span>
                          <span>·</span>
                          <span>{d.data ? new Date(d.data).toLocaleDateString('pt-BR') : '-'}</span>
                        </div>
                      </div>
                      <div className="text-right flex-shrink-0">
                        <span className="badge badge-info text-xs">{d.status}</span>
                        {d.valor_estimado != null && (
                          <p className="text-sm font-medium text-text mt-1">{formatCurrency(d.valor_estimado)}</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
