import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { isAxiosError } from 'axios'
import { toast } from 'sonner'
import { AlertCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { useChangeMyPassword } from '../hooks/useChangeMyPassword'
import { useAuthStore } from '@/stores/authStore'

export function ChangeMyPasswordPage() {
  const navigate = useNavigate()
  const { mutate, isPending } = useChangeMyPassword()
  const updateUser = useAuthStore((s) => s.updateUser)

  const [oldPassword, setOldPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [clientError, setClientError] = useState<string | null>(null)
  const [serverError, setServerError] = useState<string | null>(null)

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setClientError(null)
    setServerError(null)

    if (newPassword !== confirmPassword) {
      setClientError('Las contraseñas no coinciden')
      return
    }

    mutate(
      { oldPassword, newPassword },
      {
        onSuccess: () => {
          // Clear mustChangePassword flag in store
          updateUser({ mustChangePassword: false })
          toast.success('Contraseña actualizada correctamente')
          navigate('/')
        },
        onError: (err) => {
          if (isAxiosError(err) && err.response?.data) {
            const data = err.response.data as { error?: string; title?: string }
            if (data.error === 'invalid-old-password' || data.title === 'invalid-old-password') {
              setServerError('La contraseña actual es incorrecta')
              return
            }
          }
          setServerError('Error al cambiar la contraseña. Intentá nuevamente.')
        },
      },
    )
  }

  return (
    <div className="max-w-md mx-auto space-y-6">
      <h1 className="text-xl font-semibold">Cambiar contraseña</h1>

      <form onSubmit={handleSubmit} className="space-y-4" noValidate>
        {clientError && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{clientError}</AlertDescription>
          </Alert>
        )}

        {serverError && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{serverError}</AlertDescription>
          </Alert>
        )}

        <div className="space-y-1">
          <Label htmlFor="oldPassword">Contraseña actual</Label>
          <Input
            id="oldPassword"
            type="password"
            value={oldPassword}
            onChange={(e) => setOldPassword(e.target.value)}
            disabled={isPending}
            autoComplete="current-password"
            aria-label="Contraseña actual"
          />
        </div>

        <div className="space-y-1">
          <Label htmlFor="newPassword">Nueva contraseña</Label>
          <Input
            id="newPassword"
            type="password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            disabled={isPending}
            autoComplete="new-password"
            aria-label="Nueva contraseña"
          />
        </div>

        <div className="space-y-1">
          <Label htmlFor="confirmPassword">Confirmar nueva contraseña</Label>
          <Input
            id="confirmPassword"
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            disabled={isPending}
            autoComplete="new-password"
            aria-label="Confirmar contraseña"
          />
        </div>

        <Button type="submit" disabled={isPending} className="w-full">
          {isPending ? 'Cambiando...' : 'Cambiar contraseña'}
        </Button>
      </form>
    </div>
  )
}
