"use client";

import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ShieldCheck, ArrowRight } from "lucide-react";

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

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

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

      if (res?.error) {
        setError("Invalid email or password");
        setLoading(false);
        return;
      }

      // Fetch the updated session to determine role
      const sessionRes = await fetch("/api/auth/session");
      const session = await sessionRes.json();
      
      if (session?.user?.role === "admin") {
        router.push("/fr/admin");
      } else {
        router.push("/fr/cart");
      }
      router.refresh();
    } catch (err) {
      setError("An error occurred during login");
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-muted/30 pt-32 pb-24 flex flex-col items-center justify-center">
      
      <div className="mb-8 flex items-center justify-center">
        <div className="font-black text-4xl tracking-tighter flex items-center text-foreground">
          <span>K </span>
          <span className="mx-2 text-brand-accent">CREATION</span>
        </div>
      </div>

      <div className="w-full max-w-md bg-card rounded-xl border border-border/50 p-8 shadow-sm">
        <h1 className="text-3xl font-black text-foreground mb-6">Connexion</h1>
        
        {error && (
          <div className="bg-red-50 dark:bg-red-900/20 text-red-600 border border-red-200 dark:border-red-800 p-4 rounded-md mb-6 text-sm flex items-center gap-2">
            <ShieldCheck className="w-5 h-5 flex-shrink-0" />
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-1">E-mail ou numéro de téléphone</label>
            <input 
              type="email" 
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-brand-accent focus:border-transparent text-foreground" 
            />
          </div>
          <div>
            <div className="flex justify-between items-center mb-1">
              <label className="block text-sm font-bold text-gray-700 dark:text-gray-300">Mot de passe</label>
              <Link href="#" className="text-xs text-brand-accent hover:underline">Mot de passe oublié ?</Link>
            </div>
            <input 
              type="password" 
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full bg-white dark:bg-black/40 border border-gray-300 dark:border-white/10 rounded-md px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-brand-accent focus:border-transparent text-foreground" 
            />
          </div>

          <button 
            type="submit" 
            disabled={loading}
            className="w-full bg-brand-accent hover:bg-red-700 text-white py-2.5 rounded-md font-bold transition-colors shadow-sm disabled:opacity-50 mt-4"
          >
            {loading ? "Connexion en cours..." : "Continuer"}
          </button>
        </form>

        <div className="mt-6 text-xs text-gray-500">
          En continuant, vous acceptez les Conditions d'utilisation et la Notice de confidentialité de K-Creation.
        </div>
      </div>

      <div className="w-full max-w-md mt-6 relative flex items-center justify-center">
        <div className="absolute w-full border-t border-border/50"></div>
        <span className="relative bg-muted/30 px-4 text-xs text-gray-500 font-medium">Nouveau sur K-Creation ?</span>
      </div>

      <div className="w-full max-w-md mt-4">
        <Link 
          href="/register"
          className="w-full bg-card hover:bg-muted text-foreground border border-border/50 py-2.5 rounded-md font-medium text-sm transition-colors shadow-sm flex items-center justify-center"
        >
          Créer votre compte K-Creation
        </Link>
      </div>

    </div>
  );
}
