
"use client";

import { useState } from "react";
import { signIn, getSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { Lock, Mail, ArrowLeft } from "lucide-react";
import Link from "next/link";
import Image from "next/image";

export default function AdminLoginPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });

  const router = useRouter();
  const { toast } = useToast();

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

    try {
      const result = await signIn("credentials", {
        email: formData.email,
        password: formData.password,
        redirect: false,
      });

      if (result?.error) {
        toast({
          title: "Error de autenticación",
          description: "Credenciales inválidas. Verifica tu email y contraseña.",
          variant: "destructive",
        });
      } else {
        // Verificar la sesión para obtener el rol
        const session = await getSession();
        
        if (session?.user?.rol === 'admin') {
          toast({
            title: "¡Bienvenido!",
            description: "Has iniciado sesión exitosamente.",
          });
          router.push("/admin/dashboard");
        } else {
          toast({
            title: "Acceso denegado",
            description: "No tienes permisos de administrador.",
            variant: "destructive",
          });
        }
      }
    } catch (error) {
      toast({
        title: "Error",
        description: "Hubo un problema al iniciar sesión. Inténtalo nuevamente.",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#0A2240] to-[#2C3E50] flex items-center justify-center py-12">
      <div className="container-custom">
        <div className="max-w-md mx-auto">
          {/* Back to home link */}
          <div className="text-center mb-8">
            <Link 
              href="/"
              className="inline-flex items-center text-white hover:text-[#00B8D4] mb-6"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Volver al inicio
            </Link>
          </div>

          {/* Login Card */}
          <div className="bg-white rounded-lg shadow-xl p-8">
            {/* Logo and Title */}
            <div className="text-center mb-8">
              <div className="relative h-16 w-16 mx-auto mb-4">
                <Image
                  src="/favicon.svg"
                  alt="Escuelas Deportivas Chile"
                  fill
                  className="object-contain"
                />
              </div>
              <h1 className="heading-primary text-2xl text-[#0A2240] mb-2">
                Panel de Administración
              </h1>
              <p className="text-gray-600">
                Ingresa tus credenciales para continuar
              </p>
            </div>

            {/* Login Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                  <Input
                    type="email"
                    required
                    value={formData.email}
                    onChange={(e) => setFormData({...formData, email: e.target.value})}
                    placeholder="admin@escuelasdeportivaschile.cl"
                    className="pl-10"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Contraseña
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                  <Input
                    type="password"
                    required
                    value={formData.password}
                    onChange={(e) => setFormData({...formData, password: e.target.value})}
                    placeholder="••••••••"
                    className="pl-10"
                  />
                </div>
              </div>

              <Button
                type="submit"
                disabled={isLoading}
                className="w-full bg-[#00B8D4] hover:bg-[#0097A7] text-white py-3 rounded-lg font-semibold"
              >
                {isLoading ? "Iniciando sesión..." : "Iniciar Sesión"}
              </Button>
            </form>

            <div className="mt-6 text-center text-sm text-gray-500">
              Solo personal autorizado puede acceder a esta área
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
