'use client'

import { useState } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { AlertTriangle, Eye, EyeOff } from 'lucide-react'
import { cn } from '@/lib/utils'

interface ConfirmActionModalProps {
  open: boolean
  onClose: () => void
  onConfirm: () => void | Promise<void>
  title: string
  description: string
  objectName: string
  changeSummary: string
  confirmLabel?: string
  variant?: 'default' | 'destructive'
  loading?: boolean
}

export function ConfirmActionModal({
  open,
  onClose,
  onConfirm,
  title,
  description,
  objectName,
  changeSummary,
  confirmLabel = 'Confirmar',
  variant = 'default',
  loading = false,
}: ConfirmActionModalProps) {
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')

  // Senha demo: qualquer valor com 4+ chars
  const DEMO_PASSWORD = 'senha123'

  async function handleConfirm() {
    if (!password.trim()) {
      setError('Digite sua senha para confirmar')
      return
    }
    if (password !== DEMO_PASSWORD) {
      setError('Senha incorreta. (Demo: senha123)')
      return
    }
    setError('')
    await onConfirm()
    setPassword('')
  }

  function handleClose() {
    setPassword('')
    setError('')
    onClose()
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertTriangle
              className={cn(
                'w-5 h-5',
                variant === 'destructive' ? 'text-destructive' : 'text-yellow-500',
              )}
            />
            {title}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">{description}</p>

          {/* Objeto afetado */}
          <div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2">
            <div>
              <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                Objeto afetado
              </span>
              <p className="text-sm font-medium text-foreground mt-0.5">{objectName}</p>
            </div>
            <div>
              <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                Resumo da alteração
              </span>
              <p className="text-sm text-foreground mt-0.5">{changeSummary}</p>
            </div>
          </div>

          {/* Campo senha */}
          <div className="space-y-2">
            <Label htmlFor="confirm-password" className="text-sm font-medium">
              Senha do portal
            </Label>
            <div className="relative">
              <Input
                id="confirm-password"
                type={showPassword ? 'text' : 'password'}
                placeholder="Digite sua senha para confirmar"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value)
                  setError('')
                }}
                onKeyDown={(e) => e.key === 'Enter' && handleConfirm()}
                className={cn(error && 'border-destructive')}
                autoFocus
              />
              <button
                type="button"
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                onClick={() => setShowPassword(!showPassword)}
                tabIndex={-1}
              >
                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
            {error && <p className="text-xs text-destructive">{error}</p>}
            <p className="text-xs text-muted-foreground">
              Esta ação ficará registrada na auditoria do sistema.
            </p>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleClose} disabled={loading}>
            Cancelar
          </Button>
          <Button
            variant={variant === 'destructive' ? 'destructive' : 'default'}
            onClick={handleConfirm}
            disabled={loading || !password}
          >
            {loading ? 'Processando...' : confirmLabel}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
