import { useState } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { Copy, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertCircle } from 'lucide-react'
import { useResetUserPassword } from '../hooks/useResetUserPassword'

interface ResetPasswordModalProps {
  userId: number
}

type ModalState = 'idle' | 'confirming' | 'showing-password' | 'error'

export function ResetPasswordModal({ userId }: ResetPasswordModalProps) {
  const [open, setOpen] = useState(false)
  const [modalState, setModalState] = useState<ModalState>('idle')
  const [tempPassword, setTempPassword] = useState<string | null>(null)
  const [copyDone, setCopyDone] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)

  const { mutate, isPending } = useResetUserPassword()

  function handleOpen() {
    setModalState('confirming')
    setTempPassword(null)
    setCopyDone(false)
    setErrorMsg(null)
    setOpen(true)
  }

  function handleCancel() {
    setOpen(false)
    setModalState('idle')
  }

  function handleConfirm() {
    mutate(userId, {
      onSuccess: (data) => {
        setTempPassword(data.tempPassword)
        setModalState('showing-password')
      },
      onError: () => {
        setErrorMsg('Error al resetear la contraseña. Intentá de nuevo.')
        setModalState('error')
      },
    })
  }

  async function handleCopy() {
    if (tempPassword) {
      await navigator.clipboard.writeText(tempPassword)
      setCopyDone(true)
    }
  }

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Trigger asChild>
        <Button variant="outline" size="sm" onClick={handleOpen}>
          Resetear contraseña
        </Button>
      </Dialog.Trigger>

      <Dialog.Portal>
        <Dialog.Overlay className="fixed inset-0 bg-black/50 z-40" />
        <Dialog.Content
          className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-background border border-border rounded-lg shadow-xl p-6 z-50 w-full max-w-md space-y-4"
          aria-describedby="reset-pwd-desc"
        >
          <div className="flex items-center justify-between">
            <Dialog.Title className="text-base font-semibold">
              Resetear contraseña
            </Dialog.Title>
            <Dialog.Close asChild>
              <Button variant="ghost" size="sm" onClick={handleCancel} aria-label="Cerrar">
                <X className="h-4 w-4" />
              </Button>
            </Dialog.Close>
          </div>

          <Dialog.Description id="reset-pwd-desc" className="sr-only">
            Resetear contraseña del usuario
          </Dialog.Description>

          {modalState === 'confirming' && (
            <div className="space-y-4">
              <p className="text-sm text-muted-foreground">
                ¿Estás seguro que querés resetear la contraseña de este usuario?
                Se generará una contraseña temporal y se invalidarán todas sus sesiones activas.
              </p>
              <div className="flex gap-2 justify-end">
                <Button variant="outline" onClick={handleCancel} disabled={isPending}>
                  Cancelar
                </Button>
                <Button onClick={handleConfirm} disabled={isPending}>
                  {isPending ? 'Reseteando...' : 'Confirmar'}
                </Button>
              </div>
            </div>
          )}

          {modalState === 'showing-password' && tempPassword && (
            <div className="space-y-4">
              <Alert>
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  Esta es la única vez que verás esta contraseña. Copiála ahora.
                </AlertDescription>
              </Alert>

              <div className="rounded-md border border-border bg-muted p-3">
                <p className="font-mono text-base tracking-widest select-all">{tempPassword}</p>
              </div>

              <Button
                variant="outline"
                className="w-full"
                onClick={handleCopy}
              >
                <Copy className="h-4 w-4 mr-2" />
                {copyDone ? '¡Copiado!' : 'Copiar al portapapeles'}
              </Button>

              <Button
                className="w-full"
                onClick={() => {
                  setOpen(false)
                  setModalState('idle')
                }}
              >
                Cerrar
              </Button>
            </div>
          )}

          {modalState === 'error' && (
            <div className="space-y-4">
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{errorMsg}</AlertDescription>
              </Alert>
              <div className="flex gap-2 justify-end">
                <Button variant="outline" onClick={handleCancel}>
                  Cancelar
                </Button>
                <Button onClick={() => { setModalState('confirming'); setErrorMsg(null) }}>
                  Reintentar
                </Button>
              </div>
            </div>
          )}
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}
