"use client";
import Checkbox from "@/components/form/input/Checkbox";
import Input from "@/components/form/input/InputField";
import Label from "@/components/form/Label";
import Button from "@/components/ui/button/Button";
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "@/icons";
import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { signIn, getSession } from "next-auth/react";
import { useRouter } from "next/navigation";

export default function SignInForm() {
  const [showPassword, setShowPassword] = useState(false);
  const [isChecked, setIsChecked] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleSignIn = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setErrorMsg("");
    const formData = new FormData(e.target as HTMLFormElement);
    const email = formData.get("email") as string;
    const password = formData.get("password") as string;

    const res = await signIn("credentials", {
      email,
      password,
      redirect: false,
    });

    if (res?.error) {
      setLoading(false);
      setErrorMsg("Credenciales incorrectas. Verifica tu correo y contraseña.");
    } else {
      const session = await getSession();
      setLoading(false);
      
      const role = session?.user?.role;
      if (role === "ESTUDIANTE") {
        router.push("/estudiante");
      } else if (role === "PROFESOR") {
        router.push("/profesor");
      } else {
        router.push("/dashboard");
      }
    }
  };

  return (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full">
      <div className="w-full max-w-md sm:pt-10 mx-auto mb-5">
        <Link
          href="/"
          className="inline-flex items-center text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
        >
          <ChevronLeftIcon />
          Volver al sitio
        </Link>
      </div>
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          {/* Logo / Brand */}
          <div className="mb-7 sm:mb-9">
            <div className="flex justify-center mb-6">
               <Image src="/images/logo/logo.png" alt="CursosNirgua Logo" width={64} height={64} className="object-contain drop-shadow-md" />
            </div>
            <h1 className="mb-1 font-bold text-gray-800 text-2xl sm:text-3xl dark:text-white/90">
              Bienvenido de vuelta
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Ingresa tus credenciales para acceder al panel.
            </p>
          </div>

          <div>
            <form onSubmit={handleSignIn}>
              <div className="space-y-5">

                {errorMsg && (
                  <div className="p-3 bg-red-50 border border-red-200 text-red-600 rounded-lg text-sm font-medium flex items-center gap-2">
                    <span>⚠️</span> {errorMsg}
                  </div>
                )}

                <div>
                  <Label>
                    Correo Electrónico <span className="text-error-500">*</span>
                  </Label>
                  <Input name="email" placeholder="info@cursos.nirgua.com.ve" type="email" />
                </div>

                <div>
                  <Label>
                    Contraseña <span className="text-error-500">*</span>
                  </Label>
                  <div className="relative">
                    <Input
                      name="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Tu contraseña"
                    />
                    <span
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2"
                    >
                      {showPassword ? (
                        <EyeIcon />
                      ) : (
                        <EyeCloseIcon />
                      )}
                    </span>
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Checkbox checked={isChecked} onChange={setIsChecked} />
                    <span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
                      Mantener sesión activa
                    </span>
                  </div>
                  <Link
                    href="/recover"
                    className="text-sm text-[#1e2a47] hover:text-[#f04b50] font-medium dark:text-brand-400 transition-colors"
                  >
                    ¿Olvidaste tu contraseña?
                  </Link>
                </div>

                <div>
                  <button
                    type="submit"
                    disabled={loading}
                    className="w-full bg-[#1e2a47] hover:bg-[#f04b50] disabled:opacity-60 text-white font-bold py-3.5 rounded-xl transition-all duration-300 flex items-center justify-center gap-2 shadow-md"
                  >
                    {loading ? (
                      <>
                        <span className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        Ingresando...
                      </>
                    ) : (
                      "Ingresar al Panel"
                    )}
                  </button>
                </div>
              </div>
            </form>

            <div className="mt-6 pt-6 border-t border-gray-100">
              <p className="text-xs text-center text-gray-400">
                ¿Problemas para acceder? Contacta al administrador en{" "}
                <a href="mailto:info@cursos.nirgua.com.ve" className="text-[#1e2a47] font-medium hover:underline">
                  info@cursos.nirgua.com.ve
                </a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
