// T600.27 (IIBB) — HistorialCadenaIibbTooltip
// Espejo de HistorialCadenaTooltip para IIBB
import { useState } from 'react'
import { History } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { useHistorialIngresosBrutos } from '../hooks/useIngresosBrutos'

interface HistorialCadenaIibbTooltipProps {
  id: number
}

function formatVigencia(desde: string, hasta: string | null): string {
  return hasta ? `${desde} → ${hasta}` : `${desde} → ahora`
}

export function HistorialCadenaIibbTooltip({ id }: HistorialCadenaIibbTooltipProps) {
  const [enabled, setEnabled] = useState(false)

  const { data: historial, isLoading } = useHistorialIngresosBrutos(id, enabled)

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          aria-label="historial"
          onMouseEnter={() => setEnabled(true)}
          className="h-7 w-7 p-0"
        >
          <History className="h-4 w-4 text-muted-foreground" />
        </Button>
      </TooltipTrigger>
      <TooltipContent side="left" className="max-w-sm">
        {!enabled || isLoading ? (
          <span className="text-xs text-muted-foreground">Cargando historial...</span>
        ) : !historial || historial.length === 0 ? (
          <span className="text-xs text-muted-foreground">Sin historial</span>
        ) : (
          <div className="space-y-1">
            <p className="text-xs font-medium mb-1">Historial de versiones</p>
            {historial.map((entry, idx) => (
              <div key={entry.id} className="text-xs">
                <span className="font-mono font-medium">
                  v{idx + 1} ({entry.alicuota}%)
                </span>
                <span className="text-muted-foreground ml-1">
                  [{formatVigencia(entry.vigenciaDesde, entry.vigenciaHasta)}]
                </span>
                {idx < historial.length - 1 && (
                  <span className="text-muted-foreground"> →</span>
                )}
              </div>
            ))}
          </div>
        )}
      </TooltipContent>
    </Tooltip>
  )
}
