'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Heading from '../../components/atoms/Heading';
import { FcGoogle } from "react-icons/fc";
import { FaUserTie, FaEye, FaEyeSlash, FaGlobe, FaGraduationCap, FaCheck, FaShieldAlt, FaUsers, FaRocket } from 'react-icons/fa';
import Button from '../../components/atoms/Button';
import Swal from 'sweetalert2';
import Link from 'next/link';
import Image from "next/image";
import { Loader2, Building2, Target, Users, CheckCircle, Globe, Award, BookOpen } from 'lucide-react';
import { useUserStore } from '../../../store/useUserStore';

export default function LoginForm() {
  const router = useRouter();
  const [form, setForm] = useState({
    email: '',
    password: ''
  });
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  const setUser = useUserStore((state) => state.setUser);

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

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

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

    try {
      // Enhanced email validation
      if (!form.email || !form.email.trim()) {
        Swal.fire({
          icon: 'error',
          title: 'Email Required',
          text: 'Please enter your email address.',
          confirmButtonColor: '#0a306b'
        });
        setIsSubmitting(false);
        return;
      }

      // Check email format
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(form.email.trim())) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid Email Format',
          text: 'Please enter a valid email address (e.g., user@example.com).',
          confirmButtonColor: '#0a306b'
        });
        setIsSubmitting(false);
        return;
      }

      // Enhanced password validation
      if (!form.password || !form.password.trim()) {
        Swal.fire({
          icon: 'error',
          title: 'Password Required',
          text: 'Please enter your password.',
          confirmButtonColor: '#0a306b'
        });
        setIsSubmitting(false);
        return;
      }

      // Check password length
      if (form.password.trim().length < 1) {
        Swal.fire({
          icon: 'error',
          title: 'Password Too Short',
          text: 'Password must be at least 1 character long.',
          confirmButtonColor: '#0a306b'
        });
        setIsSubmitting(false);
        return;
      }

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

      if(!response.ok){
        const data = await response.json();

        Swal.fire({
          icon: 'error',
          title: 'Login Failed',
          text: data.message || 'Login failed. Please try again.',
          confirmButtonColor: '#0a306b'
        });

        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),
        });
      }

      if(data.role === "consultant"){
        router.push('/consultant-dashboard');
      } else {
        router.push("/")
      }
      
    } catch (err) {
      console.error('Login error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Something went wrong, please try again later',
        text: 'An unexpected error occurred. Please try again.',
        confirmButtonColor: '#0a306b'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const platformBenefits = [
    { icon: <FaRocket className="text-blue-500" />, title: "AI-Powered Search", desc: "Get discovered by students through our smart AI search engine" },
    { icon: <FaUsers className="text-green-500" />, title: "Global Student Network", desc: "Connect with thousands of students worldwide" },
    { icon: <FaGraduationCap className="text-purple-500" />, title: "University Partnerships", desc: "Access exclusive partnerships with top universities" },
    { icon: <FaShieldAlt className="text-amber-500" />, title: "Verified Profile", desc: "Build trust with verified consultant status" },
    { icon: <Target className="text-red-500" size={16} />, title: "Student Management", desc: "Track applications and student progress in one dashboard" },
    { icon: <Globe className="text-teal-500" size={16} />, title: "International Reach", desc: "Expand your consultancy beyond local boundaries" }
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50 py-12 px-4">
      <div className="max-w-6xl mx-auto">
        {/* Header Section */}
        <div className="text-center mb-12">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="w-16 h-16 bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] rounded-2xl flex items-center justify-center shadow-lg">
              <FaUserTie className="text-white text-2xl" />
            </div>
            <div className="text-left">
              <h1 className="text-4xl font-bold text-gray-900">
                Welcome to <span className="text-[#0a306b]">UniversitiesPage</span>
              </h1>
              <p className="text-lg text-gray-600">Study Abroad Consultant Portal</p>
            </div>
          </div>
          <p className="text-xl text-gray-700 max-w-3xl mx-auto">
            Access your professional consultant dashboard to manage student applications, track progress, 
            and grow your study abroad consultancy business
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Side - Benefits & Features */}
          <div className="lg:col-span-1 bg-white rounded-2xl shadow-xl p-8">
            <div className="flex items-center gap-3 mb-8">
              <div className="p-3 bg-blue-100 rounded-xl">
                <Award className="text-blue-600" size={24} />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Why Join Our Network?</h2>
                <p className="text-gray-600">Top reasons to partner with UniversitiesPage</p>
              </div>
            </div>

            <div className="space-y-6">
              {platformBenefits.map((benefit, index) => (
                <div key={index} className="flex items-start space-x-4 p-4 bg-gray-50 hover:bg-blue-50 rounded-xl transition-all duration-300 group hover:shadow-md">
                  <div className="p-2 bg-white rounded-lg shadow-sm group-hover:scale-110 transition-transform">
                    {benefit.icon}
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900">{benefit.title}</h3>
                    <p className="text-sm text-gray-600">{benefit.desc}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* Stats Section */}
            <div className="mt-8 p-6 bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] rounded-2xl text-white">
              <h3 className="font-bold text-xl mb-4">Our Consultant Network</h3>
              <div className="grid grid-cols-2 gap-4">
                <div className="text-center">
                  <div className="text-3xl font-bold">500+</div>
                  <div className="text-sm opacity-90">Verified Consultants</div>
                </div>
                <div className="text-center">
                  <div className="text-3xl font-bold">50K+</div>
                  <div className="text-sm opacity-90">Students Helped</div>
                </div>
                <div className="text-center">
                  <div className="text-3xl font-bold">95%</div>
                  <div className="text-sm opacity-90">Success Rate</div>
                </div>
                <div className="text-center">
                  <div className="text-3xl font-bold">24/7</div>
                  <div className="text-sm opacity-90">Support</div>
                </div>
              </div>
            </div>

            {/* Registration CTA */}
            <div className="mt-8 p-6 bg-gradient-to-r from-green-50 to-emerald-100 border border-green-200 rounded-2xl">
              <h3 className="font-bold text-gray-900 mb-3">New to UniversitiesPage?</h3>
              <p className="text-gray-600 mb-4">
                Join our exclusive network of study abroad consultants and reach students worldwide.
              </p>
              <button
                onClick={() => router.push('/consultant-register')}
                className="w-full py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white font-semibold rounded-xl hover:from-green-700 hover:to-emerald-700 transition-all duration-300"
              >
                Register As Consultant
              </button>
            </div>
          </div>

          {/* Center - Login Form */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-2xl shadow-xl p-8">
              <div className="flex items-center mb-8">
                <div className="p-3 bg-gradient-to-r from-[#0a306b] to-[#1e4a8e] rounded-xl mr-4">
                  <BookOpen className="text-white text-2xl" />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">Consultant Login</h2>
                  <p className="text-gray-600">Sign in to access your professional dashboard</p>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Email Field */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <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>
                    Professional Email *
                  </label>
                  <div className="relative group">
                    <input
                      type="email"
                      name="email"
                      value={form.email}
                      onChange={handleChange}
                      required
                      className="w-full px-4 py-3 pl-12 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0a306b] focus:border-[#0a306b] transition-all duration-200 text-gray-800 hover:bg-gray-100"
                      placeholder="Enter your registered email"
                    />
                    <div className="absolute left-4 top-1/2 transform -translate-y-1/2">
                      <svg className="w-5 h-5 text-gray-400 group-focus-within:text-[#0a306b]" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                      </svg>
                    </div>
                  </div>
                </div>

                {/* Password Field */}
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <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>
                    Password *
                  </label>
                  <div className="relative group">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      name="password"
                      value={form.password}
                      onChange={handleChange}
                      required
                      className="w-full px-4 py-3 pl-12 pr-12 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#0a306b] focus:border-[#0a306b] transition-all duration-200 text-gray-800 hover:bg-gray-100"
                      placeholder="Enter your password"
                    />
                    <div className="absolute left-4 top-1/2 transform -translate-y-1/2">
                      <svg className="w-5 h-5 text-gray-400 group-focus-within:text-[#0a306b]" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
                      </svg>
                    </div>
                    <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>
                </div>

                {/* Remember Me & Forgot Password */}
                <div className="flex justify-between items-center">
                  <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-5 h-5 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={20} />
                    </div>
                    <span className="group-hover:text-gray-900 transition-colors duration-200">Remember me</span>
                  </label>
                  <Link href={"/forgot-password"}>
                    <button type="button" className="text-[#0a306b] hover:text-[#1e4a8e] font-medium transition-colors duration-200">
                      Forgot Password?
                    </button>
                  </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...
                    </>
                  ) : (
                    'Access Consultant Dashboard'
                  )}
                </Button>

                {/* Divider */}
                <div className="relative my-6">
                  <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="w-full flex items-center justify-center gap-2 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"
                  >
                    <FcGoogle size={20} />
                    <span>Continue with Google</span>
                  </button>
                </div>

                {/* Registration Link */}
                <div className="text-center pt-6 border-t border-gray-200">
                  <p className="text-gray-600">
                    Don&apos;t have a consultant account?{' '}
                    <button
                      type="button"
                      onClick={() => router.push('/consultant-register')}
                      className="text-[#0a306b] font-semibold hover:text-[#1e4a8e] transition-colors duration-200 underline"
                    >
                      Register Now
                    </button>
                  </p>
                </div>
              </form>

              {/* Security Badge */}
              <div className="mt-8 p-4 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-200">
                <div className="flex items-center justify-center space-x-2 text-sm text-blue-700">
                  <FaShieldAlt />
                  <span>Your account is protected with enterprise-grade security & encryption</span>
                </div>
              </div>
            </div>

            {/* Approval Process Info */}
            <div className="mt-6 bg-gradient-to-r from-amber-50 to-yellow-50 border border-amber-200 rounded-2xl p-6">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-amber-100 rounded-xl">
                  <CheckCircle className="text-amber-600" size={24} />
                </div>
                <div>
                  <h3 className="font-bold text-gray-900 mb-2">Profile Approval Process</h3>
                  <p className="text-gray-700 mb-3">
                    After registration, complete your profile with service details, languages, and specializations. 
                    Our team will review and approve your account within 24-48 hours.
                  </p>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">1</div>
                      <span className="text-gray-600">Register Account</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">2</div>
                      <span className="text-gray-600">Complete Profile</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">3</div>
                      <span className="text-gray-600">Get Approved & Listed</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Footer Note */}
        <div className="mt-8 text-center text-sm text-gray-500">
          <p>
            UniversitiesPage is a leading study abroad platform connecting verified consultants with students worldwide. 
            All consultant profiles undergo strict verification before being listed in our AI search engine.
          </p>
        </div>
      </div>
    </div>
  );
}