'use client'

import { useCallback, useEffect, useState } from 'react'
import {
  History,
  Loader2,
  AlertCircle,
  RefreshCw,
  Search,
  Inbox,
} from 'lucide-react'

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { BoletoCard, type BoletoData } from './boleto-card'
import {
  formatBRL,
  formatDateTimeBR,
  statusLabel,
} from '@/lib/format'

interface ListResponse {
  success: boolean
  items: BoletoData[]
  pagination: {
    total: number
    limit: number
    offset: number
    returned: number
  }
  error?: string
  code?: string
}

const STATUS_FILTERS: { value: string; label: string }[] = [
  { value: 'ALL', label: 'Todos' },
  { value: 'PENDING', label: 'Pendentes' },
  { value: 'PAID', label: 'Pagos' },
  { value: 'CANCELLED', label: 'Cancelados' },
  { value: 'PROCESSING', label: 'Processando' },
  { value: 'REVERSED', label: 'Estornados' },
  { value: 'FAILED', label: 'Falhou' },
]

export function BoletosHistoricoTab() {
  const [items, setItems] = useState<BoletoData[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [total, setTotal] = useState(0)
  const [offset, setOffset] = useState(0)
  const [limit] = useState(10)
  const [status, setStatus] = useState('ALL')
  const [email, setEmail] = useState('')
  const [document, setDocument] = useState('')
  const [selected, setSelected] = useState<BoletoData | null>(null)

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params = new URLSearchParams({
        limit: String(limit),
        offset: String(offset),
      })
      if (status !== 'ALL') params.set('status', status)
      if (email.trim()) params.set('email', email.trim())
      if (document.trim()) params.set('document', document.trim())
      const resp = await fetch(`/api/boleto/listar?${params.toString()}`)
      const data: ListResponse = await resp.json()
      if (!data.success) {
        setError(data.error || 'Erro ao carregar histórico.')
        return
      }
      setItems(data.items)
      setTotal(data.pagination.total)
    } catch (err) {
      setError(
        err instanceof Error
          ? `Erro de comunicação: ${err.message}`
          : 'Erro de comunicação com o servidor.',
      )
    } finally {
      setLoading(false)
    }
  }, [limit, offset, status, email, document])

  useEffect(() => {
    void load()
  }, [load])

  async function handleSyncOne(txId: string) {
    try {
      const resp = await fetch(
        `/api/boleto/status?id=${encodeURIComponent(txId)}&sync=true`,
      )
      await resp.json()
      await load()
      // Atualiza também o selecionado
      if (selected?.transactionId === txId) {
        const updated = items.find((i) => i.transactionId === txId)
        if (updated) setSelected(updated)
      }
    } catch {
      // silent
    }
  }

  const hasMore = offset + limit < total
  const canPrev = offset > 0

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <History className="size-5 text-emerald-600" />
            Histórico de boletos
          </CardTitle>
          <CardDescription>
            {total > 0
              ? `${total} boleto(s) registrado(s) no banco local.`
              : 'Boletos gerados aparecem aqui automaticamente.'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-3 mb-4">
            <div className="space-y-1.5">
              <Label className="text-xs">Status</Label>
              <Select value={status} onValueChange={setStatus}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Filtrar por status" />
                </SelectTrigger>
                <SelectContent>
                  {STATUS_FILTERS.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">E-mail do pagador</Label>
              <Input
                placeholder="pagador@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">CPF / CNPJ</Label>
              <Input
                placeholder="apenas números"
                value={document}
                onChange={(e) => setDocument(e.target.value)}
              />
            </div>
            <div className="flex items-end gap-2">
              <Button
                type="button"
                onClick={() => {
                  setOffset(0)
                  void load()
                }}
                disabled={loading}
                className="gap-2 flex-1 bg-emerald-600 hover:bg-emerald-700 text-white"
              >
                {loading ? (
                  <Loader2 className="size-4 animate-spin" />
                ) : (
                  <Search className="size-4" />
                )}
                Filtrar
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => void load()}
                disabled={loading}
                size="icon"
                title="Recarregar"
              >
                <RefreshCw
                  className={`size-4 ${loading ? 'animate-spin' : ''}`}
                />
              </Button>
            </div>
          </div>

          {error ? (
            <Alert variant="destructive" className="mb-4">
              <AlertCircle className="size-4" />
              <AlertTitle>Erro</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          ) : null}

          {loading && items.length === 0 ? (
            <div className="flex items-center justify-center py-10">
              <Loader2 className="size-6 animate-spin text-emerald-600" />
            </div>
          ) : items.length === 0 ? (
            <div className="flex flex-col items-center text-center gap-3 py-10">
              <div className="size-12 rounded-full bg-muted flex items-center justify-center">
                <Inbox className="size-6 text-muted-foreground" />
              </div>
              <div>
                <p className="font-medium">Nenhum boleto encontrado</p>
                <p className="text-sm text-muted-foreground mt-1 max-w-sm">
                  Ajuste os filtros ou gere um novo boleto na aba
                  <span className="font-medium"> Gerar</span>.
                </p>
              </div>
            </div>
          ) : (
            <div className="rounded-md border overflow-hidden">
              <div className="hidden sm:grid grid-cols-[1fr_auto_auto_auto_auto] gap-3 bg-muted/50 px-3 py-2 text-xs font-semibold text-muted-foreground uppercase">
                <span>Pagador</span>
                <span className="text-right">Valor</span>
                <span className="text-center">Status</span>
                <span className="text-right">Criado</span>
                <span className="w-8"></span>
              </div>
              <ul className="divide-y">
                {items.map((item) => (
                  <li
                    key={item.transactionId}
                    className="grid grid-cols-1 sm:grid-cols-[1fr_auto_auto_auto_auto] gap-2 sm:gap-3 px-3 py-3 hover:bg-muted/30 cursor-pointer"
                    onClick={() =>
                      setSelected(selected?.transactionId === item.transactionId ? null : item)
                    }
                  >
                    <div className="min-w-0">
                      <p className="font-medium truncate">{item.customerName}</p>
                      <p className="text-xs text-muted-foreground truncate font-mono">
                        {item.transactionId}
                      </p>
                    </div>
                    <div className="text-right font-mono text-sm">
                      {formatBRL(item.amount)}
                    </div>
                    <div className="flex justify-start sm:justify-center">
                      <Badge variant="outline" className="font-mono text-xs">
                        {statusLabel(item.status)}
                      </Badge>
                    </div>
                    <div className="text-right text-xs text-muted-foreground">
                      {formatDateTimeBR(
                        item.createdAt
                          ? typeof item.createdAt === 'string'
                            ? item.createdAt
                            : item.createdAt.toISOString()
                          : null,
                      )}
                    </div>
                    <div className="w-8 flex items-center justify-end">
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2 text-xs"
                        onClick={(e) => {
                          e.stopPropagation()
                          void handleSyncOne(item.transactionId)
                        }}
                        title="Sincronizar com API"
                      >
                        <RefreshCw className="size-3.5" />
                      </Button>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {(canPrev || hasMore) && items.length > 0 ? (
            <div className="flex items-center justify-between mt-4">
              <Button
                type="button"
                variant="outline"
                size="sm"
                disabled={!canPrev || loading}
                onClick={() => setOffset(Math.max(0, offset - limit))}
              >
                Anterior
              </Button>
              <span className="text-xs text-muted-foreground">
                {offset + 1}–{Math.min(offset + limit, total)} de {total}
              </span>
              <Button
                type="button"
                variant="outline"
                size="sm"
                disabled={!hasMore || loading}
                onClick={() => setOffset(offset + limit)}
              >
                Próximo
              </Button>
            </div>
          ) : null}
        </CardContent>
      </Card>

      {selected ? (
        <BoletoCard
          boleto={selected}
          onSync={() => handleSyncOne(selected.transactionId)}
          syncing={loading}
        />
      ) : null}
    </div>
  )
}
