// app/foreign-student-login/foreign-student-login.jsx
'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import Heading from '../../../components/atoms/Heading';
import Input from '../../../components/atoms/Input';
import Button from '../../../components/atoms/Button';
import Swal from 'sweetalert2';
import { 
  FaEnvelope, 
  FaLock, 
  FaEye, 
  FaEyeSlash, 
  FaGoogle, 
  FaFacebookF,
  FaChartLine,
  FaCalendarCheck,
  FaUserFriends,
  FaComments,
  FaStar,
  FaShieldAlt,
  FaGraduationCap,
  FaGlobe,
  FaLightbulb,
  FaHandshake,
  FaCheck
} from 'react-icons/fa';
import { useUserStore } from '../../../../store/useUserStore';

export default function ForeignStudentLogin() {
  const router = useRouter();
  const [form, setForm] = useState({
    email: '',
    password: '',
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);

  const togglePasswordVisibility = () => setShowPassword(!showPassword);

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

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };

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

    // Simple frontend validation
    const newErrors = {};
    if (!form.email) newErrors.email = 'Email is required';
    if (!form.password) newErrors.password = 'Password is required';

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      setIsSubmitting(false);
      return;
    }

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

      const data = await response.json();

      if (response.ok) {
        
        setUser(data.data);

        if(data.role === "foreign-student"){
            router.push('/foreign-student-dashboard');
        } else {
            router.push("/")
        }

      } else {
        // Handle specific error cases
        let errorMessage = data.message || 'Login failed';
        
        if (response.status === 401) {
          errorMessage = 'Invalid email or password';
        } else if (response.status === 403) {
          errorMessage = 'Account is deactivated. Please contact support.';
        }

        Swal.fire({
          icon: 'error',
          title: 'Login Failed',
          text: errorMessage,
          confirmButtonColor: '#0B6D76'
        });
      }
    } catch (err) {
      console.error('Login error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Check for remembered email on component mount
  React.useEffect(() => {
    const rememberedEmail = localStorage.getItem('rememberEmail');
    if (rememberedEmail) {
      setForm(prev => ({ ...prev, email: rememberedEmail }));
      setRememberMe(true);
    }
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-teal-50 via-white to-blue-50 py-12 px-4 flex items-center justify-center">
      <div className="max-w-7xl w-full grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
        {/* Left Column - Login Form */}
        <div className="bg-white rounded-3xl shadow-2xl p-8 md:p-12 border border-gray-100">
          <div className="text-center mb-10">
            <div className="mb-4">
              <FaGraduationCap className="text-5xl text-teal-600 mx-auto" />
            </div>
            <Heading level={3} className="mb-3 text-gray-900">
              Welcome Back, <span className="text-teal-600">Global Guide!</span>
            </Heading>
            <p className="text-gray-600 text-lg">
              Access your dashboard and continue helping students achieve their study abroad dreams
            </p>
          </div>

          {/* Divider */}
          <div className="relative mb-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-6 bg-white text-gray-500 font-medium">
                Continue Your Journey
              </span>
            </div>
          </div>

          {/* Login Form */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Email Input */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Your Registered Email
              </label>
              <div className="relative">
                <Input
                  type="email"
                  name="email"
                  value={form.email}
                  onChange={handleChange}
                  placeholder="Enter your email address"
                  className="pl-12 py-3.5 text-base"
                  required
                />
                <FaEnvelope className="absolute left-4 top-3.5 text-gray-400 text-lg" />
              </div>
              {errors.email && <p className="text-sm text-red-500 mt-2">{errors.email}</p>}
            </div>

            {/* Password Input */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Your Password
              </label>
              <div className="relative">
                <Input
                  type={showPassword ? 'text' : 'password'}
                  name="password"
                  value={form.password}
                  onChange={handleChange}
                  placeholder="Enter your password"
                  className="pl-12 py-3.5 text-base"
                  required
                />
                <FaLock className="absolute left-4 top-3.5 text-gray-400 text-lg" />
                <button
                  type="button"
                  onClick={togglePasswordVisibility}
                  className="absolute right-4 top-3.5 text-gray-500 hover:text-teal-600 transition-colors"
                >
                  {showPassword ? <FaEyeSlash className="text-lg" /> : <FaEye className="text-lg" />}
                </button>
              </div>
              {errors.password && <p className="text-sm text-red-500 mt-2">{errors.password}</p>}
            </div>

            {/* Remember Me & Forgot Password */}
            <div className="flex flex-wrap items-center justify-between">
              <label className="flex items-center space-x-3 cursor-pointer group">
                <div className={`w-5 h-5 border-2 rounded flex items-center justify-center transition-colors ${rememberMe ? 'bg-teal-600 border-teal-600' : 'border-gray-300 group-hover:border-teal-500'}`}>
                  {rememberMe && <span className="text-white text-xs">✓</span>}
                </div>
                <input
                  type="checkbox"
                  checked={rememberMe}
                  onChange={(e) => setRememberMe(e.target.checked)}
                  className="hidden"
                />
                <span className="text-sm text-gray-700 group-hover:text-gray-900">Remember this device</span>
              </label>
              
              <Link 
                href="/forgot-password" 
                className="text-sm text-teal-600 hover:text-teal-700 font-medium transition-colors"
              >
                Forgot password?
              </Link>
            </div>

            {/* Submit Button */}
            <Button 
              type="submit" 
              disabled={isSubmitting}
              className="w-full py-4 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-300"
            >
              {isSubmitting ? (
                <div className="flex items-center justify-center">
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-3"></div>
                  Signing In...
                </div>
              ) : (
                '🚀 Access Your Dashboard'
              )}
            </Button>

            {/* Registration Link */}
            <div className="text-center pt-6 border-t border-gray-100">
              <p className="text-gray-600">
                New to Universities Page?{' '}
                <Link 
                  href="/foreign-students/register" 
                  className="text-teal-600 font-bold hover:text-teal-700 transition-colors hover:underline"
                >
                  Become a Foreign Student Guide
                </Link>
              </p>
              <p className="text-sm text-gray-500 mt-2">
                Start earning by sharing your study abroad experience
              </p>
            </div>
          </form>
        </div>

        {/* Right Column - Content Section */}
        <div className="space-y-10">

          {/* Dashboard Features */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white p-8 rounded-2xl shadow-lg border border-gray-100 hover:border-teal-200 transition-all duration-300">
              <div className="w-14 h-14 bg-teal-100 rounded-2xl flex items-center justify-center mb-5">
                <FaChartLine className="text-2xl text-teal-600" />
              </div>
              <h4 className="font-bold text-xl text-gray-900 mb-3">Earnings Dashboard</h4>
              <p className="text-gray-600 mb-4">
                Track your consultation earnings, pending payments, and financial growth in real-time
              </p>
              <div className="flex items-center text-sm text-teal-600 font-medium">
                <FaStar className="mr-2" />
                95% of guides earn $500+ monthly
              </div>
            </div>
            
            <div className="bg-white p-8 rounded-2xl shadow-lg border border-gray-100 hover:border-blue-200 transition-all duration-300">
              <div className="w-14 h-14 bg-blue-100 rounded-2xl flex items-center justify-center mb-5">
                <FaCalendarCheck className="text-2xl text-blue-600" />
              </div>
              <h4 className="font-bold text-xl text-gray-900 mb-3">Session Management</h4>
              <p className="text-gray-600 mb-4">
                Schedule consultations, set availability, and manage bookings with our smart calendar
              </p>
              <div className="flex items-center text-sm text-blue-600 font-medium">
                <FaUserFriends className="mr-2" />
                Average 15 sessions/week per guide
              </div>
            </div>
          </div>

          {/* Student Success Stories */}
          <div className="bg-white rounded-2xl shadow-lg p-8 border border-gray-200">
            <h3 className="text-xl font-bold text-gray-900 mb-4 flex items-center">
              <FaComments className="mr-3 text-purple-600" />
              Guides Making a Difference
            </h3>
            <div className="space-y-4">
              <div className="bg-purple-50 rounded-xl p-4">
                <p className="text-gray-700 italic mb-2">
                  "I've helped 47 students get into UK universities while earning $1,200/month. This platform changed my student life!"
                </p>
                <p className="text-sm text-gray-600 font-medium">— Sarah, MBA Student in London</p>
              </div>
              <div className="bg-teal-50 rounded-xl p-4">
                <p className="text-gray-700 italic mb-2">
                  "As an engineering student in Germany, I guide 3-4 students weekly. It's rewarding and pays my rent!"
                </p>
                <p className="text-sm text-gray-600 font-medium">— Ahmed, Engineering Student in Berlin</p>
              </div>
            </div>
            <div className="mt-6 pt-6 border-t border-gray-200 text-center">
              <p className="text-gray-600">
                Join <span className="font-bold text-teal-600">2,300+ foreign student guides</span> worldwide
              </p>
              <p className="text-sm text-gray-500 mt-1">
                Your experience is valuable. Share it and earn.
              </p>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}