// T600.28 (IIBB) — TiposDeIibbPage
// Página principal de gestión de Ingresos Brutos
import { useState, useCallback } from 'react'
import { TriangleAlert, PlusCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { IngresosBrutosTable } from '../components/IngresosBrutosTable'
import { IngresosBrutosFormModal } from '../components/IngresosBrutosFormModal'
import { NuevaVigenciaIibbModal } from '../components/NuevaVigenciaIibbModal'
import { useIngresosBrutosList } from '../hooks/useIngresosBrutos'
import {
  PROVINCIAS,
  PROVINCIA_DISPLAY,
} from '../types/ingresosBrutos.types'
import type { IngresosBrutos, IngresosBrutosFilter, ProvinciaArgentina } from '../types/ingresosBrutos.types'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

export function TiposDeIibbPage() {
  const [page, setPage] = useState(1)
  const [provinciaFilter, setProvinciaFilter] = useState<ProvinciaArgentina | undefined>(undefined)
  const [activoFilter, setActivoFilter] = useState<boolean | undefined>(undefined)

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

  const filters: IngresosBrutosFilter = {
    page,
    pageSize: 20,
    ...(provinciaFilter !== undefined ? { provincia: provinciaFilter } : {}),
    ...(activoFilter !== undefined ? { activo: activoFilter } : {}),
  }

  const { data, isLoading } = useIngresosBrutosList(filters)

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

  const handleNuevaVersion = useCallback((row: IngresosBrutos) => {
    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 */}
      <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 alícuota.
        </span>
      </div>

      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Ingresos Brutos</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">
        <Select
          value={provinciaFilter ?? '__all__'}
          onValueChange={(v) => {
            setProvinciaFilter(v === '__all__' ? undefined : (v as ProvinciaArgentina))
            setPage(1)
          }}
        >
          <SelectTrigger className="max-w-xs" aria-label="Filtrar por provincia">
            <SelectValue placeholder="Filtrar por provincia..." />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="__all__">Todas las provincias</SelectItem>
            {PROVINCIAS.map((p) => (
              <SelectItem key={p} value={p}>
                {PROVINCIA_DISPLAY[p]}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <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>
      ) : (
        <IngresosBrutosTable
          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} registro${data.total !== 1 ? 's' : ''}` : ''}
        </span>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={!hasPrev}
            onClick={() => setPage((p) => p - 1)}
            aria-label="Anterior"
          >
            Anterior
          </Button>
          <span className="flex items-center px-2 text-sm text-muted-foreground">
            {page} / {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={!hasNext}
            onClick={() => setPage((p) => p + 1)}
            aria-label="Siguiente"
          >
            Siguiente
          </Button>
        </div>
      </div>

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

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