import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { CanPerform } from '@/components/auth/CanPerform'
import { useChargeableCharConfigs } from '../hooks/useChargeableCharConfigs'
import { useDeactivateChargeableCharConfig } from '../hooks/useDeactivateChargeableCharConfig'
import { ChargeableCharsTable } from '../components/ChargeableCharsTable'
import { ChargeableCharFormDialog } from '../components/ChargeableCharFormDialog'
import { CopyToAllProductTypesDialog } from '../components/CopyToAllProductTypesDialog'
import type { ChargeableCharConfig } from '../types'

const PERMISSION = 'tasacion:caracteres_especiales:gestionar'
const DEFAULT_PAGE_SIZE = 20

export function ChargeableCharsPage() {
  // ── Filter / pagination state ──────────────────────────────────────────────
  const [page, setPage] = useState(1)
  const [selectedProductTypeId, setSelectedProductTypeId] = useState<number | undefined>(undefined)
  const [activeOnly, setActiveOnly] = useState(true)

  // ── Dialog state ──────────────────────────────────────────────────────────
  const [createOpen, setCreateOpen] = useState(false)
  const [scheduleConfig, setScheduleConfig] = useState<ChargeableCharConfig | null>(null)
  const [deactivateId, setDeactivateId] = useState<number | null>(null)
  const [copyFromConfig, setCopyFromConfig] = useState<ChargeableCharConfig | null>(null)

  // ── Data ──────────────────────────────────────────────────────────────────
  const { data, isLoading } = useChargeableCharConfigs({
    productTypeId: selectedProductTypeId,
    activeOnly,
    page,
    pageSize: DEFAULT_PAGE_SIZE,
  })

  const deactivateMutation = useDeactivateChargeableCharConfig(deactivateId ?? 0)

  function handleDeactivate(config: ChargeableCharConfig) {
    setDeactivateId(config.id)
    // Trigger deactivation immediately (idempotent)
    deactivateMutation.mutate()
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">Caracteres Tasables</h1>
        <CanPerform permission={PERMISSION}>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCopyFromConfig(data?.items[0] ?? null)}
              disabled={!data?.items.length}
            >
              Copiar a todos los tipos
            </Button>
            <Button size="sm" onClick={() => setCreateOpen(true)}>
              Nuevo carácter
            </Button>
          </div>
        </CanPerform>
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="h-12 w-full rounded-md bg-muted animate-pulse" />
          ))}
        </div>
      ) : (
        <ChargeableCharsTable
          configs={data?.items ?? []}
          total={data?.total ?? 0}
          page={page}
          pageSize={DEFAULT_PAGE_SIZE}
          onPageChange={setPage}
          productTypeId={selectedProductTypeId}
          activeOnly={activeOnly}
          onProductTypeChange={(v) => { setSelectedProductTypeId(v); setPage(1) }}
          onActiveOnlyChange={(v) => { setActiveOnly(v); setPage(1) }}
          onSchedulePrice={setScheduleConfig}
          onDeactivate={handleDeactivate}
        />
      )}

      {/* Create dialog */}
      <ChargeableCharFormDialog
        open={createOpen}
        mode="create"
        onOpenChange={setCreateOpen}
      />

      {/* Schedule price dialog */}
      <ChargeableCharFormDialog
        open={!!scheduleConfig}
        mode="schedulePrice"
        config={scheduleConfig ?? undefined}
        onOpenChange={(open) => { if (!open) setScheduleConfig(null) }}
      />

      {/* Copy to all product types dialog */}
      {copyFromConfig && (
        <CopyToAllProductTypesDialog
          open={!!copyFromConfig}
          onOpenChange={(open) => { if (!open) setCopyFromConfig(null) }}
          symbol={copyFromConfig.symbol}
          pricePerUnit={copyFromConfig.pricePerUnit}
          validFrom={copyFromConfig.validFrom}
          category={copyFromConfig.category}
        />
      )}
    </div>
  )
}
