import { useNavigate } from 'react-router-dom'
import { isAxiosError } from 'axios'
import { AlertCircle, Newspaper } from 'lucide-react'
import { useLogin } from '../hooks/useLogin'
import { LoginForm } from '../components/LoginForm'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Alert, AlertDescription } from '@/components/ui/alert'

function resolveErrorMessage(err: unknown): string | null {
  if (!err) return null
  if (isAxiosError(err) && err.response?.data) {
    const data = err.response.data as { error?: string }
    return data.error ?? 'Error al iniciar sesión'
  }
  return 'Error al iniciar sesión'
}

export function LoginPage() {
  const navigate = useNavigate()
  const { mutate, isPending, error } = useLogin()

  function handleSubmit(username: string, password: string) {
    mutate(
      { username, password },
      {
        onSuccess: () => {
          void navigate('/')
        },
      },
    )
  }

  const errorMessage = resolveErrorMessage(error)

  return (
    <Card variant="glass" className="w-full max-w-md">
      <CardHeader className="space-y-3 text-center pb-2">
        {/* Brand mark */}
        <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 to-violet-500 shadow-lg shadow-brand-500/30">
          <Newspaper className="h-6 w-6 text-white" strokeWidth={2.25} />
        </div>
        <CardTitle className="text-2xl tracking-tight">SIG-CM 2.0</CardTitle>
        <CardDescription className="text-sm">
          Sistema de gestión comercial · El Día
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4 pt-4">
        {errorMessage && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{errorMessage}</AlertDescription>
          </Alert>
        )}
        <LoginForm onSubmit={handleSubmit} isLoading={isPending} />
      </CardContent>
    </Card>
  )
}
