'use client'

import { useState } from 'react'
import {
  Copy,
  Check,
  FileText,
  Receipt,
  Calendar,
  Hash,
  Banknote,
  RefreshCw,
} from 'lucide-react'

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import {
  formatBRL,
  formatBarcode,
  formatDateBR,
  formatDateTimeBR,
  formatCPF,
  statusLabel,
} from '@/lib/format'

export interface BoletoData {
  transactionId: string
  paymentId?: string | null
  amount: number
  tax?: number | null
  taxPercent?: number | null
  netAmount?: number | null
  barcode?: string | null
  dueDate?: string | Date | null
  acquirente?: string | null
  paymentMethod?: string | null
  status: string
  statusText?: string | null
  customerName: string
  customerEmail: string
  customerDocument: string
  customerPhone?: string | null
  description?: string | null
  confirmedAt?: string | Date | null
  createdAt?: string | Date | null
}

function toDateStr(value?: string | Date | null): string | null {
  if (!value) return null
  if (typeof value === 'string') return value
  return value.toISOString()
}

const STATUS_BADGE_CLASS: Record<string, string> = {
  PENDING:
    'bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-900/40 dark:text-amber-200 dark:border-amber-800',
  PAID:
    'bg-emerald-100 text-emerald-800 border-emerald-300 dark:bg-emerald-900/40 dark:text-emerald-200 dark:border-emerald-800',
  CANCELLED:
    'bg-rose-100 text-rose-800 border-rose-300 dark:bg-rose-900/40 dark:text-rose-200 dark:border-rose-800',
  REVERSED:
    'bg-purple-100 text-purple-800 border-purple-300 dark:bg-purple-900/40 dark:text-purple-200 dark:border-purple-800',
  FAILED:
    'bg-red-100 text-red-800 border-red-300 dark:bg-red-900/40 dark:text-red-200 dark:border-red-800',
  PROCESSING:
    'bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-900/40 dark:text-blue-200 dark:border-blue-800',
}

export function badgeClassForStatus(status?: string | null): string {
  if (!status) return ''
  return STATUS_BADGE_CLASS[status.toUpperCase()] || ''
}

export function BoletoCard({
  boleto,
  onSync,
  syncing,
}: {
  boleto: BoletoData
  onSync?: () => void
  syncing?: boolean
}) {
  const [copiedBarcode, setCopiedBarcode] = useState(false)
  const [copiedTx, setCopiedTx] = useState(false)

  async function copy(text: string, which: 'barcode' | 'tx') {
    try {
      await navigator.clipboard.writeText(text)
      if (which === 'barcode') {
        setCopiedBarcode(true)
        setTimeout(() => setCopiedBarcode(false), 2000)
      } else {
        setCopiedTx(true)
        setTimeout(() => setCopiedTx(false), 2000)
      }
    } catch {
      // ignore
    }
  }

  const dueDateStr = toDateStr(boleto.dueDate)
  const confirmedAtStr = toDateStr(boleto.confirmedAt)
  const createdAtStr = toDateStr(boleto.createdAt)

  return (
    <Card className="overflow-hidden border-2 border-emerald-200 dark:border-emerald-900/50 shadow-lg">
      <CardHeader className="bg-gradient-to-r from-emerald-50 to-emerald-50/0 dark:from-emerald-950/40 dark:to-transparent border-b">
        <div className="flex items-start justify-between gap-3 flex-wrap">
          <div className="flex items-center gap-3">
            <div className="size-10 rounded-lg bg-emerald-600 text-white flex items-center justify-center shadow">
              <Receipt className="size-5" />
            </div>
            <div>
              <CardTitle className="text-lg">Boleto gerado</CardTitle>
              <CardDescription className="text-xs font-mono break-all max-w-md">
                {boleto.transactionId}
              </CardDescription>
            </div>
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <Badge
              variant="outline"
              className={`border ${badgeClassForStatus(boleto.status)}`}
            >
              {statusLabel(boleto.status)}
            </Badge>
            {onSync ? (
              <Button
                size="sm"
                variant="outline"
                onClick={onSync}
                disabled={syncing}
                className="h-7 gap-1 text-xs"
              >
                <RefreshCw className={`size-3 ${syncing ? 'animate-spin' : ''}`} />
                {syncing ? 'Sincronizando…' : 'Atualizar status'}
              </Button>
            ) : null}
          </div>
        </div>
      </CardHeader>

      <CardContent className="pt-5 space-y-5">
        {/* Linha digitável */}
        {boleto.barcode ? (
          <div className="rounded-lg border-2 border-dashed border-emerald-300 dark:border-emerald-800 bg-emerald-50/50 dark:bg-emerald-950/20 p-4">
            <div className="flex items-center justify-between gap-2 mb-1">
              <span className="text-xs uppercase tracking-wide text-muted-foreground font-semibold flex items-center gap-1.5">
                <Hash className="size-3.5" />
                Linha digitável
              </span>
              <Button
                size="sm"
                variant="ghost"
                className="h-7 gap-1 text-xs"
                onClick={() => copy(boleto.barcode!, 'barcode')}
              >
                {copiedBarcode ? (
                  <Check className="size-3.5 text-emerald-600" />
                ) : (
                  <Copy className="size-3.5" />
                )}
                {copiedBarcode ? 'Copiado' : 'Copiar'}
              </Button>
            </div>
            <p className="font-mono text-base sm:text-lg tracking-wider break-all leading-relaxed">
              {formatBarcode(boleto.barcode)}
            </p>
          </div>
        ) : null}

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <InfoTile
            icon={<Banknote className="size-4" />}
            label="Valor"
            value={formatBRL(boleto.amount)}
            highlight
          />
          <InfoTile
            icon={<FileText className="size-4" />}
            label="Taxa"
            value={
              boleto.tax != null
                ? `${formatBRL(boleto.tax)}${
                    boleto.taxPercent != null
                      ? ` (${boleto.taxPercent}%)`
                      : ''
                  }`
                : '—'
            }
          />
          <InfoTile
            icon={<Banknote className="size-4" />}
            label="Líquido"
            value={formatBRL(boleto.netAmount)}
          />
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <InfoTile
            icon={<Calendar className="size-4" />}
            label="Vencimento"
            value={formatDateBR(dueDateStr)}
          />
          <InfoTile
            icon={<Calendar className="size-4" />}
            label="Pago em"
            value={confirmedAtStr ? formatDateTimeBR(confirmedAtStr) : '—'}
          />
          <InfoTile
            icon={<FileText className="size-4" />}
            label="Pagador"
            value={boleto.customerName}
            sub={
              boleto.customerDocument
                ? formatCPF(boleto.customerDocument)
                : undefined
            }
          />
          <InfoTile
            icon={<FileText className="size-4" />}
            label="E-mail"
            value={boleto.customerEmail}
          />
          <InfoTile
            icon={<FileText className="size-4" />}
            label="Adquirente"
            value={boleto.acquirente || '—'}
          />
          <InfoTile
            icon={<Calendar className="size-4" />}
            label="Criado em"
            value={createdAtStr ? formatDateTimeBR(createdAtStr) : '—'}
          />
        </div>

        {boleto.description ? (
          <>
            <Separator />
            <div className="text-sm">
              <span className="text-muted-foreground">Descrição: </span>
              <span className="font-medium">{boleto.description}</span>
            </div>
          </>
        ) : null}

        <Separator />

        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
          <span>Método:</span>
          <Badge variant="secondary" className="font-mono">
            {boleto.paymentMethod || 'BOLETO'}
          </Badge>
          {boleto.paymentId ? (
            <>
              <span>·</span>
              <span>Payment ID:</span>
              <span className="font-mono">{boleto.paymentId}</span>
              <Button
                size="sm"
                variant="ghost"
                className="h-6 px-2 text-xs"
                onClick={() => copy(boleto.transactionId, 'tx')}
              >
                {copiedTx ? (
                  <Check className="size-3 text-emerald-600" />
                ) : (
                  <Copy className="size-3" />
                )}
                {copiedTx ? 'Copiado' : 'Copiar TX'}
              </Button>
            </>
          ) : null}
        </div>
      </CardContent>
    </Card>
  )
}

function InfoTile({
  icon,
  label,
  value,
  sub,
  highlight,
}: {
  icon: React.ReactNode
  label: string
  value: string
  sub?: string
  highlight?: boolean
}) {
  return (
    <div
      className={`rounded-lg border p-3 ${
        highlight
          ? 'border-emerald-300 bg-emerald-50/60 dark:border-emerald-800 dark:bg-emerald-950/30'
          : 'border-border bg-muted/30'
      }`}
    >
      <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-1">
        {icon}
        <span className="uppercase tracking-wide font-semibold">{label}</span>
      </div>
      <div
        className={`font-medium ${highlight ? 'text-emerald-700 dark:text-emerald-300 text-lg' : ''}`}
      >
        {value}
      </div>
      {sub ? <div className="text-xs text-muted-foreground">{sub}</div> : null}
    </div>
  )
}
