// T600.8 — TiposDeIvaPage
// Página principal de gestión de Tipos de IVA
import { useState, useCallback } from 'react'
import { TriangleAlert, PlusCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { TipoDeIvaTable } from '../components/TipoDeIvaTable'
import { TipoDeIvaFormModal } from '../components/TipoDeIvaFormModal'
import { NuevaVigenciaModal } from '../components/NuevaVigenciaModal'
import { useTiposDeIvaList } from '../hooks/useTiposDeIva'
import type { TipoDeIva, TipoDeIvaFilter } from '../types/tipoDeIva.types'
import { Button as Btn } from '@/components/ui/button'

export function TiposDeIvaPage() {
  const [page, setPage] = useState(1)
  const [codigoFilter, setCodigoFilter] = useState('')
  const [activoFilter, setActivoFilter] = useState<boolean | undefined>(undefined)

  // Estado de modales
  const [editItem, setEditItem] = useState<TipoDeIva | null>(null)
  const [editOpen, setEditOpen] = useState(false)
  const [nuevaVigenciaItem, setNuevaVigenciaItem] = useState<TipoDeIva | null>(null)
  const [nuevaVigenciaOpen, setNuevaVigenciaOpen] = useState(false)

  const filters: TipoDeIvaFilter = {
    page,
    pageSize: 20,
    ...(codigoFilter ? { codigo: codigoFilter } : {}),
    ...(activoFilter !== undefined ? { activo: activoFilter } : {}),
  }

  const { data, isLoading } = useTiposDeIvaList(filters)

  const handleEdit = useCallback((row: TipoDeIva) => {
    setEditItem(row)
    setEditOpen(true)
  }, [])

  const handleNuevaVersion = useCallback((row: TipoDeIva) => {
    setNuevaVigenciaItem(row)
    setNuevaVigenciaOpen(true)
  }, [])

  const totalPages = data ? Math.ceil(data.total / (data.pageSize || 20)) : 1
  const hasPrev = page > 1
  const hasNext = page < totalPages

  return (
    <div className="space-y-4">
      {/* Banner de advertencia global — visible al montar [REQ-UI-005] */}
      <div
        className="flex items-start gap-3 rounded-md border px-4 py-3 text-sm"
        role="alert"
        style={{
          backgroundColor: 'var(--warning-bg)',
          borderColor: 'var(--warning-border)',
          color: 'var(--warning-foreground)',
        }}
      >
        <TriangleAlert className="h-4 w-4 mt-0.5 shrink-0" style={{ color: 'var(--warning)' }} />
        <span>
          Los cambios de alícuota afectan presupuestos en curso. Usá{' '}
          <strong>Nueva vigencia</strong> para versionar cambios de porcentaje.
        </span>
      </div>

      {/* Header con título y botón crear */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Tipos de IVA</h1>
        <Button
          size="sm"
          onClick={() => {
            setEditItem(null)
            setEditOpen(true)
          }}
          aria-label="crear nuevo"
        >
          <PlusCircle className="h-4 w-4 mr-2" />
          Crear nuevo
        </Button>
      </div>

      {/* Filtros */}
      <div className="flex items-center gap-3 flex-wrap">
        <Input
          placeholder="Filtrar por código..."
          value={codigoFilter}
          onChange={(e) => {
            setCodigoFilter(e.target.value)
            setPage(1)
          }}
          className="max-w-xs"
          aria-label="Filtrar por código"
        />

        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">Estado:</span>
          <Button
            variant={activoFilter === undefined ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => { setActivoFilter(undefined); setPage(1) }}
          >
            Todos
          </Button>
          <Button
            variant={activoFilter === true ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => { setActivoFilter(true); setPage(1) }}
          >
            Activos
          </Button>
          <Button
            variant={activoFilter === false ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => { setActivoFilter(false); setPage(1) }}
          >
            Inactivos
          </Button>
        </div>
      </div>

      {/* Tabla */}
      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full rounded-md" />
          ))}
        </div>
      ) : (
        <TipoDeIvaTable
          rows={data?.items ?? []}
          onEdit={handleEdit}
          onNuevaVersion={handleNuevaVersion}
        />
      )}

      {/* Paginación */}
      <div className="flex items-center justify-between pt-2">
        <span className="text-sm text-muted-foreground">
          {data ? `${data.total} tipo${data.total !== 1 ? 's' : ''} de IVA` : ''}
        </span>
        <div className="flex gap-2">
          <Btn
            variant="outline"
            size="sm"
            disabled={!hasPrev}
            onClick={() => setPage((p) => p - 1)}
            aria-label="Anterior"
          >
            Anterior
          </Btn>
          <span className="flex items-center px-2 text-sm text-muted-foreground">
            {page} / {totalPages}
          </span>
          <Btn
            variant="outline"
            size="sm"
            disabled={!hasNext}
            onClick={() => setPage((p) => p + 1)}
            aria-label="Siguiente"
          >
            Siguiente
          </Btn>
        </div>
      </div>

      {/* Modal Crear/Editar */}
      <TipoDeIvaFormModal
        open={editOpen}
        item={editItem}
        onClose={() => setEditOpen(false)}
        onSuccess={() => setEditOpen(false)}
      />

      {/* Modal Nueva Vigencia */}
      <NuevaVigenciaModal
        open={nuevaVigenciaOpen}
        item={nuevaVigenciaItem}
        onClose={() => setNuevaVigenciaOpen(false)}
        onSuccess={() => setNuevaVigenciaOpen(false)}
      />
    </div>
  )
}
