'use client'

import { useState, type FormEvent } from 'react'
import { Loader2, Wand2, AlertCircle, CheckCircle2 } from 'lucide-react'

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  CardFooter,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import {
  maskAmount,
  maskCPFCNPJ,
  maskPhone,
  parseAmount,
} from '@/lib/format'
import { BoletoCard, type BoletoData } from './boleto-card'

interface BoletoCriarResponse {
  success: boolean
  transaction_id?: string
  payment_id?: string
  amount?: number
  tax?: number
  tax_percent?: number
  net_amount?: number
  barcode?: string
  due_date?: string
  acquirente?: string
  payment_method?: string
  status?: string
  status_text?: string
  message?: string
  warning?: string
  error?: string
  code?: string
  localId?: string
}

export function BoletosGerarTab() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [document, setDocument] = useState('')
  const [phone, setPhone] = useState('')
  const [amount, setAmount] = useState('')
  const [description, setDescription] = useState('')
  const [webhookUrl, setWebhookUrl] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [warning, setWarning] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [generated, setGenerated] = useState<BoletoData | null>(null)

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setError(null)
    setWarning(null)
    setSuccess(null)
    setGenerated(null)

    const amountNum = parseAmount(amount)
    if (amountNum === null || amountNum < 1) {
      setError('Informe um valor válido (mínimo R$ 1,00; recomendado R$ 5,00 para evitar rejeição por taxa mínima da adquirente).')
      return
    }
    if (!name.trim()) {
      setError('Informe o nome do pagador.')
      return
    }
    if (!email.trim() || !email.includes('@')) {
      setError('Informe um e-mail válido do pagador.')
      return
    }
    const docDigits = document.replace(/\D/g, '')
    if (![11, 14].includes(docDigits.length)) {
      setError('Informe um CPF (11 dígitos) ou CNPJ (14 dígitos) válido.')
      return
    }

    setLoading(true)
    try {
      const response = await fetch('/api/boleto/criar', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          amount: amountNum,
          customer: {
            name: name.trim(),
            email: email.trim(),
            document: docDigits,
            phone: phone || undefined,
          },
          description: description || undefined,
          webhookUrl: webhookUrl || undefined,
        }),
      })
      const data: BoletoCriarResponse = await response.json()

      if (!data.success) {
        setError(
          data.error ||
            data.message ||
            'Não foi possível gerar o boleto. Tente novamente.',
        )
        return
      }

      if (data.warning) setWarning(data.warning)

      setSuccess(
        `Boleto gerado com sucesso! ${data.message || ''}`.trim(),
      )
      setGenerated({
        transactionId: data.transaction_id!,
        paymentId: data.payment_id || null,
        amount: data.amount ?? amountNum,
        tax: data.tax ?? null,
        taxPercent: data.tax_percent ?? null,
        netAmount: data.net_amount ?? null,
        barcode: data.barcode ?? null,
        dueDate: data.due_date ?? null,
        acquirente: data.acquirente ?? null,
        paymentMethod: data.payment_method || 'BOLETO',
        status: data.status || 'PENDING',
        statusText: data.status_text ?? null,
        customerName: name.trim(),
        customerEmail: email.trim(),
        customerDocument: docDigits,
        customerPhone: phone || null,
        description: description || null,
        confirmedAt: null,
        createdAt: new Date().toISOString(),
      })

      // Limpa os campos de entrada
      setName('')
      setEmail('')
      setDocument('')
      setPhone('')
      setAmount('')
      setDescription('')
      setWebhookUrl('')
    } catch (err) {
      setError(
        err instanceof Error
          ? `Erro de comunicação: ${err.message}`
          : 'Erro de comunicação com o servidor.',
      )
    } finally {
      setLoading(false)
    }
  }

  function handleReset() {
    setGenerated(null)
    setSuccess(null)
    setWarning(null)
    setError(null)
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <Card className="lg:sticky lg:top-6 h-fit">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Wand2 className="size-5 text-emerald-600" />
            Gerar novo boleto
          </CardTitle>
          <CardDescription>
            Preencha os dados do pagador e o valor. O boleto será emitido via
            Dust Payments em tempo real.
          </CardDescription>
        </CardHeader>
        <form onSubmit={handleSubmit}>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field label="Valor (R$) *">
                <Input
                  inputMode="decimal"
                  placeholder="0,00"
                  value={amount}
                  onChange={(e) => setAmount(maskAmount(e.target.value))}
                  required
                />
              </Field>
              <Field label="Telefone (opcional)">
                <Input
                  inputMode="tel"
                  placeholder="(11) 99999-9999"
                  value={phone}
                  onChange={(e) => setPhone(maskPhone(e.target.value))}
                />
              </Field>
            </div>

            <Field label="Nome do pagador *">
              <Input
                placeholder="Ex.: Maria Silva"
                value={name}
                onChange={(e) => setName(e.target.value)}
                maxLength={100}
                required
              />
            </Field>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Field label="E-mail do pagador *">
                <Input
                  type="email"
                  placeholder="pagador@email.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </Field>
              <Field label="CPF / CNPJ *">
                <Input
                  inputMode="numeric"
                  placeholder="000.000.000-00"
                  value={document}
                  onChange={(e) => setDocument(maskCPFCNPJ(e.target.value))}
                  required
                />
              </Field>
            </div>

            <Field label="Descrição (opcional)">
              <Textarea
                placeholder="Ex.: Pedido 4471, mensalidade, serviço prestado…"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                maxLength={200}
                rows={2}
              />
              <p className="text-xs text-muted-foreground text-right mt-1">
                {description.length}/200
              </p>
            </Field>

            <Field label="Webhook URL (opcional)">
              <Input
                type="url"
                placeholder="https://seusite.com/webhook"
                value={webhookUrl}
                onChange={(e) => setWebhookUrl(e.target.value)}
              />
              <p className="text-xs text-muted-foreground mt-1">
                Se vazio, usa o webhook padrão do DustPay.
              </p>
            </Field>

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

            {warning ? (
              <Alert>
                <AlertCircle className="size-4" />
                <AlertTitle>Aviso</AlertTitle>
                <AlertDescription>{warning}</AlertDescription>
              </Alert>
            ) : null}

            {success ? (
              <Alert className="border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200">
                <CheckCircle2 className="size-4" />
                <AlertTitle>Sucesso</AlertTitle>
                <AlertDescription>{success}</AlertDescription>
              </Alert>
            ) : null}
          </CardContent>
          <CardFooter className="flex flex-col sm:flex-row gap-2 sm:justify-end">
            {generated ? (
              <Button
                type="button"
                variant="outline"
                onClick={handleReset}
                disabled={loading}
              >
                Gerar outro
              </Button>
            ) : null}
            <Button
              type="submit"
              disabled={loading}
              className="gap-2 bg-emerald-600 hover:bg-emerald-700 text-white w-full sm:w-auto"
            >
              {loading ? (
                <Loader2 className="size-4 animate-spin" />
              ) : (
                <Wand2 className="size-4" />
              )}
              {loading ? 'Gerando…' : 'Gerar boleto'}
            </Button>
          </CardFooter>
        </form>
      </Card>

      <div className="space-y-4">
        {generated ? (
          <BoletoCard boleto={generated} />
        ) : (
          <Card className="h-full min-h-[280px] flex items-center justify-center border-dashed">
            <CardContent 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">
                <Wand2 className="size-6 text-muted-foreground" />
              </div>
              <div>
                <p className="font-medium">Nenhum boleto gerado nesta sessão</p>
                <p className="text-sm text-muted-foreground mt-1 max-w-xs">
                  Preencha o formulário ao lado e clique em
                  <span className="font-medium"> Gerar boleto</span> para
                  visualizar a linha digitável aqui.
                </p>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}

function Field({
  label,
  children,
}: {
  label: string
  children: React.ReactNode
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-sm font-medium">{label}</Label>
      {children}
    </div>
  )
}
