'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import Heading from '../../components/atoms/Heading';
import { FcGoogle } from "react-icons/fc";
import { FaGithub, FaLinkedinIn, FaEye, FaEyeSlash, FaRocket, FaUserGraduate } from 'react-icons/fa';
import Button from '../../components/atoms/Button';
import { signIn } from 'next-auth/react';
import Swal from 'sweetalert2';
import Link from "next/link";
import {useUserStore} from '../../../store/useUserStore';
import toast from 'react-hot-toast';
import Image from "next/image";
import { Loader2, Star, Users, Target, CheckCircle } from 'lucide-react';

export default function LoginForm() {
  const setUser = useUserStore((state) => state.setUser);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [form, setForm] = useState({ email: '', password: '' });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleGoogleLogin = () => {
    window.location.href = "/api/frontend/login/auth/google/";
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {

      const redirectValue = searchParams.get("redirect") || "no-redirect";

      setIsSubmitting(true)

      const response = await fetch("/api/frontend/login/", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify(form)
      })

      if(!response.ok) {
        const errorData = await response.json();
        const errorMessages = errorData.message;

        Swal.fire({
          icon: 'error',
          title: 'Authentication Failed',
          text: errorMessages || 'An error occurred',
          confirmButtonColor: '#0a306b',
        });

        setIsSubmitting(false)
        return;
      }

      const data = await response.json();
      setUser(data.data);

      const wishlist = JSON.parse(localStorage.getItem('wishlist')) || [];

      if (wishlist.length > 0) {
        const wishdata = { items: wishlist };
        await fetch('/api/frontend/wishlist', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(wishdata),
        });
      }

      toast.success(data.message);

      if (data.role === "admin") {
        router.push("/admin");
      } else {
        if (redirectValue !== "no-redirect") {
          const formatted = redirectValue.trim().replace(/\s+/g, "-");
          router.push(`/university/${formatted}`);
        } else {
          router.push("/dashboard");
        }
      }

    } catch {
      setIsSubmitting(false)
    } finally {
      setIsSubmitting(false);
    }
  }

  const features = [
    { icon: "", text: "Secure & Encrypted Login" },
    { icon: <FaUserGraduate className="text-white" />, text: "Personalized Dashboard" },
    { icon: <Target className="text-white" size={16} />, text: "Track Your Progress" },
    { icon: <Users className="text-white" size={16} />, text: "Join 50k+ Students" }
  ];

  return (
    <div className="min-h-screen flex items-center justify-center px-4 bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50 relative overflow-hidden">
      {/* Background Pattern */}
     
      <div className="grid grid-cols-1 lg:grid-cols-2 max-w-7xl w-full items-center gap-8 rounded-3xl bg-white shadow-2xl p-6 md:p-8 relative z-10">
        {/* Enhanced Image Section */}
        <div className="relative hidden lg:block">
          <div className={`absolute -left-6 top-1/2 -translate-y-1/2 h-4/5 w-6 bg-gradient-to-b from-[#0a306b] to-[#1e4a8e] rounded-r-2xl z-10 transition-all duration-500 ${isHovered ? 'scale-110' : ''}`}></div>
          
          <div 
            className="relative rounded-2xl overflow-hidden shadow-2xl transform transition-all duration-500 hover:scale-105"
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
          >
        <Image
  src="/assets/auth.jpg"
  alt="Learning Platform"
  width={1920}   // actual image width in pixels
  height={600}   // actual image height in pixels
  className="w-full h-[600px] object-cover"
/>
            
            {/* Overlay Content */}
            <div className="absolute inset-0 bg-gradient-to-t from-[#0a306b]/90 via-[#0a306b]/50 to-transparent">
              <div className="absolute bottom-0 left-0 right-0 p-8 text-white">
                <div className="flex items-center mb-4">
                  <Star className="fill-yellow-400 text-yellow-400 mr-2" />
                  <span className="font-semibold">Rated 4.9/5 by Students</span>
                </div>
                <h3 className="text-3xl font-bold mb-3">Transform Your Learning Journey</h3>
                <p className="text-lg opacity-90 mb-6">Access premium courses, track your progress, and achieve academic excellence</p>
                
                {/* Features List */}
                <div className="grid grid-cols-2 gap-3 mb-6">
                  {features.map((feature, index) => (
                    <div key={index} className="flex items-center space-x-2">
                      <div className="w-6 h-6 bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full flex items-center justify-center">
                        {feature.icon}
                      </div>
                      <span className="text-sm">{feature.text}</span>
                    </div>
                  ))}
                </div>

                {/* Stats */}
                <div className="flex space-x-6 text-center">
                  <div>
                    <div className="text-2xl font-bold">40k+</div>
                    <div className="text-sm opacity-90">Active Students</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold">95%</div>
                    <div className="text-sm opacity-90">Success Rate</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold">24/7</div>
                    <div className="text-sm opacity-90">Support</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Enhanced Form Section */}
        <div className="w-full">
          <div className="text-center lg:text-left mb-8">
            <div className="flex items-center justify-center lg:justify-start space-x-3 mb-4">
              <div className="w-12 h-12 bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] rounded-xl flex items-center justify-center">
                <FaRocket className="text-white text-xl" />
              </div>
              <Heading level={2} className="font-bold text-4xl bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] bg-clip-text text-transparent">
                Welcome Back
              </Heading>
            </div>
            <p className="text-gray-600 text-lg">
              Sign in to your {pathname.includes('/admin') ? 'admin' : 'student'} dashboard
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Email Field */}
            <div className="relative group">
              <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none transition-transform duration-200 group-focus-within:scale-110">
                <svg className="h-5 w-5 text-gray-400 group-focus-within:text-[#0a306b]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
                </svg>
              </div>
              <input
                type="email"
                name="email"
                value={form.email}
                onChange={handleChange}
                required
                className="w-full pl-12 pr-4 py-4 rounded-xl bg-gray-50 border border-gray-200 text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#0a306b] focus:border-transparent transition-all duration-200 text-gray-800 group-hover:bg-gray-100"
                placeholder="Enter your email address"
              />
            </div>

            {/* Password Field */}
            <div className="relative group">
              <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none transition-transform duration-200 group-focus-within:scale-110">
                <svg className="h-5 w-5 text-gray-400 group-focus-within:text-[#0a306b]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              </div>
              <input
                type={showPassword ? 'text' : 'password'}
                name="password"
                value={form.password}
                onChange={handleChange}
                required
                className="w-full pl-12 pr-12 py-4 rounded-xl bg-gray-50 border border-gray-200 text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#0a306b] focus:border-transparent transition-all duration-200 text-gray-800 group-hover:bg-gray-100"
                placeholder="Enter your password"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-[#0a306b] transition-colors duration-200"
              >
                {showPassword ? <FaEyeSlash size={18} /> : <FaEye size={18} />}
              </button>
            </div>

            {/* Remember Me & Forgot Password */}
            <div className="flex justify-between items-center text-sm">
              <label className="flex items-center text-gray-700 gap-2 cursor-pointer group">
                <div className="relative">
                  <input type="checkbox" className="sr-only peer" />
                  <div className="w-4 h-4 rounded border border-gray-300 peer-checked:bg-[#0a306b] peer-checked:border-[#0a306b] transition-colors duration-200 group-hover:border-[#0a306b]"></div>
                  <CheckCircle className="absolute top-0 left-0 text-white opacity-0 peer-checked:opacity-100 transition-opacity duration-200" size={16} />
                </div>
                <span className="group-hover:text-gray-900 transition-colors duration-200">Remember Me</span>
              </label>
              <Link href="forgot-password" type="button" className="text-[#0a306b] hover:text-[#1e4a8e] font-medium transition-colors duration-200">
                Forgot Password?
              </Link>
            </div>

            {/* Submit Button */}
            <Button 
              type="submit" 
              disabled={isSubmitting} 
              className="w-full py-4 rounded-xl font-semibold text-white bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] hover:from-[#1e4a8e] hover:to-[#0a306b] transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105 disabled:hover:scale-100"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="animate-spin mr-2" size={20} />
                  Signing In...
                </>
              ) : (
                'Sign In to Dashboard'
              )}
            </Button>

            {/* Divider */}
            <div className="relative my-8">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-gray-300"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-4 bg-white text-gray-500 font-medium">Or continue with</span>
              </div>
            </div>

            {/* Social Login */}
            <div className="grid grid-cols-1 gap-3">
              <button
                type="button"
                onClick={handleGoogleLogin}
                className="flex items-center justify-center gap-3 bg-white border border-gray-300 rounded-xl py-3 px-4 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-all duration-200 shadow-sm hover:shadow-md transform hover:scale-105"
              >
                <FcGoogle size={20} /> 
                <span>Continue with Google</span>
              </button>
              
            </div>

            {/* Registration Link */}
            <p className="text-sm text-center text-gray-600 mt-8">
              Don&apos;t have an account?{' '}
              <button
                type="button"
                onClick={() => router.push(pathname.includes('/admin') ? '/admin-register' : '/student-register')}
                className="text-[#0a306b] font-semibold hover:text-[#1e4a8e] transition-colors duration-200 underline"
              >
                {pathname.includes('/admin') ? 'Register As Admin' : 'Register As Student'}
              </button>
            </p>
          </form>

          {/* Security Badge */}
          <div className="mt-8 p-4 bg-gradient-to-r from-green-50 to-emerald-50 rounded-xl border border-green-200">
            <div className="flex items-center justify-center space-x-2 text-sm text-green-700">
              
              <span>Your login is secure and encrypted</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}