import { createFileRoute, redirect } from "@tanstack/react-router"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { Mail, Lock, Eye, EyeOff, Loader2, Shield } from "lucide-react"

export const Route = createFileRoute("/login")({
  validateSearch: (search) => ({
    redirect: (search.redirect as string) || "/dashboard",
  }),
  beforeLoad: ({ context, search }) => {
    if (context.auth.isAuthenticated) {
      throw redirect({ to: search.redirect })
    }
  },
  component: LoginComponent,
})

function LoginComponent() {
  const { auth } = Route.useRouteContext()
  const { redirect } = Route.useSearch()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [showPassword, setShowPassword] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError("")

    try {
      await auth.login(email, password)
      window.location.href = redirect
    } catch (err: any) {
      setError(err.message || "No fue posible iniciar sesión")
    } finally {
      setIsLoading(false)
    }
  }
  

  return (
    <div className="min-h-screen w-full grid place-items-center px-4 bg-background text-foreground relative overflow-hidden">
      {/* Auroras decorativas claras */}
      <div className="pointer-events-none absolute inset-0 [mask-image:radial-gradient(50%_50%_at_50%_50%,black,transparent)]">
        <div className="absolute -top-32 -left-24 h-80 w-80 rounded-full bg-primary/15 blur-3xl" />
        <div className="absolute -bottom-24 -right-16 h-72 w-72 rounded-full bg-secondary/30 blur-3xl" />
      </div>

      <Card className="w-full max-w-md border border-border bg-card shadow-xl rounded-2xl backdrop-blur-sm">
        <CardHeader className="space-y-1 text-center">
          <div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-2xl bg-muted">
            <Shield className="h-6 w-6 text-foreground" aria-hidden />
          </div>
          <CardTitle className="font-mono text-2xl">Iniciar sesión</CardTitle>
          <CardDescription className="text-muted-foreground">
            Accede a tu panel para gestionar planes y materias
          </CardDescription>
        </CardHeader>

        <CardContent>
          {error && (
            <div role="alert" className="mb-4 rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Email */}
            <div className="grid gap-2">
              <Label htmlFor="email">Correo institucional</Label>
              <div className="relative">
                <div className="pointer-events-none absolute inset-y-0 left-0 flex w-10 items-center justify-center">
                  <Mail className="h-4 w-4 text-muted-foreground" aria-hidden />
                </div>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10"
                  placeholder="usuario@lasalle.mx"
                  autoComplete="email"
                  required
                />
              </div>
            </div>

            {/* Password */}
            <div className="grid gap-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="password">Contraseña</Label>
                <a
                  href="/reset-password"
                  className="text-xs text-muted-foreground underline-offset-4 hover:underline"
                >
                  ¿Olvidaste tu contraseña?
                </a>
              </div>
              <div className="relative">
                <div className="pointer-events-none absolute inset-y-0 left-0 flex w-10 items-center justify-center">
                  <Lock className="h-4 w-4 text-muted-foreground" aria-hidden />
                </div>
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pl-10 pr-10"
                  autoComplete="current-password"
                  required
                />
                <button
                  type="button"
                  aria-label={showPassword ? "Ocultar contraseña" : "Mostrar contraseña"}
                  onClick={() => setShowPassword((s) => !s)}
                  className="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-muted-foreground hover:text-foreground/80"
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            <Button type="submit" disabled={isLoading} className="w-full font-mono" size="lg">
              {isLoading ? (
                <span className="inline-flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" /> Iniciando…
                </span>
              ) : (
                "Entrar"
              )}
            </Button>

            <Separator className="my-2" />
            <p className="text-center text-xs text-muted-foreground">
              Al continuar aceptas nuestros <a href="#" className="underline underline-offset-4">Términos</a> y <a href="#" className="underline underline-offset-4">Política de privacidad</a>.
            </p>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}